File:  [LON-CAPA] / loncom / publisher / loncfile.pm
Revision 1.129: download - view: text, annotated - select for diffs
Tue May 21 02:57:16 2024 UTC (5 weeks, 6 days ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Bug 6990. Ability to download tarball of Authoring Space's files/directories.
  - Support use of domain default and also override for individual author(s).
  - Check if there is sufficient disk space to create archive file
  - Each author may only have one archive request in process at a time
  - Remove archive file after download
  - Log archive creation and deletion actions in nohist_archivelog.db in
    author's data directory.

    1: # The LearningOnline Network with CAPA
    2: # Handler to rename files, etc, in construction space
    3: #
    4: #  This file responds to the various buttons and events
    5: #  in the top frame of the construction space directory.
    6: #  Each event is processed in two phases.  The first phase
    7: #  presents a page that describes the proposed action to the user
    8: #  and requests confirmation.  The second phase commits the action
    9: #  and displays a page showing the results of the action.
   10: #
   11: #
   12: # $Id: loncfile.pm,v 1.129 2024/05/21 02:57:16 raeburn Exp $
   13: #
   14: # Copyright Michigan State University Board of Trustees
   15: #
   16: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
   17: #
   18: # LON-CAPA is free software; you can redistribute it and/or modify
   19: # it under the terms of the GNU General Public License as published by
   20: # the Free Software Foundation; either version 2 of the License, or
   21: # (at your option) any later version.
   22: #
   23: # LON-CAPA is distributed in the hope that it will be useful,
   24: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   25: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   26: # GNU General Public License for more details.
   27: #
   28: # You should have received a copy of the GNU General Public License
   29: # along with LON-CAPA; if not, write to the Free Software
   30: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   31: #
   32: # /home/httpd/html/adm/gpl.txt
   33: #
   34: # http://www.lon-capa.org/
   35: #
   36: =pod
   37: 
   38: =head1 NAME
   39: 
   40: Apache::loncfile - Authoring space file management.
   41: 
   42: =head1 SYNOPSIS
   43: 
   44:  Content handler for buttons on the top frame of the construction space
   45: directory.
   46: 
   47: =head1 INTRODUCTION
   48: 
   49:   loncfile is invoked when buttons in the top frame of the construction
   50: space directory listing are clicked.   All operations proceed in two phases.
   51: The first phase describes to the user exactly what will be done.  If the user
   52: confirms the operation, the second phase commits the operation and indicates
   53: completion.  When the user dismisses the output of phase2, they are returned to
   54: an "appropriate" directory listing in general.
   55: 
   56:     This is part of the LearningOnline Network with CAPA project
   57: described at http://www.lon-capa.org.
   58: 
   59: =head2 Subroutines
   60: 
   61: =cut
   62: 
   63: package Apache::loncfile;
   64: 
   65: use strict;
   66: use Apache::File;
   67: use File::Basename;
   68: use File::Copy;
   69: use HTML::Entities();
   70: use Apache::Constants qw(:common :http :methods);
   71: use Apache::lonnet;
   72: use Apache::loncommon();
   73: use Apache::lonhtmlcommon;
   74: use Apache::lonlocal;
   75: use LONCAPA qw(:DEFAULT :match);
   76: 
   77: my $DEBUG=0;
   78: my $r;				# Needs to be global for some stuff RF.
   79: 
   80: =pod
   81: 
   82: =item Debug($request, $message)
   83: 
   84:   If debugging is enabled puts out a debugging message determined by the
   85:   caller.  The debug message goes to the Apache error log file. Debugging
   86:   is enabled by setting the module global DEBUG variable to nonzero (TRUE).
   87: 
   88:  Parameters:
   89: 
   90: =over 4
   91: 
   92: =item $request - The current request operation.
   93: 
   94: =item $message - The message to put in the log file.
   95: 
   96: =back
   97: 
   98:  Returns:
   99:    nothing.
  100: 
  101: =cut
  102: 
  103: sub Debug {
  104:     # Put out the indicated message but only if DEBUG is true.
  105:     if ($DEBUG) {
  106: 	my ($r,$message) = @_;
  107: 	$r->log_reason($message);
  108:     }
  109: }
  110: 
  111: sub done {
  112:     my ($destfn) = @_;
  113:     return
  114:        '<p>'
  115:       .&Apache::lonhtmlcommon::confirm_success(&mt("Done"))
  116:       .'<br /><a href="'.&url($destfn).'">'.&mt("Continue").'</a>'
  117:       .'<script type="text/javascript">'
  118:       .'location.href="'.&url($destfn,'js').'";'
  119:       .'</script>'
  120:       .'</p>';
  121: }
  122: 
  123: =pod
  124: 
  125: =item URLToPath($url)
  126: 
  127:   Convert a URL to a file system path.
  128: 
  129:   In order to manipulate the construction space objects, it is necessary
  130:   to access url identified objects a filespace objects.  This function
  131:   translates a construction space URL to a file system path.
  132:  Parameters:
  133: 
  134: =over 4
  135: 
  136: =item  Url    - string [in] The url to convert.
  137: 
  138: =back
  139: 
  140:  Returns:
  141: 
  142: =over 4
  143: 
  144: =item  The corresponding file system path.
  145: 
  146: =back
  147: 
  148: Global References
  149: 
  150: =over 4
  151: 
  152: =item  $r      - Request object [in] Referenced in the &Debug calls.
  153: 
  154: =back
  155: 
  156: =cut
  157: 
  158: sub URLToPath {
  159:     my $Url = shift;
  160:     &Debug($r, "UrlToPath got: $Url");
  161:     $Url=~ s{^https?\://[^/]+}{};
  162:     $Url=~ s{//+}{/}g;
  163:     $Url=~ s{^/}{};
  164:     $Url=$Apache::lonnet::perlvar{'lonDocRoot'}."/$Url";
  165:     &Debug($r, "Returning $Url \n");
  166:     return $Url;
  167: }
  168: 
  169: sub url {
  170:     my ($fn,$context) = @_;
  171:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
  172:     $fn=~ s/^\Q$londocroot\E//;
  173:     $fn=~s{/\./}{/}g;
  174:     if ($context eq 'js') {
  175:         &js_escape(\$fn);
  176:     } else {
  177:         $fn=&HTML::Entities::encode($fn,'\'<>"&');
  178:     }
  179:     return $fn;
  180: }
  181: 
  182: sub display {
  183:     my $fn=shift;
  184:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
  185:     $fn=~s/^\Q$londocroot\E//;
  186:     $fn=~s{/\./}{/}g;
  187:     return '<span class="LC_filename">'.$fn.'</span>';
  188: }
  189: 
  190: 
  191: # see if the file is
  192: # a) published (return 0 if not)
  193: # b) if, so obsolete (return 0 if not)
  194: 
  195: sub obsolete_unpub {
  196:     my ($user,$domain,$construct)=@_;
  197:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
  198:     my $published=$construct;
  199:     $published=~s{^\Q$londocroot/priv/\E}{$londocroot/res/};
  200:     if (-e $published) {
  201: 	if (&Apache::lonnet::metadata($published,'obsolete')) {
  202: 	    return 1;
  203: 	}
  204: 	return 0;
  205:     } else {
  206: 	return 1;
  207:     }
  208: }
  209: 
  210: # see if directory is empty
  211: # ignores any .meta, .save, .bak, and .log files created for a previously
  212: # published file, which has since been marked obsolete and deleted.
  213: # ignores a .DS_Store file put there when viewing directory via webDAV on MacOS.
  214: sub empty_directory {
  215:     my ($dirname,$phase) = @_;
  216:     if (opendir DIR, $dirname) {
  217:         my @files = grep(!/^\.\.?$/, readdir(DIR)); # ignore . and ..
  218:         if (@files) {
  219:             my @orphans = grep(/\.(meta|save|log|bak|DS_Store)$/,@files);
  220:             if (scalar(@files) - scalar(@orphans) > 0) {
  221:                 return 0;
  222:             } else {
  223:                 if (($phase eq 'Delete2') && (@orphans > 0)) {
  224:                     foreach my $file (@orphans) {
  225:                         if ($file =~ /\.(meta|save|log|bak)$/) {
  226:                             unlink($dirname.$file);
  227:                         }
  228:                     }
  229:                 }
  230:             }
  231:         }
  232:         closedir(DIR);
  233:         return 1;
  234:     }
  235:     return 0;
  236: }
  237: 
  238: =pod
  239: 
  240: =item exists($user, $domain, $file)
  241: 
  242:    Determine if a resource filename has been published or exists
  243:    in the construction space.
  244: 
  245:  Parameters:
  246: 
  247: =over 4
  248: 
  249: =item  $user     - string [in] - Name of the user for which to check.
  250: 
  251: =item  $domain   - string [in] - Name of the domain in which the resource
  252:                           might have been published.
  253: 
  254: =item  $file     - string [in] - Name of the file.
  255: 
  256: =item  $creating - string [in] - optional, type of object being created,
  257:                                either 'directory' or 'file'. Defaults to
  258:                                'file' if unspecified.
  259: 
  260: =back
  261: 
  262: Returns:
  263: 
  264: =over 4
  265: 
  266: =item  string - Either undef, 'warning' or 'error' depending on the
  267:                 type of problem
  268: 
  269: =item  string - Either where the resource exists as an html string that can
  270:            be embedded in a dialog or an empty string if the resource
  271:            does not exist.
  272: 
  273: =back
  274: 
  275: =cut
  276: 
  277: sub exists {
  278:     my ($user, $domain, $construct, $creating) = @_;
  279:     $creating ||= 'file';
  280: 
  281:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
  282:     my $published=$construct;
  283:     $published=~s{^\Q$londocroot/priv/\E}{$londocroot/res/};
  284:     my ($type,$result);
  285:     if ( -d $construct ) {
  286: 	return ('error','<p class="LC_error">'.&mt('Error: destination for operation is an existing directory.').'</p>');
  287: 	
  288:     }
  289: 
  290:     if ( -e $published) {
  291: 	if ( -e $construct ) {
  292: 	    $type = 'warning';
  293: 	    $result.='<p class="LC_warning">'.&mt('Warning: target file exists, and has been published!').'</p>';
  294: 	} else {
  295: 	    my $published_type = (-d $published) ? 'directory' : 'file';
  296: 
  297: 	    if ($published_type eq $creating) {
  298: 		$type = 'warning';
  299: 		$result.='<p class="LC_warning">'.&mt("Warning: a published $published_type of this name exists.").'</p>';
  300: 	    } else {
  301: 		$type = 'error';
  302: 		$result.='<p class="LC_error">'.&mt("Error: a published $published_type of this name exists.").'</p>';
  303: 	    }
  304: 	}
  305:     } elsif ( -e $construct) {
  306: 	$type = 'warning';
  307: 	$result.='<p class="LC_warning">'.&mt('Warning: target file exists!').'</p>';
  308:     }
  309: 
  310:     return ($type,$result);
  311: }
  312: 
  313: =pod
  314: 
  315: =item checksuffix($old, $new)
  316: 
  317:   Determine if a resource filename suffix (the stuff after the .) would change
  318: as a result of this operation.
  319: 
  320:  Parameters:
  321: 
  322: =over 4
  323: 
  324: =item  $old   = string [in]  Previous filename.
  325: 
  326: =item  $new   = string [in]  Resultant filename.
  327: 
  328: =back
  329: 
  330:  Returns:
  331: 
  332: =over 4
  333: 
  334: =item    Empty string if everything worked.
  335: 
  336: =item    String containing an error message if there was a problem.
  337: 
  338: =back
  339: 
  340: =cut
  341: 
  342: sub checksuffix {
  343:     my ($old,$new) = @_;
  344:     my $result;
  345:     my $oldsuffix;
  346:     my $newsuffix;
  347:     if ($new=~m:(.*/*)([^/]+)\.(\w+)$:) { $newsuffix=$3; }
  348:     if ($old=~m:(.*)/+([^/]+)\.(\w+)$:) { $oldsuffix=$3; }
  349:     if (lc($oldsuffix) ne lc($newsuffix)) {
  350: 	$result.=
  351:             '<p class="LC_warning">'.&mt('Warning: change of MIME type!').'></p>';
  352:     }
  353:     return $result;
  354: }
  355: 
  356: sub cleanDest {
  357:     my ($dest,$subdir,$fn,$uname,$udom)=@_;
  358:     #remove bad characters
  359:     my $foundbad=0;
  360:     my $warnings;
  361:     my $error='';
  362:     if ($subdir && $dest =~/\./) {
  363: 	$foundbad=1;
  364: 	$dest=~s/\.//g;
  365:     }
  366:     $dest =~ s/(\s+$|^\s+)//g;
  367:     if  ($dest=~/[\#\?&%\":]/) {
  368: 	$foundbad=1;
  369: 	$dest=~s/[\#\?&%\":]//g;
  370:     }
  371:     if ($dest=~m|/|) {
  372: 	my ($newpath)=($dest=~m|(.*)/|);
  373: 	($newpath,$error)=&relativeDest($fn,$newpath,$uname,$udom);
  374: 	if (! -d "$newpath") {
  375: 	    $warnings = '<p class="LC_warning">'
  376:                        .&mt("You have requested to create file in directory [_1] which doesn't exist. The requested directory path has been removed from the requested filename."
  377:                            ,&display($newpath))
  378:                        .'</p>';
  379: 	    $dest=~s|.*/||;
  380: 	}
  381:     }
  382:     if ($dest =~ /\.(\d+)\.(\w+)$/) {
  383: 	$warnings .= '<p class="LC_warning">'
  384:                     .&mt('Bad filename [_1]',&display($dest))
  385:                     .'<br />'
  386:                     .&mt('[_1](name).(number).(extension)[_2] not allowed.','<tt>','</tt>')
  387:                     .'<br />'
  388:                     .&mt('Removing the [_1].number.[_2] from requested filename.','<tt>','</tt>')
  389:                     .'</p>';
  390: 	$dest =~ s/\.(\d+)(\.\w+)$/$2/;
  391:     }
  392:     if ($foundbad) {
  393:         $warnings .= '<p class="LC_warning">'
  394:                     .&mt('Invalid characters in requested name have been removed.')
  395:                     .'</p>';
  396:     }
  397:     return ($dest,$error,$warnings);
  398: }
  399: 
  400: sub relativeDest {
  401:     my ($fn,$newfilename,$uname,$udom)=@_;
  402:     my $error = '';
  403:     if ($newfilename=~/^\//) {
  404: # absolute, simply add path
  405:         my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
  406: 	$newfilename="$londocroot/res/$udom/$uname/";
  407:     } else {
  408: 	my $dir=$fn;
  409: 	$dir=~s{/[^/]+$}{};
  410: 	$newfilename=$dir.'/'.$newfilename;
  411:     }
  412:     $newfilename=~s{//+}{/}g; # remove duplicate /
  413:     while ($newfilename=~m{/\.\./}) {
  414: 	$newfilename=~ s{/[^/]+/\.\./}{/}g; #remove dir/..
  415:     }
  416:     my ($authorname,$authordom)=&Apache::lonnet::constructaccess($newfilename);
  417:     unless (($authorname) && ($authordom)) {
  418:        my $otherdir = &display($newfilename);
  419:        $error = &mt('Access denied to [_1]',$otherdir);
  420:     }
  421:     return ($newfilename,$error);
  422: }
  423: 
  424: =pod
  425: 
  426: =item CloseForm1($request, $user, $file)
  427: 
  428:    Close of a form on the successful completion of phase 1 processing
  429: 
  430: Parameters:
  431: 
  432: =over 4
  433: 
  434: =item  $request - Apache Request Object [in] - Apache server request object.
  435: 
  436: =item  $cancelurl - the url to go to on cancel.
  437: 
  438: =back
  439: 
  440: =cut
  441: 
  442: sub CloseForm1 {
  443:     my ($request,  $fn) = @_;
  444:     $request->print('<input type="submit" value="'.&mt('Continue').'" /></form>');
  445:     $request->print(' <form action="'.&url($fn).'" method="post">'.
  446:                     '<input type="submit" value="'.&mt('Cancel').'" /></form>');
  447: }
  448: 
  449: 
  450: =pod
  451: 
  452: =item CloseForm2($request, $user, $directory)
  453: 
  454:    Successfully close off the phase 2 form.
  455: 
  456: Parameters:
  457: 
  458: =over 4
  459: 
  460: =item   $request    - Apache Request object [in] - The request that is being
  461:                  executed.
  462: 
  463: =item   $user       - string [in] - Name of the user that is initiating the
  464:                  request.
  465: 
  466: =item   $directory  - string [in] - Directory in which the operation is
  467:                  being done relative to the top level construction space
  468:                  directory.
  469: 
  470: =back
  471: 
  472: =cut
  473: 
  474: sub CloseForm2 {
  475:     my ($request, $user, $fn) = @_;
  476:     $request->print(&done($fn));
  477: }
  478: 
  479: =pod
  480: 
  481: =item Rename1($request, $filename, $user, $domain, $dir)
  482: 
  483:    Perform phase 1 processing of the file rename operation.
  484: 
  485: Parameters:
  486: 
  487: =over 4
  488: 
  489: =item  $request   - Apache Request Object [in] The request object for the
  490: current request.
  491: 
  492: =item  $filename  - The filename relative to construction space.
  493: 
  494: =item  $user      - Name of the user making the request.
  495: 
  496: =item  $domain    - User login domain.
  497: 
  498: =item  $dir       - Directory specification of the path to the file.
  499: 
  500: =back
  501: 
  502: Side effects:
  503: 
  504: =over 4
  505: 
  506: =item A new form is displayed prompting for confirmation.  The newfilename
  507: hidden field of this form is loaded with
  508: new filename relative to the current directory ($dir).
  509: 
  510: =back
  511: 
  512: =cut
  513: 
  514: sub Rename1 {
  515:     my ($request, $user, $domain, $fn, $newfilename, $style) = @_;
  516: 
  517:     if(-e $fn) {
  518: 	if($newfilename) {
  519: 	    # is dest a dir
  520: 	    if ($style eq 'move') {
  521: 		if (-d $newfilename) {
  522: 		    if ($fn =~ m|/([^/]*)$|) { $newfilename .= '/'.$1; }
  523: 		}
  524: 	    }
  525: 	    if ($newfilename =~ m|/[^\.]+$|) {
  526: 		#no extension add on original extension
  527: 		if ($fn =~ m|/[^\.]*\.([^\.]+)$|) {
  528: 		    $newfilename.='.'.$1;
  529: 		}
  530: 	    }
  531: 	    $request->print(&checksuffix($fn, $newfilename));
  532: 	    #renaming a dir, delete the trailing /
  533:             #remove second to last element for current dir
  534: 	    if (-d $fn) {
  535: 		$newfilename=~/\.(\w+)$/;
  536: 		if (&Apache::loncommon::fileembstyle($1) eq 'ssi') {
  537: 		    $request->print('<p><span class="LC_error">'.
  538: 				    &mt('Cannot change MIME type of a directory.').
  539: 				    '</span>'.
  540: 				    '<br /><a href="'.&url($fn).'">'.&mt('Cancel').'</a></p>');
  541: 		    return;
  542: 		}
  543: 		$newfilename=~s/\/[^\/]+\/([^\/]+)$/\/$1/;
  544: 	    }
  545: 	    $newfilename=~s://+:/:g; # remove duplicate /
  546: 	    while ($newfilename=~m:/\.\./:) {
  547: 		$newfilename=~ s:/[^/]+/\.\./:/:g; #remove dir/..
  548: 	    }
  549: 	    my ($type, $return)=&exists($user, $domain, $newfilename);
  550: 	    $request->print($return);
  551: 	    if ($type eq 'error') {
  552: 		$request->print('<br /><a href="'.&url($fn).'">'.&mt('Cancel').'</a>');
  553: 		return;
  554: 	    }
  555: 	    unless (&obsolete_unpub($user,$domain,$fn)) {
  556:                 $request->print('<p><span class="LC_error">'
  557:                                .&mt('Cannot rename or move non-obsolete published file.')
  558:                                .'</span><br />'
  559:                                .'<a href="'.&url($fn).'">'.&mt('Cancel').'</a></p>'
  560:                 );
  561: 		return;
  562: 	    }
  563: 	    my $action;
  564: 	    if ($style eq 'rename') {
  565: 		$action='Rename';
  566: 	    } else {
  567: 		$action='Move';
  568: 	    }
  569:             $request->print('<input type="hidden" name="newfilename" value="'
  570:                            .$newfilename.'" />'
  571:                            .'<p>'
  572:                            .&mt($action.' [_1] to [_2]?',
  573:                                 &display($fn),
  574:                                 &display($newfilename))
  575:                            .'</p>'
  576:         );
  577: 	    &CloseForm1($request, $fn);
  578: 	} else {
  579: 	    $request->print('<p class="LC_error">'.&mt('No new filename specified.').'</p></form>');
  580: 	    return;
  581: 	}
  582:     } else {
  583:         $request->print('<p class="LC_error">'
  584:                        .&mt('No such file: [_1]',
  585:                             &display($fn))
  586:                        .'</p></form>'
  587:         );
  588: 	return;
  589:     }
  590: 
  591: }
  592: 
  593: =pod
  594: 
  595: =item Delete1
  596: 
  597:    Performs phase 1 processing of the delete operation.  In phase one
  598:   we just check to be sure the file exists.
  599: 
  600: Parameters:
  601: 
  602: =over 4
  603: 
  604: =item   $request   - Apache Request Object [in] request object for the current
  605:                 request.
  606: 
  607: =item   $user      - string [in]  Name of the user initiating the request.
  608: 
  609: =item   $domain    - string [in]  Domain the initiating user is logged in as
  610: 
  611: =item   $filename  - string [in]  Source filename.
  612: 
  613: =back
  614: 
  615: =cut
  616: 
  617: sub Delete1 {
  618:     my ($request, $user, $domain, $fn) = @_;
  619: 
  620:     if( -e $fn) {
  621: 	$request->print('<input type="hidden" name="newfilename" value="'.
  622: 			$fn.'" />');
  623:         if (-d $fn) {
  624:             unless (&empty_directory($fn,'Delete1')) {
  625:                 $request->print('<p>'
  626:                                .'<span class="LC_error">'
  627:                                .&mt('Only empty directories may be deleted.')
  628:                                .'</span><br />'
  629:                                .&mt('You must delete the contents of the directory first.')
  630:                                .'</p>'
  631:                                .'<p><a href="'.&url($fn).'">'.&mt('Cancel').'</a></p>'
  632:                 );
  633:                 return;
  634:             }
  635:         } else {
  636: 	    unless (&obsolete_unpub($user,$domain,$fn)) {
  637:                 $request->print('<p><span class="LC_error">'
  638:                                .&mt('Cannot delete non-obsolete published file.')
  639:                                .'</span><br />'
  640:                                .'<a href="'.&url($fn).'">'.&mt('Cancel').'</a></p>'
  641:                 );
  642: 	        return;
  643: 	    }
  644:         }
  645:         $request->print('<p>'
  646:                        .&mt('Delete [_1]?',
  647:                             &display($fn))
  648:                        .'</p>'
  649:         );
  650: 	&CloseForm1($request, $fn);
  651:     } else {
  652:         $request->print('<p class="LC_error">'
  653:                        .&mt('No such file: [_1]',
  654:                             &display($fn))
  655:                        .'</p></form>'
  656:         );
  657:     }
  658: }
  659: 
  660: =pod
  661: 
  662: =item Copy1($request, $user, $domain, $filename, $newfilename)
  663: 
  664:    Performs phase 1 processing of the construction space copy command.
  665:    Ensure that the source file exists.  Ensure that a destination exists,
  666:    also warn if the destination already exists.
  667: 
  668: Parameters:
  669: 
  670: =over 4
  671: 
  672: =item   $request   - Apache Request Object [in] request object for the current
  673:                 request.
  674: 
  675: =item   $user      - string [in]  Name of the user initiating the request.
  676: 
  677: =item   $domain    - string [in]  Domain the initiating user is logged in as
  678: 
  679: =item   $fn  - string [in]  Source filename.
  680: 
  681: =item   $newfilename-string [in]  Destination filename.
  682: 
  683: =back
  684: 
  685: =cut
  686: 
  687: sub Copy1 {
  688:     my ($request, $user, $domain, $fn, $newfilename) = @_;
  689: 
  690:     if(-e $fn) {
  691: 	# is dest a dir
  692: 	if (-d $newfilename) {
  693: 	    if ($fn =~ m|/([^/]*)$|) { $newfilename .= '/'.$1; }
  694: 	}
  695: 	if ($newfilename =~ m|/[^\.]+$|) {
  696: 	    #no extension add on original extension
  697: 	    if ($fn =~ m|/[^\.]*\.([^\.]+)$|) {	$newfilename.='.'.$1; }
  698: 	}
  699: 	$newfilename=~s://+:/:g; # remove duplicate /
  700: 	while ($newfilename=~m:/\.\./:) {
  701: 	    $newfilename=~ s:/[^/]+/\.\./:/:g; #remove dir/..
  702: 	}
  703: 	$request->print(&checksuffix($fn,$newfilename));
  704: 	my ($type,$return)=&exists($user, $domain, $newfilename);
  705: 	$request->print($return);
  706: 	if ($type eq 'error') {
  707: 	    $request->print('<br /><a href="'.&url($fn).'">'.&mt('Cancel').'</a></form>');
  708: 	    return;
  709: 	}
  710: # Check if there is enough space.
  711:         my @fileinfo = stat($fn);
  712:         my ($dir,$fname) = ($fn =~ m{^(.+/)([^/]+)$});
  713:         my $filesize = $fileinfo[7];
  714:         $filesize = int($filesize/1000); #expressed in kb
  715:         my $output = &Apache::loncommon::excess_filesize_warning($user,$domain,'author',
  716:                                                                  $fname,$filesize,'copy');
  717:         if ($output) {
  718:             $request->print($output.'<br /><a href="'.&url($dir).'">'.&mt('Cancel').'</a></form>');
  719:             return;
  720:         }
  721:     $request->print(
  722:         '<input type="hidden" name="newfilename"'
  723:        .' value="'.$newfilename.'" />'
  724:        .'<p>'
  725:        .&mt('Copy [_1] to [_2]?',
  726:             &display($fn),
  727:             &display($newfilename))
  728:        .'</p>'
  729:         );
  730: 	&CloseForm1($request, $fn);
  731:     } else {
  732:         $request->print('<p class="LC_error">'
  733:                        .&mt('No such file: [_1]',
  734:                             &display($fn))
  735:                        .'</p></form>'
  736:         );
  737:     }
  738: }
  739: 
  740: =pod
  741: 
  742: =item NewDir1
  743: 
  744:   Does all phase 1 processing of directory creation:
  745:   Ensures that the user provides a new directory name,
  746:   and that the directory does not already exist.
  747: 
  748: Parameters:
  749: 
  750: =over 4
  751: 
  752: =item   $request  - Apache Request Object [in] - Server request object for the
  753:                current url.
  754: 
  755: =item   $username - Name of the user that is requesting the directory creation.
  756: 
  757: =item $domain - Domain user is in
  758: 
  759: =item   $fn     - source file.
  760: 
  761: =item   $newdir   - Name of the directory to be created; path relative to the
  762:                top level of construction space.
  763: =back
  764: 
  765: Side Effects:
  766: 
  767: =over 4
  768: 
  769: =item A new form is displayed.  Clicking on the confirmation button
  770: causes the newdir operation to transition into phase 2.  The hidden field
  771: "newfilename" is set with the construction space path to the new directory.
  772: 
  773: 
  774: =back
  775: 
  776: =cut
  777: 
  778: 
  779: sub NewDir1 {
  780:     my ($request, $username, $domain, $fn, $newfilename, $mode) = @_;
  781: 
  782:     my ($type, $result)=&exists($username,$domain,$newfilename,'directory');
  783:     $request->print($result);
  784:     if ($type eq 'error') {
  785: 	$request->print('</form>');
  786:     } else {
  787: 	if (($mode eq 'testbank') || ($mode eq 'imsimport')) {
  788: 	    $request->print('<input type="hidden" name="callingmode" value="'.$mode.'" />'."\n".
  789:                             '<input type="hidden" name="inhibitmenu" value="yes" />');
  790: 	}
  791:         $request->print('<input type="hidden" name="newfilename" value="'
  792:                        .$newfilename.'" />'
  793:                        .'<p>'
  794:                        .&mt('Make new directory [_1]?',
  795:                             &display($newfilename))
  796:                        .'</p>'
  797:         );
  798: 	&CloseForm1($request, $fn);
  799:     }
  800: }
  801: 
  802: 
  803: sub Decompress1 {
  804:     my ($request, $user, $domain, $fn) = @_;
  805:     if( -e $fn) {
  806:    	$request->print('<input type="hidden" name="newfilename" value="'.$fn.'" />');
  807:    	$request->print('<p>'
  808:                    .&mt('Decompress [_1]?',
  809:                         &display($fn))
  810:                    .'</p>'
  811:     );
  812:    	&CloseForm1($request, $fn);
  813:     } else {
  814:         $request->print('<p class="LC_error">'
  815:                        .&mt('No such file: [_1]',
  816:                             &display($fn))
  817:                        .'</p></form>'
  818:         );
  819:     }
  820: }
  821: 
  822: sub Archive1 {
  823:     my ($request,$fn) = @_;
  824:     my @posstypes = qw(problem library sty sequence page task rights meta xml html xhtml htm xhtm css js tex txt gif jpg jpeg png svg other);
  825:     my (%location_of,%defaults);
  826:     my ($compstyle,$canarchive,$cancompress,$numformat,$numcompress,$defext) =
  827:         &archive_tools(\%location_of,\%defaults);
  828:     if (!$canarchive) {
  829:         $request->print('<p class="LC_error">'.
  830:                         &mt('This LON-CAPA instance does not seem to have either tar or zip installed.').'</p>'."\n".
  831:                         '<span class="LC_warning">'.
  832:                         &mt('At least one of the two is needed in order to be able to create an archive file for: [_1].',
  833:                             &display($fn))."\n".
  834:                         '</span></form>');
  835:     } elsif (-e $fn) {
  836:         $request->print('<input type="hidden" name="adload" value="" />'."\n".
  837:                         &Apache::lonhtmlcommon::start_pick_box().
  838:                         &Apache::lonhtmlcommon::row_title(&mt('Directory')).
  839:                         &display($fn).
  840:                         &Apache::lonhtmlcommon::row_closure().
  841:                         &Apache::lonhtmlcommon::row_title(&mt('Options').
  842:                         &Apache::loncommon::help_open_topic('Archiving_Directory_Options')).
  843:                         '<fieldset><legend>'.&mt('Recurse').'</legend>'.
  844:                         '<span class="LC_nobreak"><label><input type="checkbox" name="recurse" /> '.
  845:                         &mt('include subdirectories').'</label></span>'.
  846:                         '</fieldset>'.
  847:                         '<fieldset><legend>'.&mt('File types (extensions) to include').('&nbsp;'x2).
  848:                         '<span style="text-decoration:line-through">'.('&nbsp;'x5).'</span>'.('&nbsp;'x2).
  849:                         '<input type="button" name="checkall" value="'.&mt('check all').
  850:                         '" style="height:20px;" onclick="checkAll(document.phaseone.filetype);" />'.
  851:                         ('&nbsp;'x2).
  852:                         '<input type="button" name="uncheckall" value="'.&mt('uncheck all').
  853:                         '" style="height:20px;" onclick="uncheckAll(document.phaseone.filetype);" /></legend>'.
  854:                         '<table>');
  855:         my $rem;
  856:         my $numinrow = 6;
  857:         for (my $i=0; $i<@posstypes; $i++) {
  858:             my $rem = $i%($numinrow);
  859:             if ($rem == 0) {
  860:                if ($i > 0) {
  861:                     $request->print('</tr>'."\n");
  862:                }
  863:                $request->print('<tr>'."\n");
  864:             }
  865:             $request->print('<td class="LC_left_item">'.
  866:                             '<span class="LC_nobreak"><label>'.
  867:                             '<input type="checkbox" name="filetype" '.
  868:                             'value="'.$posstypes[$i].'" /> '.
  869:                             $posstypes[$i].'</label></span></td>'."\n");
  870:         }
  871:         $rem = scalar(@posstypes)%($numinrow);
  872:         my $colsleft;
  873:         if ($rem) {
  874:             $colsleft = $numinrow - $rem;
  875:         }
  876:         if ($colsleft > 1 ) {
  877:             $request->print('<td colspan="'.$colsleft.'" class="LC_left_item">'.
  878:                             '&nbsp;</td>'."\n");
  879:         } elsif ($colsleft == 1) {
  880:             $request->print('<td class="LC_left_item">&nbsp;</td>'."\n");
  881:         }
  882:         $request->print('</tr></table>'."\n".
  883:                         '</fieldset>'.
  884:                         '<fieldset><legend>'.&mt('Archive file format').'</legend>');
  885:         foreach my $possfmt ('tar','zip') {
  886:             if (exists($location_of{$possfmt})) {
  887:                 $request->print('<span class="LC_nobreak">'.
  888:                                 '<label><input type="radio" name="format" value="'.$possfmt.'"'.
  889:                                 $defaults{$possfmt}.' onclick="toggleCompression(this.form);" /> '.
  890:                                 $possfmt.'</label></span>&nbsp;&nbsp; ');
  891:             }
  892:         }
  893:         $request->print('</fieldset>'."\n".
  894:                         '<fieldset style="display:'.$compstyle.'" id="tar_compression">'.
  895:                         '<legend>'.&mt('Compression to apply to tar file').'</legend>'.
  896:                         '<span class="LC_nobreak">');
  897:         if ($cancompress) { 
  898:             foreach my $compress ('gzip','bzip2','xz') {
  899:                 if (exists($location_of{$compress})) {
  900:                     $request->print('<label><input type="radio" name="compress" value="'.$compress.'"'.
  901:                                     $defaults{$compress}.' onclick="setArchiveExt(this.form);"  />'.
  902:                                     $compress.'</label>&nbsp;&nbsp;');
  903:                 }
  904:             }
  905:         } else {
  906:             $request->print('<span class="LC_warning">'.
  907:                             &mt('This LON-CAPA instance does not seem to have gzip, bzip2 or xz installed.').
  908:                             '<br />'.&mt('No compression will be used.').'</span>');
  909:         }
  910:         $request->print('</fieldset>'."\n".
  911:                         '<fieldset style="display:none" id="archive_saveas">'.
  912:                         '<legend>'.&mt('Filename to download').'</legend>'.
  913:                         '<table style="border-spacing:0"><tr><td style="padding:0;">'.&mt('Name').'<br />'."\n".
  914:                         '<input type="text" name="archivefname" value="" size="8" /></td><td style="padding:0;">'.
  915:                         &mt('Extension').'<br />'."\n".
  916:                         '<input type="text" name="archiveext" id="archiveext" value="" size="4" readonly="readonly" />'.
  917:                         '</td></tr></table></fieldset>'."\n".
  918:                         &Apache::lonhtmlcommon::row_closure(1).
  919:                         &Apache::lonhtmlcommon::end_pick_box().'<br />'."\n"
  920:         );
  921:         &CloseForm1($request, $fn);
  922:     } else {
  923:         $request->print('<p class="LC_error">'
  924:                        .&mt('No such directory: [_1]',
  925:                             &display($fn))
  926:                        .'</p></form>'
  927:         );
  928:     }
  929:     return;
  930: }
  931: 
  932: sub archive_tools {
  933:     my ($location_of,$defaults) = @_;
  934:     my ($compstyle,$canarchive,$cancompress,$numformat,$numcompress,$defext);
  935:     ($numformat,$numcompress) = (0,0);
  936:     if ((ref($location_of) eq 'HASH') && (ref($defaults) eq 'HASH')) {
  937:         foreach my $program ('tar','gzip','bzip2','xz','zip') {
  938:             foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
  939:                              '/usr/sbin/') {
  940:                 if (-x $dir.$program) {
  941:                     $location_of->{$program} = $dir.$program;
  942:                     last;
  943:                 }
  944:             }
  945:         }
  946:         foreach my $format ('tar','zip') {
  947:             if (exists($location_of->{$format})) {
  948:                 unless ($canarchive) {
  949:                     $defext = $format;
  950:                     $defaults->{$format} = ' checked="checked"';
  951:                     if ($format eq 'tar') {
  952:                         $compstyle = 'block';
  953:                     } else {
  954:                         $compstyle = 'none';
  955:                     }
  956:                 }
  957:                 $canarchive = 1;
  958:                 $numformat ++;
  959:             }
  960:         }
  961:         foreach my $compress ('gzip','bzip2','xz') {
  962:             if (exists($location_of->{$compress})) {
  963:                 $numcompress ++;
  964:                 unless ($cancompress) {
  965:                     if ($defext eq 'tar') {
  966:                         if ($compress eq 'gzip') {
  967:                             $defext .= '.gz';
  968:                         } elsif ($compress eq 'bzip2') {
  969:                             $defext .= '.bz2';
  970:                         } else {
  971:                             $defext .= ".$compress";
  972:                         }
  973:                     }
  974:                     $defaults->{$compress} = ' checked="checked"';
  975:                     $cancompress = 1;
  976:                 }
  977:             }
  978:         }
  979:     }
  980:     if (wantarray) {
  981:         return ($compstyle,$canarchive,$cancompress,$numformat,$numcompress,$defext);
  982:     } else {
  983:         return $defext;
  984:     }
  985: }
  986: 
  987: sub archive_in_progress {
  988:     my ($earlyout,$idnum);
  989:     if ($env{'cgi.author.archive'} =~ /^(\d+)_\d+_\d+$/) {
  990:         my $timestamp = $1;
  991:         $idnum = $env{'cgi.author.archive'};
  992:         if (exists($env{'cgi.'.$idnum.'.archive'})) {
  993:             my $hashref = &Apache::lonnet::thaw_unescape($env{'cgi.'.$idnum.'.archive'});
  994:             my $lonprtdir = $Apache::lonnet::perlvar{'lonPrtDir'};
  995:             if (-e $lonprtdir.'/'.$env{'user.name'}.'_'.$env{'user.domain'}.'_archive_'.$idnum.'.txt') {
  996:                 $earlyout = $timestamp;
  997:             } elsif (ref($hashref) eq 'HASH') {
  998:                 my $suffix = $hashref->{'extension'};
  999:                 if (-e $lonprtdir.'/'.$env{'user.name'}.'_'.$env{'user.domain'}.'_archive_'.$idnum.$suffix) {
 1000:                     $earlyout = $timestamp;
 1001:                 }
 1002:             }
 1003:             unless ($earlyout) {
 1004:                 &Apache::lonnet::delenv('cgi.'.$idnum.'.archive');
 1005:                 &Apache::lonnet::delenv('cgi.author.archive');
 1006:             }
 1007:         } else {
 1008:             &Apache::lonnet::delenv('cgi.author.archive');
 1009:         }
 1010:     }
 1011:     return ($earlyout,$idnum);
 1012: }
 1013: 
 1014: sub cancel_archive_form {
 1015:     my ($r,$title,$fname,$earlyout,$idnum) = @_;
 1016:     $r->print('<h2>'.$title.'</h2>'."\n".
 1017:               '<form action="/adm/cfile" method="post" onsubmit="return confirmation(this);">'."\n".
 1018:               '<input type="hidden" name="filename" value="'.$fname.'" />'."\n".
 1019:               '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 1020:               '<p>'.&mt('Each author may only have one archive request in process at a time.')."\n".'<ul>'.
 1021:               '<li>'.&mt('An incomplete archive request was begun: [_1].',
 1022:                          &Apache::lonlocal::locallocaltime($earlyout)).
 1023:               '</li>'."\n".
 1024:               '<li>'.&mt('An archive request is considered complete when the archive file has been successfully downloaded.').'</li>'."\n".
 1025:               '<li>'.
 1026:               &mt('To submit a new archive request, either wait for the existing request (e.g., in another tab/window) to complete, or remove it.').'</li>'."\n".
 1027:               '</ul></p>'."\n".
 1028:               '<p><span class="LC_nobreak">'.&mt('Remove existing archive request?').'&nbsp;'."\n".
 1029:               '<label><input type="radio" name="remove_archive_request" value="'.$idnum.'" />'.&mt('Yes').'</label>'.
 1030:               ('&nbsp;'x2)."\n".
 1031:               '<label><input type="radio" name="remove_archive_request" value="" checked="checked" />'.&mt('No').'</label></span></p>'."\n".
 1032:               '<br />');
 1033: }
 1034: 
 1035: =pod
 1036: 
 1037: =item NewFile1
 1038: 
 1039:   Does all phase 1 processing of file creation:
 1040:   Ensures that the user provides a new filename, adds proper extension
 1041:   if needed and that the file does not already exist, if it is a html,
 1042:   problem, page, or sequence, it then creates a form link to hand the
 1043:   actual creation off to the proper handler.
 1044: 
 1045: Parameters:
 1046: 
 1047: =over 4
 1048: 
 1049: =item   $request  - Apache Request Object [in] - Server request object for the
 1050:                current url.
 1051: 
 1052: =item   $username - Name of the user that is requesting the directory creation.
 1053: 
 1054: =item   $domain   - Name of the domain of the user
 1055: 
 1056: =item   $fn      - Source filename
 1057: 
 1058: =item   $newfilename
 1059:                   - Name of the file to be created; no path information
 1060: 
 1061: =item   $warnings - Information about changes to filename made by cleanDest().
 1062: 
 1063: =back
 1064: 
 1065: Side Effects:
 1066: 
 1067: =over 4
 1068: 
 1069: =item 2 new forms are displayed.  Clicking on the confirmation button
 1070: causes the browser to attempt to load the specfied URL, allowing the
 1071: proper handler to take care of file creation. There is also a Cancel
 1072: button which returns you to the directory listing you came from
 1073: 
 1074: =back
 1075: 
 1076: =cut
 1077: 
 1078: sub NewFile1 {
 1079:     my ($request, $user, $domain, $fn, $newfilename, $warnings) = @_;
 1080:     return if (&filename_check($newfilename,$warnings) ne 'ok');
 1081: 
 1082:     if ($env{'form.action'} =~ /new(.+)file/) {
 1083: 	my $extension=$1;
 1084: 	if ($newfilename !~ /\Q.$extension\E$/) {
 1085: 	    if ($newfilename =~ m|/[^/.]*\.(?:[^/.]+)$|) {
 1086: 		#already has an extension strip it and add in expected one
 1087: 		$newfilename =~ s|(/[^./])\.(?:[^.]+)$|$1|;
 1088: 	    }
 1089: 	    $newfilename.=".$extension";
 1090: 	}
 1091:     }
 1092:     my ($type, $result)=&exists($user,$domain,$newfilename);
 1093:     if ($type eq 'error') {
 1094:         $request->print($warnings.$result);
 1095: 	$request->print('</form>');
 1096:     } else {
 1097:         my $extension;
 1098: 
 1099:         if ($newfilename =~ m{[^/.]+\.([^/.]+)$}) {
 1100:             $extension = $1;
 1101:         }
 1102: 
 1103:         my @okexts = qw(xml html xhtml htm xhtm problem page sequence rights sty task library js css txt);
 1104:         if (($extension eq '') || (!grep(/^\Q$extension\E/,@okexts))) {
 1105:             my $validexts = '.'.join(', .',@okexts);
 1106:             $request->print($warnings.$result);
 1107:             $request->print('<p class="LC_warning">'.
 1108:                 &mt('Invalid filename: ').&display($newfilename).'</p><p>'.
 1109:                 &mt('The name of the new file needs to end with an appropriate file extension to indicate the type of file to create.').'<br />'.
 1110:                 &mt('The following are valid extensions: [_1].',$validexts).
 1111:                 '</p></form><p>'.
 1112: 		'<form name="fileaction" action="/adm/cfile" method="post">'.
 1113:                 '<input type="hidden" name="qualifiedfilename" value="'.$fn.'" />'.
 1114: 		'<input type="hidden" name="action" value="newfile" />'.
 1115: 	        '<span class ="LC_nobreak">'.&mt('Enter a filename: ').'<input type="text" name="newfilename" value="Type Name Here" onfocus="if (this.value == '."'Type Name Here') this.value=''".'" />&nbsp;<input type="submit" value="Go" />'.
 1116:                 '</span></form></p>'.
 1117:                 '<p><form action="'.&url($fn).
 1118:                 '" method="post"><p><input type="submit" value="'.&mt('Cancel').'" /></form></p>');
 1119:         } elsif (($type ne 'warning') && ($warnings eq '') && ($result eq '')) {
 1120:             my $query = "";
 1121:             $query .= "?mode=" . $env{'form.mode'} unless (!exists($env{'form.mode'}) || !length($env{'form.mode'}));
 1122:             $request->print('
 1123:                 <script type="text/javascript">
 1124:                     window.location = "'.&url($newfilename,'js'). $query .'";
 1125:                 </script>');
 1126:         } else {
 1127:             $request->print($warnings.$result);
 1128:             $request->print('<p>'.&mt('Make new file').' '.&display($newfilename).'?</p>');
 1129:             $request->print('</form>');
 1130:             $request->print('<form action="'.&url($newfilename).
 1131:                         '" method="post"><p><input type="submit" value="'.&mt('Continue').'" /></p></form>');
 1132:             $request->print('<form action="'.&url($fn).
 1133:                         '" method="post"><p><input type="submit" value="'.&mt('Cancel').'" /></p></form>');
 1134:         }
 1135:     }
 1136:     return;
 1137: }
 1138: 
 1139: sub filename_check {
 1140:     my ($newfilename) = @_;
 1141:     ##Informs User (name).(number).(extension) not allowed
 1142:     if($newfilename =~ /\.(\d+)\.(\w+)$/){
 1143:         $r->print('<span class="LC_error">'.$newfilename.
 1144:                   ' - '.&mt('Bad Filename').'<br />('.&mt('name').').('.&mt('number').').('.&mt('extension').') '.
 1145:                   ' '.&mt('Not Allowed').'</span>');
 1146:         return;
 1147:     }
 1148:     if($newfilename =~ /(\:\:\:|\&\&\&|\_\_\_)/){
 1149:         $r->print('<span class="LC_error">'.$newfilename.
 1150:                   ' - '.&mt('Bad Filename').'<br />('.&mt('Must not include').' '.$1.') '.
 1151:                   ' '.&mt('Not Allowed').'</span>');
 1152:         return;
 1153:     }
 1154:     return 'ok';
 1155: }
 1156: 
 1157: =pod
 1158: 
 1159: =item phaseone($r, $fn, $uname, $udom)
 1160: 
 1161:   Peforms phase one processing of the request.  In phase one, error messages
 1162: are returned if the request cannot be performed (e.g. attempts to manipulate
 1163: files that are nonexistent).  If the operation can be performed, what is
 1164: about to be done will be presented to the user for confirmation.  If the
 1165: user confirms the request, then phase two is executed, the action
 1166: performed and reported to the user.
 1167: 
 1168:  Parameters:
 1169: 
 1170: =over 4
 1171: 
 1172: =item $r  - request object [in] - The Apache request being executed.
 1173: 
 1174: =item $fn = string [in] - The filename being manipulated by the
 1175:                              request.
 1176: 
 1177: =item $uname - string [in] Name of user logged in and doing this action.
 1178: 
 1179: =item $udom  - string [in] Domain name under which the user logged in.
 1180: 
 1181: =back
 1182: 
 1183: =cut
 1184: 
 1185: sub phaseone {
 1186:     my ($r,$fn,$uname,$udom)=@_;
 1187: 
 1188:     my $doingdir=0;
 1189:     if ($env{'form.action'} eq 'newdir') { $doingdir=1; }
 1190:     my ($newfilename,$error,$warnings) =
 1191:         &cleanDest($env{'form.newfilename'},$doingdir,$fn,$uname,$udom);
 1192:     unless ($error) {
 1193:         ($newfilename,$error)=&relativeDest($fn,$newfilename,$uname,$udom);
 1194:     }
 1195:     if ($error) {
 1196:         my $dirlist;
 1197:         if ($fn=~m{^(.*/)[^/]+$}) {
 1198:             $dirlist=$1;
 1199:         } else {
 1200:             $dirlist=$fn;
 1201:         }
 1202:         if ($warnings) {
 1203:             $r->print($warnings);
 1204:         }
 1205:         $r->print('<div class="LC_error">'.$error.'</div>'.
 1206:                   '<p><a href="'.&url($dirlist).'">'.&mt('Return to Directory').
 1207:                   '</a></p>');
 1208:         return;
 1209:     }
 1210:     $r->print('<form action="/adm/cfile" method="post" name="phaseone">'."\n".
 1211: 	      '<input type="hidden" name="qualifiedfilename" value="'.$fn.'" />'."\n".
 1212: 	      '<input type="hidden" name="phase" value="two" />'."\n".
 1213: 	      '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1214: 
 1215:     if ($env{'form.action'} eq 'newfile' ||
 1216:         $env{'form.action'} eq 'newhtmlfile' ||
 1217:         $env{'form.action'} eq 'newproblemfile' ||
 1218:         $env{'form.action'} eq 'newpagefile' ||
 1219:         $env{'form.action'} eq 'newsequencefile' ||
 1220:         $env{'form.action'} eq 'newrightsfile' ||
 1221:         $env{'form.action'} eq 'newstyfile' ||
 1222:         $env{'form.action'} eq 'newtaskfile' ||
 1223:         $env{'form.action'} eq 'newlibraryfile' ||
 1224:         $env{'form.action'} eq 'Select Action') {
 1225:         my $empty=&mt('Type Name Here');
 1226:         if (($newfilename!~/\/$/) && ($newfilename!~/$empty$/)) {
 1227:             &NewFile1($r, $uname, $udom, $fn, $newfilename, $warnings);
 1228:         } else {
 1229:             if ($warnings) {
 1230:                 $r->print($warnings);
 1231:             }
 1232:             $r->print('<p class="LC_error">'
 1233:                      .&mt('No new filename specified.')
 1234:                      .'</p></form>'
 1235:             );
 1236:         }
 1237:     } else {
 1238:         if ($warnings) {
 1239:             $r->print($warnings);
 1240:         }
 1241:         if ($env{'form.action'} eq 'rename') {
 1242: 	    &Rename1($r, $uname, $udom, $fn, $newfilename, 'rename');
 1243:         } elsif ($env{'form.action'} eq 'move') {
 1244: 	    &Rename1($r, $uname, $udom, $fn, $newfilename, 'move');
 1245:         } elsif ($env{'form.action'} eq 'delete') {
 1246: 	    &Delete1($r, $uname, $udom, $fn);
 1247:         } elsif ($env{'form.action'} eq 'decompress') {
 1248: 	    &Decompress1($r, $uname, $udom, $fn);
 1249:         } elsif ($env{'form.action'} eq 'archive') {
 1250:             &Archive1($r,$fn);
 1251:         } elsif ($env{'form.action'} eq 'copy') {
 1252: 	    if ($newfilename) {
 1253: 	        &Copy1($r, $uname, $udom, $fn, $newfilename);
 1254: 	    } else {
 1255:                 $r->print('<p class="LC_error">'
 1256:                          .&mt('No new filename specified.')
 1257:                          .'</p></form>'
 1258:                 );
 1259:             }
 1260:         } elsif ($env{'form.action'} eq 'newdir') {
 1261: 	    my $mode = '';
 1262: 	    if (exists($env{'form.callingmode'}) ) {
 1263: 	        $mode = $env{'form.callingmode'};
 1264: 	    }
 1265: 	    &NewDir1($r, $uname, $udom, $fn, $newfilename, $mode);
 1266:         }
 1267:     }
 1268: }
 1269: 
 1270: =pod
 1271: 
 1272: =item Rename2($request, $user, $directory, $oldfile, $newfile)
 1273: 
 1274: Performs phase 2 processing of a rename reequest.   This is where the
 1275: actual rename is performed.
 1276: 
 1277: Parameters
 1278: 
 1279: =over 4
 1280: 
 1281: =item $request - Apache request object [in] The request being processed.
 1282: 
 1283: =item $user  - string [in] The name of the user initiating the request.
 1284: 
 1285: =item $directory - string [in] The name of the directory relative to the
 1286:                  construction space top level of the renamed file.
 1287: 
 1288: =item $oldfile - Name of the file.
 1289: 
 1290: =item $newfile - Name of the new file.
 1291: 
 1292: =back
 1293: 
 1294: Returns:
 1295: 
 1296: =over 4
 1297: 
 1298: =item 1 Success.
 1299: 
 1300: =item 0 Failure.
 1301: 
 1302: =cut
 1303: 
 1304: sub Rename2 {
 1305: 
 1306:     my ($request, $user, $directory, $oldfile, $newfile) = @_;
 1307: 
 1308:     &Debug($request, "Rename2 directory: ".$directory." old file: ".$oldfile.
 1309: 	   " new file ".$newfile."\n");
 1310:     &Debug($request, "Target is: ".$directory.'/'.
 1311: 	   $newfile);
 1312:     if (-e $oldfile) {
 1313: 
 1314: 	my $oRN=$oldfile;
 1315: 	my $nRN=$newfile;
 1316: 	unless (rename($oldfile,$newfile)) {
 1317: 	    $request->print('<span class="LC_error">'.&mt('Error').': '.$!.'</span>');
 1318: 	    return 0;
 1319: 	}
 1320: 	## If old name.(extension) exits, move under new name.
 1321: 	## If it doesn't exist and a new.(extension) exists
 1322: 	## delete it (only concern when renaming over files)
 1323: 	my $tmp1=$oRN.'.meta';
 1324: 	my $tmp2=$nRN.'.meta';
 1325: 	if(-e $tmp1){
 1326: 	    unless(rename($tmp1,$tmp2)){ }
 1327: 	} elsif(-e $tmp2){
 1328: 	    unlink $tmp2;
 1329: 	}
 1330: 	$tmp1=$oRN.'.save';
 1331: 	$tmp2=$nRN.'.save';
 1332: 	if(-e $tmp1){
 1333: 	    unless(rename($tmp1,$tmp2)){ }
 1334: 	} elsif(-e $tmp2){
 1335: 	    unlink $tmp2;
 1336: 	}
 1337: 	$tmp1=$oRN.'.log';
 1338: 	$tmp2=$nRN.'.log';
 1339: 	if(-e $tmp1){
 1340: 	    unless(rename($tmp1,$tmp2)){ }
 1341: 	} elsif(-e $tmp2){
 1342: 	    unlink $tmp2;
 1343: 	}
 1344: 	$tmp1=$oRN.'.bak';
 1345: 	$tmp2=$nRN.'.bak';
 1346: 	if(-e $tmp1){
 1347: 	    unless(rename($tmp1,$tmp2)){ }
 1348: 	} elsif(-e $tmp2){
 1349: 	    unlink $tmp2;
 1350: 	}
 1351:     } else {
 1352:         $request->print(
 1353:             '<p class="LC_error">'
 1354:            .&mt('No such file: [_1]',
 1355:                 &display($oldfile))
 1356:            .'</p></form>'
 1357:         );
 1358: 	return 0;
 1359:     }
 1360:     return 1;
 1361: }
 1362: 
 1363: =pod
 1364: 
 1365: =item Delete2($request, $user, $filename)
 1366: 
 1367:   Performs phase two of a delete.  The user has confirmed that they want
 1368: to delete the selected file.   The file is deleted and the results of the
 1369: delete attempt are indicated.
 1370: 
 1371: Parameters:
 1372: 
 1373: =over 4
 1374: 
 1375: =item $request - Apache Request object [in] the request object for the current
 1376:                  delete operation.
 1377: 
 1378: =item $user    - string [in]  The name of the user initiating the delete
 1379:                  request.
 1380: 
 1381: =item $filename - string [in] The name of the file, relative to construction
 1382:                   space, to delete.
 1383: 
 1384: =back
 1385: 
 1386: Returns:
 1387:   1 - success.
 1388:   0 - Failure.
 1389: 
 1390: =cut
 1391: 
 1392: sub Delete2 {
 1393:     my ($request, $user, $filename) = @_;
 1394:     if (-d $filename) {
 1395: 	unless (&empty_directory($filename,'Delete2')) {
 1396: 	    $request->print('<span class="LC_error">'.&mt('Error: Directory Non Empty').'</span>');
 1397: 	    return 0;
 1398: 	} else {
 1399: 	    if(-e $filename) {
 1400: 		unless(rmdir($filename)) {
 1401: 		    $request->print('<span class="LC_error">'.&mt('Error').': '.$!.'</span>');
 1402: 		    return 0;
 1403: 		}
 1404: 	    } else {
 1405:         	$request->print('<p class="LC_error">'.&mt('No such file').'</p></form>');
 1406: 		return 0;
 1407: 	    }
 1408: 	}
 1409:     } else {
 1410: 	if(-e $filename) {
 1411: 	    unless(unlink($filename)) {
 1412: 		$request->print('<span class="LC_error">'.&mt('Error').': '.$!.'</span>');
 1413: 		return 0;
 1414: 	    }
 1415: 	} else {
 1416:             $request->print('<p class="LC_error">'.&mt('No such file').'</p></form>');
 1417: 	    return 0;
 1418: 	}
 1419:     }
 1420:     return 1;
 1421: }
 1422: 
 1423: =pod
 1424: 
 1425: =item Copy2($request, $username, $dir, $oldfile, $newfile)
 1426: 
 1427:    Performs phase 2 of a copy.  The file is copied and the status
 1428:    of that copy is reported back to the user.
 1429: 
 1430: =over 4
 1431: 
 1432: =item $request - Apache request object [in]; the apache request currently
 1433:                  being executed.
 1434: 
 1435: =item $username - string [in] Name of the user who is requesting the copy.
 1436: 
 1437: =item $dir - string [in] Directory path relative to the construction space
 1438:              of the destination file.
 1439: 
 1440: =item $oldfile - string [in] Name of the source file.
 1441: 
 1442: =item $newfile - string [in] Name of the destination file.
 1443: 
 1444: 
 1445: =back
 1446: 
 1447: Returns 0 failure, and 1 successs.
 1448: 
 1449: =cut
 1450: 
 1451: sub Copy2 {
 1452:     my ($request, $username, $dir, $oldfile, $newfile) = @_;
 1453:     &Debug($request ,"Will try to copy $oldfile to $newfile");
 1454:     if(-e $oldfile) {
 1455:         if ($oldfile eq $newfile) {
 1456:             $request->print('<span class="LC_error">'.&mt('Warning').': '.&mt('Name of new file is the same as name of old file').' - '.&mt('no action taken').'.</span>');
 1457:             return 1;
 1458:         }
 1459: 	unless (copy($oldfile, $newfile)) {
 1460: 	    $request->print('<span class="LC_error">'.&mt('copy Error').': '.$!.'</span>');
 1461: 	    return 0;
 1462: 	} elsif (!chmod(0660, $newfile)) {
 1463: 	    $request->print('<span class="LC_error">'.&mt('chmod error').': '.$!.'</span>');
 1464: 	    return 0;
 1465: 	} elsif (-e $oldfile.'.meta' &&
 1466: 		 !copy($oldfile.'.meta', $newfile.'.meta') &&
 1467: 		 !chmod(0660, $newfile.'.meta')) {
 1468: 	    $request->print('<span class="LC_error">'.&mt('copy metadata error').
 1469: 			    ': '.$!.'</span>');
 1470: 	    return 0;
 1471: 	} else {
 1472: 	    return 1;
 1473: 	}
 1474:     } else {
 1475:         $request->print('<p class="LC_error">'.&mt('No such file').'</p>');
 1476: 	return 0;
 1477:     }
 1478:     return 1;
 1479: }
 1480: 
 1481: =pod
 1482: 
 1483: =item NewDir2($request, $user, $newdirectory)
 1484: 
 1485: 	Performs phase 2 processing of directory creation.  This involves creating the directory and
 1486: 	reporting the results of that creation to the user.
 1487: 	
 1488: Parameters:
 1489: =over 4
 1490: 
 1491: =item $request  - Apache request object [in].  Object representing the current HTTP request.
 1492: 
 1493: =item $user - string [in] The name of the user that is initiating the request.
 1494: 
 1495: =item $newdirectory - string [in] The full path of the directory being created.
 1496: 
 1497: =back
 1498: 
 1499: Returns 0 - failure 1 - success.
 1500: 
 1501: =cut
 1502: 
 1503: sub NewDir2 {
 1504:     my ($request, $user, $newdirectory) = @_;
 1505: 
 1506:     unless(mkdir($newdirectory, 02770)) {
 1507: 	$request->print('<span class="LC_error">'.&mt('Error').': '.$!.'</span>');
 1508: 	return 0;
 1509:     }
 1510:     unless(chmod(02770, ($newdirectory))) {
 1511: 	$request->print('<span class="LC_error">'.&mt('Error').': '.$!.'</span>');
 1512: 	return 0;
 1513:     }
 1514:     return 1;
 1515: }
 1516: 
 1517: sub decompress2 {
 1518:     my ($r, $user, $dir, $file) = @_;
 1519:     &Apache::lonnet::appenv({'cgi.file' => $file});
 1520:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
 1521:     my $result=&Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
 1522:     $r->print($result);
 1523:     &Apache::lonnet::delenv('cgi.file');
 1524:     &Apache::lonnet::delenv('cgi.dir');
 1525:     return 1;
 1526: }
 1527: 
 1528: sub Archive2 {
 1529:     my ($r,$uname,$udom,$fn,$identifier) = @_;
 1530:     my %options = (
 1531:                     dir => $fn,
 1532:                     uname => $uname,
 1533:                     udom => $udom,
 1534:                   );
 1535:     if ($env{'form.adload'}) {
 1536:         $options{'adload'} = 1;
 1537:         if ($env{'form.archivefname'} ne '') {
 1538:             $env{'form.archivefname'} =~ s{\.+}{.}g;
 1539:             $options{'fname'} = $env{'form.archivefname'};
 1540:         }
 1541:         if ($env{'form.archiveext'} ne '') {
 1542:             $options{'extension'} = $env{'form.archiveext'};
 1543:         }
 1544:     }
 1545:     my @filetypes = qw(problem library sty sequence page task rights meta xml html xhtml htm xhtm css js tex txt gif jpg jpeg png svg other);
 1546:     my (@include,%oktypes);
 1547:     map { $oktypes{$_} = 1; } @filetypes;
 1548:     my @posstypes = &Apache::loncommon::get_env_multiple('form.filetype');
 1549:     foreach my $type (@posstypes) {
 1550:         if ($oktypes{$type}) {
 1551:             push(@include,$type);
 1552:         }
 1553:     }
 1554:     if (scalar(@include) == scalar(@filetypes)) {
 1555:         $options{'types'} = 'all';
 1556:     } else {
 1557:         $options{'types'} = join(',',@include);
 1558:     }
 1559:     if (exists($env{'form.recurse'})) {
 1560:         $options{'recurse'} = 1;
 1561:     }
 1562:     if (exists($env{'form.encrypt'})) {
 1563:         if ($env{'form.enckey'} ne '') {
 1564:             $options{'encrypt'} = $env{'form.enckey'};
 1565:         }
 1566:     }
 1567:     $options{'format'} = 'tar';
 1568:     $options{'compress'} = 'gzip';
 1569:     if ((exists($env{'form.format'})) && $env{'form.format'} =~ /^zip$/i) {
 1570:         $options{'format'} = 'zip';
 1571:         delete($options{'compress'});
 1572:     } elsif ((exists($env{'form.compress'})) && ($env{'form.compress'} =~ /^(xz|bzip2)$/i)) {
 1573:         $options{'compress'} = lc($env{'form.compress'});  
 1574:     }
 1575:     my $key = 'cgi.'.$identifier.'.archive';
 1576:     my $storestring = &Apache::lonnet::freeze_escape(\%options);
 1577:     &Apache::lonnet::appenv({$key => $storestring,
 1578:                              'cgi.author.archive' => $identifier});
 1579:     return 1;
 1580: }
 1581: 
 1582: sub Archive3 {
 1583:     my ($hashref) = @_;
 1584:     if (ref($hashref) eq 'HASH') {
 1585:         if (($hashref->{'uname'} eq $env{'user.name'}) &&
 1586:             ($hashref->{'udom'} eq $env{'user.domain'}) &&
 1587:             ($env{'environment.canarchive'}) &&
 1588:             ($env{'form.delarchive'})) {
 1589:             my $filesdest = $Apache::lonnet::perlvar{'lonPrtDir'}.'/'.$env{'user.name'}.'_'.$env{'user.domain'}.'_archive_'.$env{'form.delarchive'};
 1590:             if (-e $filesdest) {
 1591:                 my $size = (stat($filesdest))[7];
 1592:                 if (unlink($filesdest)) {
 1593:                     my ($identifier,$suffix) = split(/\./,$env{'form.delarchive'},2);
 1594:                     if (($identifier) && (exists($env{'cgi.'.$identifier.'.archive'}))) {
 1595:                         my $delres = &Apache::lonnet::delenv('cgi.'.$identifier.'.archive');
 1596:                         if (($delres eq 'ok') &&
 1597:                             (exists($env{'cgi.author.archive'})) &&
 1598:                             ($env{'cgi.author.archive'} eq $identifier)) {
 1599:                             &Apache::lonnet::authorarchivelog($hashref,$size,$filesdest,'delete');
 1600:                             &Apache::lonnet::delenv('cgi.author.archive');
 1601:                         }
 1602:                     }
 1603:                     return 1;
 1604:                 }
 1605:             }
 1606:         }
 1607:     }
 1608:     return 0;
 1609: }
 1610: 
 1611: =pod
 1612: 
 1613: =item phasetwo($r, $fn, $uname, $udom,$identifier)
 1614: 
 1615:    Controls the phase 2 processing of file management
 1616:    requests for construction space.  In phase one, the user
 1617:    was asked to confirm the operation.  In phase 2, the operation
 1618:    is performed and the result is shown.
 1619: 
 1620:   The strategy is to break out the processing into specific action processors
 1621:   named action2 where action is the requested action and the 2 denotes
 1622:   phase 2 processing.
 1623: 
 1624: Parameters:
 1625: 
 1626: =over 4
 1627: 
 1628: =item  $r     - Apache Request object [in] The request object for this httpd
 1629:            transaction.
 1630: 
 1631: =item  $fn    - string [in]  A filename indicating the object that is being
 1632:            manipulated.
 1633: 
 1634: =item  $uname - string [in] The name of the user initiating the file management
 1635:            request.
 1636: 
 1637: =item  $udom  - string  [in] The login domain of the user initiating the
 1638:            file management request.
 1639: =back
 1640: 
 1641: =cut
 1642: 
 1643: sub phasetwo {
 1644:     my ($r,$fn,$uname,$udom,$identifier)=@_;
 1645: 
 1646:     &Debug($r, "loncfile - Entering phase 2 for $fn");
 1647: 
 1648:     # Break down the file into its component pieces.
 1649: 
 1650:     my $dir;		# Directory path
 1651:     my $main;		# Filename.
 1652:     my $suffix;		# Extension.
 1653:     if ($fn=~m:(.*)/([^/]+):) {
 1654: 	$dir=$1;		# Directory path
 1655: 	$main=$2;		# Filename.
 1656:     }
 1657:     if($main=~m:\.(\w+)$:){ # Fixes problems with filenames with no extensions
 1658: 	$suffix=$1; #This is the actually filename extension if it exists
 1659: 	$main=~s/\.\w+$//; #strip the extension
 1660:     }
 1661:     my $dest;                       #
 1662:     my $dest_dir;                   # On success this is where we'll go.
 1663:     my $disp_newname;               #
 1664:     my $dest_newname;               #
 1665:     &Debug($r,"loncfile::phase2 dir = $dir main = $main suffix = $suffix");
 1666:     &Debug($r,"    newfilename = ".$env{'form.newfilename'});
 1667: 
 1668:     my $conspace=$fn;
 1669: 
 1670:     &Debug($r,"loncfile::phase2 Full construction space name: $conspace");
 1671: 
 1672:     &Debug($r,"loncfie::phase2 action is $env{'form.action'}");
 1673: 
 1674:     # Select the appropriate processing sub.
 1675:     if ($env{'form.action'} eq 'decompress') {
 1676: 	$main .= '.'.$suffix;
 1677: 	if(!&decompress2($r, $uname, $dir, $main)) {
 1678: 	    return ;
 1679: 	}
 1680: 	$dest = $dir."/.";
 1681:     } elsif ($env{'form.action'} eq 'archive') {
 1682:         &Archive2($r,$uname,$udom,$fn,$identifier);
 1683:         return;
 1684:     } elsif ($env{'form.action'} eq 'rename' ||
 1685: 	     $env{'form.action'} eq 'move') {
 1686: 	if($env{'form.newfilename'}) {
 1687: 	    if (!defined($dir)) {
 1688: 		$fn=~m:^(.*)/:;
 1689: 		$dir=$1;
 1690: 	    }
 1691: 	    if(!&Rename2($r, $uname, $dir, $fn, $env{'form.newfilename'})) {
 1692: 		return;
 1693: 	    }
 1694: 	    $dest = $dir."/";
 1695: 	    $dest_newname = $env{'form.newfilename'};
 1696: 	    $env{'form.newfilename'} =~ /.+(\/.+$)/;
 1697: 	    $disp_newname = $1;
 1698: 	    $disp_newname =~ s/\///;
 1699: 	}
 1700:     } elsif ($env{'form.action'} eq 'delete') {
 1701: 	if(!&Delete2($r, $uname, $env{'form.newfilename'})) {
 1702: 	    return ;
 1703: 	}
 1704: 	# Once a resource is deleted, we just list the directory that
 1705: 	# previously held it.
 1706: 	#
 1707: 	$dest = $dir."/.";		# Parent dir.
 1708:     } elsif ($env{'form.action'} eq 'copy') {
 1709: 	if($env{'form.newfilename'}) {
 1710: 	    if(!&Copy2($r, $uname, $dir, $fn, $env{'form.newfilename'})) {
 1711: 		return ;
 1712: 	    }
 1713: 	    $dest = $env{'form.newfilename'};
 1714:      	} else {
 1715:             $r->print('<p class="LC_error">'.&mt('No New filename specified').'</p></form>');
 1716: 	    return;
 1717: 	}
 1718: 	
 1719:     } elsif ($env{'form.action'} eq 'newdir') {
 1720:         my $newdir= $env{'form.newfilename'};
 1721: 	if(!&NewDir2($r, $uname, $newdir)) {
 1722: 	    return;
 1723: 	}
 1724: 	$dest = $newdir."/";
 1725:     }
 1726:     if ( ($env{'form.action'} eq 'newdir') && ($env{'form.phase'} eq 'two') && ( ($env{'form.callingmode'} eq 'testbank') || ($env{'form.callingmode'} eq 'imsimport') ) ) {
 1727:         $r->print(
 1728:             '<p>'
 1729:            .&Apache::lonhtmlcommon::confirm_success(&mt('Done'))
 1730:            .'<br /><a href="javascript:self.close()">'.&mt('Continue').'</a>'
 1731:            .'</p>'
 1732:         );
 1733:     } else {
 1734:         if ($env{'form.action'} eq 'rename') {
 1735:             $r->print(
 1736:                  '<p>'.&Apache::lonhtmlcommon::confirm_success(&mt('Done')).'</p>'
 1737:                 .&Apache::lonhtmlcommon::actionbox(
 1738:                      ['<a href="'.&url($dest).'">'.&mt('Return to Directory').'</a>',
 1739:                       '<a href="'.&url($dest_newname).'">'.$disp_newname.'</a>']));
 1740:         } else {
 1741: 	    $r->print(&done($dest));
 1742: 	}
 1743:     }
 1744: }
 1745: 
 1746: sub handler {
 1747: 
 1748:     $r=shift;
 1749: 
 1750:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['decompress','action','filename','newfilename','mode']);
 1751: 
 1752:     &Debug($r, "loncfile.pm - handler entered");
 1753:     &Debug($r, " filename: ".$env{'form.filename'});
 1754:     &Debug($r, " newfilename: ".$env{'form.newfilename'});
 1755: #
 1756: # Determine the root filename
 1757: # This could come in as "filename", which actually is a URL, or
 1758: # as "qualifiedfilename", which is indeed a real filename in filesystem,
 1759: # or in value of decompress form element, or need to be extracted
 1760: # from %env from hashref retrieved for cgi.<id>.archive key, where id
 1761: # is a unique cgi_id created when an Author creates an archive of
 1762: # Authoring Space for download.
 1763: #
 1764:     my ($fn,$archiveref);
 1765: 
 1766:     if ($env{'form.filename'}) {
 1767: 	&Debug($r, "test: $env{'form.filename'}");
 1768: 	$fn=&unescape($env{'form.filename'});
 1769: 	$fn=&URLToPath($fn);
 1770:     } elsif ($env{'form.delarchive'}) {
 1771:         my ($delarchive,$suffix) = split(/\./,$env{'form.delarchive'});
 1772:         if (($delarchive) && (exists($env{'cgi.'.$delarchive.'.archive'}))) {
 1773:             $archiveref = &Apache::lonnet::thaw_unescape($env{'cgi.'.$delarchive.'.archive'});
 1774:             if (ref($archiveref) eq 'HASH') {
 1775:                 $fn = $archiveref->{'dir'};
 1776:             }
 1777:         }
 1778:     } elsif($ENV{'QUERY_STRING'} && $env{'form.phase'} ne 'two') {
 1779: 	#Just hijack the script only the first time around to inject the
 1780: 	#correct information for further processing
 1781: 	$fn=&unescape($env{'form.decompress'});
 1782: 	$fn=&URLToPath($fn);
 1783: 	$env{'form.action'}="decompress";
 1784:     } elsif ($env{'form.qualifiedfilename'}) {
 1785: 	$fn=$env{'form.qualifiedfilename'};
 1786:     } else {
 1787: 	&Debug($r, "loncfile::handler - no form.filename");
 1788: 	$r->log_reason($env{'user.name'}.' at '.$env{'user.domain'}.
 1789: 		       ' unspecified filename for cfile', $r->filename);
 1790: 	return HTTP_NOT_FOUND;
 1791:     }
 1792: 
 1793:     unless ($fn) {
 1794: 	&Debug($r, "loncfile::handler - doctored url is empty");
 1795: 	$r->log_reason($env{'user.name'}.' at '.$env{'user.domain'}.
 1796: 		       ' trying to cfile non-existing file', $r->filename);
 1797: 	return HTTP_NOT_FOUND;
 1798:     }
 1799: 
 1800: # ----------------------------------------------------------- Start page output
 1801: 
 1802:     my ($uname,$udom) = &Apache::lonnet::constructaccess($fn);
 1803:     &Debug($r,
 1804: 	   "loncfile::handler constructaccess uname = $uname domain = $udom");
 1805:     if (($uname eq '') || ($udom eq '')) {
 1806: 	$r->log_reason($uname.' at '.$udom.
 1807: 		       ' trying to manipulate file '.$env{'form.filename'}.
 1808: 		       ' ('.$fn.') - not authorized',
 1809: 		       $r->filename);
 1810: 	return HTTP_NOT_ACCEPTABLE;
 1811:     }
 1812:     if (($env{'form.delarchive'}) &&
 1813:         ($env{'environment.canarchive'})) {
 1814:         &Apache::loncommon::content_type($r,'text/plain');
 1815:         $r->send_http_header;
 1816:         $r->print(&Archive3($archiveref));
 1817:         return OK;
 1818:     }
 1819: 
 1820:     &Apache::loncommon::content_type($r,'text/html');
 1821:     $r->send_http_header;
 1822: 
 1823: # Declarations for items used for directory archive requests
 1824:     my ($js,$identifier,$defext,$archive_earlyout,$archive_idnum);
 1825:     my $args = {};
 1826: 
 1827:     if (($env{'form.action'} eq 'newdir') && ($env{'form.phase'} eq 'two') && 
 1828:         (($env{'form.callingmode'} eq 'testbank') || ($env{'form.callingmode'} eq 'imsimport'))) {
 1829: 	my $newdirname = $env{'form.newfilename'};
 1830:         &js_escape(\$newdirname);
 1831: 	$js = <<"ENDJS";
 1832: <script type="text/javascript">
 1833: // <![CDATA[
 1834: function writeDone() {
 1835:     window.focus();
 1836:     opener.document.info.newdir.value = "$newdirname";
 1837:     setTimeout("self.close()",10000);
 1838: }
 1839: // ]]>
 1840: </script>
 1841: ENDJS
 1842:         $args->{'add_entries'} = { onload => "writeDone()" };
 1843:     } elsif (($env{'form.action'} eq 'archive') &&
 1844:              ($env{'environment.canarchive'})) {
 1845: # Check if author already has an archive request in process
 1846:         ($archive_earlyout,$archive_idnum) = &archive_in_progress();
 1847: # Check if archive request was in process which author wishes to terminate
 1848:         if ($env{'form.remove_archive_request'}) {
 1849:             if ($env{'form.remove_archive_request'} eq $archive_idnum) {
 1850:                 if (exists($env{'cgi.'.$archive_idnum.'.archive'})) {
 1851:                     my $archiveref = &Apache::lonnet::thaw_unescape($env{'cgi.'.$archive_idnum.'.archive'});
 1852:                     if (ref($archiveref) eq 'HASH') {
 1853:                         $env{'form.delarchive'} = $archive_idnum.$archiveref->{'extension'};
 1854:                         if (&Archive3($archiveref)) {
 1855:                             ($archive_earlyout,$archive_idnum) = &archive_in_progress();
 1856:                         }
 1857:                         delete($env{'form.delarchive'});
 1858:                     }
 1859:                 }
 1860:             }
 1861:         }
 1862:         if ($archive_earlyout) {
 1863:             my $conftext =
 1864:                 &mt('Removing an existing request will terminate an active download of the archive file.');
 1865:             &js_escape(\$conftext);
 1866:             $js = <<"ENDJS";
 1867: <script type="text/javascript">
 1868: // <![CDATA[
 1869: function confirmation(form) {
 1870:     if (form.remove_archive_request.length) {
 1871:         for (var i=0; i<form.remove_archive_request.length; i++) {
 1872:             if (form.remove_archive_request[i].checked) {
 1873:                 if (form.remove_archive_request[i].value == '$archive_idnum') {
 1874:                     if (!confirm('$conftext')) {
 1875:                         return false;
 1876:                     }
 1877:                 }
 1878:             }
 1879:         }
 1880:     }
 1881:     return true;
 1882: }
 1883: // ]]>
 1884: </script>
 1885: 
 1886: ENDJS
 1887:         } else {
 1888:             if ($env{'form.phase'} eq 'two') {
 1889:                 $identifier = &Apache::loncommon::get_cgi_id();
 1890:                 $args->{'redirect'} = [0.1,"/cgi-bin/archive.pl?$identifier"];
 1891:             } else {
 1892:                 my (%location_of,%defaults);
 1893:                 $defext = &archive_tools(\%location_of,\%defaults);
 1894:                 my $check_uncheck_js = &Apache::loncommon::check_uncheck_jscript();
 1895:                 $js = <<"ENDJS";
 1896: <script type="text/javascript">
 1897: // <![CDATA[
 1898: function toggleCompression(form) {
 1899:     if (document.getElementById('tar_compression')) {
 1900:         if (form.format.length > 1) {
 1901:             for (var i=0; i<form.format.length; i++) {
 1902:                 if (form.format[i].checked) {
 1903:                     if (form.format[i].value == 'zip') {
 1904:                         document.getElementById('tar_compression').style.display = 'none';
 1905:                     } else if (form.format[i].value == 'tar') {
 1906:                         document.getElementById('tar_compression').style.display = 'block';
 1907:                     }
 1908:                     break;
 1909:                 }
 1910:             }
 1911:         }
 1912:     }
 1913:     setArchiveExt(form);
 1914:     return;
 1915: }
 1916: 
 1917: function setArchiveExt(form) {
 1918:     var newfmt;
 1919:     var newcomp;
 1920:     var newdef;
 1921:     if (document.getElementById('archiveext')) {
 1922:         if (form.format.length) {
 1923:             for (var i=0; i<form.format.length; i++) {
 1924:                 if (form.format[i].checked) {
 1925:                     newfmt = form.format[i].value;
 1926:                     break;
 1927:                 }
 1928:             }
 1929:         } else {
 1930:             newfmt = form.format[0];
 1931:         }
 1932:         if (newfmt == 'tar') {
 1933:             if (document.getElementById('tar_compression')) {
 1934:                 if (form.compress.length) {
 1935:                     for (var i=0; i<form.compress.length; i++) {
 1936:                         if (form.compress[i].checked) {
 1937:                             newcomp = form.compress[i].value;
 1938:                             break;
 1939:                         }
 1940:                     }
 1941:                 } else {
 1942:                     newcomp = form.compress[0];
 1943:                 }
 1944:             }
 1945:             if (newcomp == 'gzip') {
 1946:                 newdef = newfmt+'.gz';
 1947:             } else if (newcomp == 'bzip2') {
 1948:                 newdef = newfmt+'.bz2';
 1949:             } else if (newcomp == 'xz') {
 1950:                 newdef = newfmt+'.'+newcomp;
 1951:             } else {
 1952:                 newdef = newfmt;
 1953:             }
 1954:         } else if (newfmt == 'zip') {
 1955:             newdef = newfmt;
 1956:         }
 1957:         if ((newdef == '') || (newdef == undefined) || (newdef == null)) {
 1958:             newdef = '.$defext';
 1959:         }
 1960:         document.getElementById('archiveext').value = newdef;
 1961:     }
 1962: }
 1963: 
 1964: function resetForm() {
 1965:     if (document.phaseone.filetype.length) {
 1966:         for (var i=0; i<document.phaseone.filetype.length; i++) {
 1967:             document.phaseone.filetype[i].checked = false;
 1968:         }
 1969:     }
 1970:     if (document.getElementById('tar_compression')) { 
 1971:         if (document.phaseone.format.length) {
 1972:             document.getElementById('tar_compression').style.display = 'block';
 1973:             for (var i=0; i<document.phaseone.format.length; i++) {
 1974:                 if (document.phaseone.format[i].value == 'tar') {
 1975:                     document.phaseone.format[i].checked = true;  
 1976:                 } else {
 1977:                     document.phaseone.format[i].checked = false;
 1978:                 }
 1979:             }
 1980:         }
 1981:         if (document.phaseone.compress.length) {
 1982:             for (var i=0; i<document.phaseone.compress.length; i++) {
 1983:                 if (document.phaseone.compress[i].value == 'gzip') {
 1984:                     document.phaseone.compress[i].checked = true;
 1985:                 } else {
 1986:                     document.phaseone.compress[i].checked = false;
 1987:                 }
 1988:             }
 1989:         }
 1990:     }
 1991:     document.phaseone.recurse.checked = false;
 1992:     var a = document.createElement('a');
 1993:     var vis;
 1994:     if (typeof a.download != "undefined") {
 1995:         document.phaseone.adload.value = '1';
 1996:         if (document.getElementById('archive_saveas')) {
 1997:             document.getElementById('archive_saveas').style.display = 'block';
 1998:             vis = '1';
 1999:         }
 2000:     }
 2001:     if (vis == '1') {
 2002:         if (document.getElementById('archiveext')) {
 2003:             document.getElementById('archiveext').value='.$defext';
 2004:         }
 2005:     } else {
 2006:         if (document.getElementById('archive_saveas')) {
 2007:             document.getElementById('archive_saveas').style.display = 'none';
 2008:         }
 2009:         if (document.getElementById('archiveext')) {
 2010:             document.getElementById('archiveext').value='';
 2011:         }
 2012:     }
 2013: }
 2014: 
 2015: $check_uncheck_js
 2016: 
 2017: // ]]>
 2018: </script>
 2019: 
 2020: ENDJS
 2021:                 $args->{'add_entries'} = { onload => "resetForm()" };
 2022:             }
 2023:         }
 2024:     }
 2025:     my $londocroot = $r->dir_config('lonDocRoot');
 2026:     my $trailfile = $fn;
 2027:     $trailfile =~ s{^/(priv/)}{$londocroot/$1};
 2028: 
 2029:     # Breadcrumbs
 2030:     my $crsauthor;
 2031:     my $text = 'Authoring Space';
 2032:     my $title = 'Authoring Space File Operation',
 2033:     my $href = &Apache::loncommon::authorspace(&url($fn));
 2034:     if ($env{'request.course.id'}) {
 2035:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2036:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2037:         if ($href eq "/priv/$cdom/$cnum/") {
 2038:             $text = 'Course Authoring Space';
 2039:             $title = 'Course Authoring Space File Operation',
 2040:             $crsauthor = 1;
 2041:         }
 2042:     }
 2043:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 2044:     &Apache::lonhtmlcommon::add_breadcrumb({
 2045:         'text'  => $text,
 2046:         'href'  => $href,
 2047:     });
 2048:     &Apache::lonhtmlcommon::add_breadcrumb({
 2049:         'text'  => 'File Operation',
 2050:         'title' => $title,
 2051:         'href'  => '',
 2052:     });
 2053: 
 2054:     $r->print(&Apache::loncommon::start_page($title,$js,$args)
 2055:              .&Apache::lonhtmlcommon::breadcrumbs()
 2056:              .&Apache::loncommon::head_subbox(
 2057:                   &Apache::loncommon::CSTR_pageheader($trailfile))
 2058:     );
 2059: 
 2060:     unless ($env{'form.action'} eq 'archive') {
 2061:         $r->print('<p>'.&mt('Location').': '.&display($fn).'</p>');
 2062:     }
 2063: 
 2064:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 2065:         unless ($crsauthor) {
 2066:             $r->print('<p class="LC_info">'
 2067:                      .&mt('Co-Author [_1]',$uname.':'.$udom)
 2068:                      .'</p>'
 2069:             );
 2070:         }
 2071:     }
 2072: 
 2073: 
 2074:     &Debug($r, "loncfile::handler Form action is $env{'form.action'} ");
 2075:     my %action = &Apache::lonlocal::texthash(
 2076:         'delete'          => 'Delete',
 2077:         'rename'          => 'Rename',
 2078:         'move'            => 'Move',
 2079:         'newdir'          => 'New Directory',
 2080:         'decompress'      => 'Decompress',
 2081:         'archive'         => 'Export directory to archive file',
 2082:         'copy'            => 'Copy',
 2083:         'newfile'         => 'New Resource',
 2084: 	'newhtmlfile'     => 'New Resource',
 2085: 	'newproblemfile'  => 'New Resource',
 2086: 	'newpagefile'     => 'New Resource',
 2087: 	'newsequencefile' => 'New Resource',
 2088: 	'newrightsfile'   => 'New Resource',
 2089: 	'newstyfile'      => 'New Resource',
 2090: 	'newtaskfile'     => 'New Resource',
 2091:         'newlibraryfile'  => 'New Resource',
 2092: 	'Select Action'   => 'New Resource',
 2093:     );
 2094:     if ($action{$env{'form.action'}}) {
 2095:         if ($crsauthor) {
 2096:             my @disallowed = qw(page sequence rights library);
 2097:             my $newtype;
 2098:             if ($env{'form.action'} =~ /^new(\w+)file$/) {
 2099:                 $newtype = $1;
 2100:             } elsif ($env{'form.action'} eq 'newfile') {
 2101:                 ($newtype) = ($env{'form.newfilename'} =~ m{\.([^/.]+)$});
 2102:                 $newtype = lc($newtype);
 2103:             }
 2104:             if (($newtype ne '') &&
 2105:                 (grep(/^\Q$newtype\E$/,@disallowed))) {
 2106:                 $r->print('<p class="LC_error">'
 2107:                          .&mt('Creation of a new file of type: [_1] is not permitted in Course Authoring Space',$newtype)
 2108:                          .'</p>'
 2109:                          .&Apache::loncommon::end_page()
 2110:                 );
 2111:                 return OK;
 2112:             }
 2113:             if ($env{'form.action'} eq 'archive') {
 2114:                 $r->print('<p>'.&mt('Location').': '.&display($fn).'</p>'."\n".
 2115:                           '<p class="LC_error">'.
 2116:                           &mt('Export to an archive file is not permitted in Course Authoring Space').
 2117:                           '</p>'."\n".
 2118:                           &Apache::loncommon::end_page());
 2119:                 return OK; 
 2120:             }
 2121:         } elsif ($env{'form.action'} eq 'archive') {
 2122:             if ($env{'environment.canarchive'}) {
 2123:                 if ($archive_earlyout) {
 2124:                     my $fname = &url($fn);
 2125:                     my $title = $action{$env{'form.action'}};
 2126:                     &cancel_archive_form($r,$title,$fname,$archive_earlyout,$archive_idnum);
 2127:                     &CloseForm1($r,$fn);
 2128:                     $r->print(&Apache::loncommon::end_page());
 2129:                     return OK;
 2130:                 }
 2131:             } else {
 2132:                 $r->print('<p>'.&mt('Location').': '.&display($fn).'</p>'."\n".
 2133:                           '<p class="LC_error">'.
 2134:                           &mt('You do not have permission to export to an archive file in this Authoring Space').
 2135:                           '</p>'."\n".
 2136:                           &Apache::loncommon::end_page());
 2137:                 return OK;
 2138:             }
 2139:         }
 2140:         $r->print('<h2>'.$action{$env{'form.action'}}.'</h2>'."\n");
 2141:     } else {
 2142:         $r->print('<p class="LC_error">'
 2143:                  .&mt('Unknown Action: [_1]',$env{'form.action'})
 2144:                  .'</p>'
 2145:                  .&Apache::loncommon::end_page()
 2146:         );
 2147:         return OK;
 2148:     }
 2149: 
 2150:     if ($env{'form.phase'} eq 'two') {
 2151: 	&Debug($r, "loncfile::handler  entering phase2");
 2152: 	&phasetwo($r,$fn,$uname,$udom,$identifier);
 2153:     } else {
 2154: 	&Debug($r, "loncfile::handler  entering phase1");
 2155: 	&phaseone($r,$fn,$uname,$udom);
 2156:     }
 2157: 
 2158:     $r->print(&Apache::loncommon::end_page());
 2159:     return OK;
 2160: }
 2161: 
 2162: 1;
 2163: __END__
 2164: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>