Annotation of loncom/publisher/lonupload.pm, revision 1.39

1.12      foxr        1: 
1.1       www         2: # The LearningOnline Network with CAPA
                      3: # Handler to upload files into construction space
                      4: #
1.39    ! jms         5: # $Id: lonupload.pm,v 1.38 2008/07/18 03:27:48 raeburn Exp $
1.8       matthew     6: #
                      7: # Copyright Michigan State University Board of Trustees
                      8: #
                      9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                     10: #
                     11: # LON-CAPA is free software; you can redistribute it and/or modify
                     12: # it under the terms of the GNU General Public License as published by
                     13: # the Free Software Foundation; either version 2 of the License, or
                     14: # (at your option) any later version.
                     15: #
                     16: # LON-CAPA is distributed in the hope that it will be useful,
                     17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     19: # GNU General Public License for more details.
                     20: #
                     21: # You should have received a copy of the GNU General Public License
                     22: # along with LON-CAPA; if not, write to the Free Software
                     23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     24: #
                     25: # /home/httpd/html/adm/gpl.txt
                     26: #
                     27: # http://www.lon-capa.org/
                     28: #
1.10      harris41   29: ###
1.1       www        30: 
1.39    ! jms        31: =head1 NAME
        !            32: 
        !            33: Apache::lonupload - upload files into construction space
        !            34: 
        !            35: =head1 SYNOPSIS
        !            36: 
        !            37: Invoked by /etc/httpd/conf/srm.conf:
        !            38: 
        !            39:  <Location /adm/upload>
        !            40:  PerlAccessHandler       Apache::lonacc
        !            41:  SetHandler perl-script
        !            42:  PerlHandler Apache::lonupload
        !            43:  ErrorDocument     403 /adm/login
        !            44:  ErrorDocument     404 /adm/notfound.html
        !            45:  ErrorDocument     406 /adm/unauthorized.html
        !            46:  ErrorDocument	  500 /adm/errorhandler
        !            47:  </Location>
        !            48: 
        !            49: =head1 INTRODUCTION
        !            50: 
        !            51: This module uploads a file sitting on a client computer into 
        !            52: library server construction space.
        !            53: 
        !            54: This is part of the LearningOnline Network with CAPA project
        !            55: described at http://www.lon-capa.org.
        !            56: 
        !            57: =head1 HANDLER SUBROUTINE
        !            58: 
        !            59: This routine is called by Apache and mod_perl.
        !            60: 
        !            61: =over 4
        !            62: 
        !            63: =item *
        !            64: 
        !            65: Initialize variables
        !            66: 
        !            67: =item *
        !            68: 
        !            69: Start page output
        !            70: 
        !            71: =item *
        !            72: 
        !            73: output relevant interface phase (phaseone or phasetwo or phasethree)
        !            74: 
        !            75: =item *
        !            76: 
        !            77: (phase one is to specify upload file; phase two is to handle conditions
        !            78: subsequent to specification--like overwriting an existing file; phase three
        !            79: is to handle processing of secondary uploads - of embedded objects in an
        !            80: html file).
        !            81: 
        !            82: =back
        !            83: 
        !            84: =head1 OTHER SUBROUTINES
        !            85: 
        !            86: =over 4
        !            87: 
        !            88: =item *
        !            89: 
        !            90: phaseone() : Interface for specifying file to upload.
        !            91: 
        !            92: =item *
        !            93: 
        !            94: phasetwo() : Interface for handling post-conditions about uploading (such
        !            95: as overwriting an existing file).
        !            96: 
        !            97: =item *
        !            98: 
        !            99: phasethree() : Interface for handling secondary uploads of embedded objects
        !           100: in an html file.
        !           101: 
        !           102: =item *
        !           103: 
        !           104: upfile_store() : Store contents of uploaded file into temporary space.  Invoked
        !           105: by phaseone subroutine.
        !           106: 
        !           107: =item *
        !           108: 
        !           109: check_extension() : Checks if filename extension is permitted and checks type
        !           110:  of file - if html file, calls parser to check for embedded objects.
        !           111:  Invoked by phasetwo subroutine.
        !           112: 
        !           113: =back
        !           114: 
        !           115: =cut
        !           116: 
1.1       www       117: package Apache::lonupload;
                    118: 
                    119: use strict;
                    120: use Apache::File;
                    121: use File::Copy;
1.13      foxr      122: use File::Basename;
1.1       www       123: use Apache::Constants qw(:common :http :methods);
1.3       www       124: use Apache::loncacc;
1.10      harris41  125: use Apache::loncommon();
1.13      foxr      126: use Apache::lonnet;
1.14      foxr      127: use HTML::Entities();
1.20      www       128: use Apache::lonlocal;
1.29      albertel  129: use Apache::lonnet;
1.34      albertel  130: use LONCAPA();
1.12      foxr      131: 
                    132: my $DEBUG=0;
                    133: 
                    134: sub Debug {
1.30      albertel  135:     # Put out the indicated message but only if DEBUG is true.
1.22      albertel  136:     if ($DEBUG) {
1.30      albertel  137: 	my ($r,$message) = @_;
                    138: 	$r->log_reason($message);
1.22      albertel  139:     }
1.12      foxr      140: }
1.1       www       141: 
1.2       www       142: sub upfile_store {
                    143:     my $r=shift;
                    144: 	
1.29      albertel  145:     my $fname=$env{'form.upfile.filename'};
1.2       www       146:     $fname=~s/\W//g;
                    147:     
1.29      albertel  148:     chomp($env{'form.upfile'});
1.1       www       149:   
1.29      albertel  150:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
1.2       www       151: 		  '_upload_'.$fname.'_'.time.'_'.$$;
                    152:     {
                    153:        my $fh=Apache::File->new('>'.$r->dir_config('lonDaemons').
                    154:                                    '/tmp/'.$datatoken.'.tmp');
1.29      albertel  155:        print $fh $env{'form.upfile'};
1.1       www       156:     }
1.2       www       157:     return $datatoken;
                    158: }
                    159: 
                    160: sub phaseone {
1.25      raeburn   161:     my ($r,$fn,$uname,$udom,$mode)=@_;
                    162:     my $action = '/adm/upload';
                    163:     if ($mode eq 'testbank') {
                    164:         $action = '/adm/testbank';
                    165:     } elsif ($mode eq 'imsimport') {
                    166:         $action = '/adm/imsimport';
                    167:     }
1.29      albertel  168:     $env{'form.upfile.filename'}=~s/\\/\//g;
                    169:     $env{'form.upfile.filename'}=~s/^.*\/([^\/]+)$/$1/;
                    170:     if ($env{'form.upfile.filename'}) {
1.22      albertel  171: 	$fn=~s/\/[^\/]+$//;
                    172: 	$fn=~s/([^\/])$/$1\//;
1.29      albertel  173: 	$fn.=$env{'form.upfile.filename'};
1.22      albertel  174: 	$fn=~s/^\///;
                    175: 	$fn=~s/(\/)+/\//g;
1.13      foxr      176: 
                    177: #    Fn is the full path to the destination filename.
                    178: #    
                    179: 
1.22      albertel  180: 	&Debug($r, "Filename for upload: $fn");
                    181: 	if (($fn) && ($fn!~/\/$/)) {
1.28      raeburn   182: 	    $r->print('<form action="'.$action.'" method="post" name="fileupload">'.
1.23      albertel  183: 		      '<input type="hidden" name="phase" value="two" />'.
                    184: 		      '<input type="hidden" name="datatoken" value="'.
                    185: 		      &upfile_store.'" />'.
                    186: 		      '<input type="hidden" name="uploaduname" value="'.$uname.
1.35      albertel  187: 		      '" />'.&mt('Save uploaded file as ').
1.33      albertel  188:                       "<span class='LC_filename'>/priv/$uname/</span>".
1.25      raeburn   189:                       '<input type="text" size="50" name="filename" value="'.$fn.
1.33      albertel  190:                       '" /><br />'.
                    191: 		      '<br />'.&mt('Choose file type:').'
1.25      raeburn   192: <select name="filetype">
                    193:  <option value="standard" selected>'.&mt('Regular file').'
                    194:  <option value="testbank">'.&mt('Testbank file').'
                    195:  <option value="imsimport">'.&mt('IMS package').'
1.33      albertel  196: </select>'.&Apache::loncommon::help_open_topic("Uploading_File_Options").'
1.25      raeburn   197: <br />
                    198: <br />
                    199: ');
1.35      albertel  200:             $r->print('<input type="button" value="'.&mt('Save').'" onClick="javascript:verifyForm()"/></form>');
1.22      albertel  201: 	    # Check for bad extension and warn user
                    202: 	    if ($fn=~/\.(\w+)$/ && 
                    203: 		(&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.33      albertel  204: 		$r->print('<span class="LC_error">'.&mt('The extension on this file,').
1.22      albertel  205: 			  ' "'.$1.'"'.&mt(', is reserved internally by LON-CAPA.').
1.33      albertel  206: 			  ' <br />'.&mt('Please change the extension.').'</span>');
1.22      albertel  207: 	    } elsif($fn=~/\.(\w+)$/ && 
                    208: 		    !defined(&Apache::loncommon::fileembstyle($1))) {
1.33      albertel  209: 		$r->print('<span class="LC_error">'.&mt('The extension on this file,').
1.22      albertel  210: 			  ' "'.$1.'"'.&mt(', is not recognized by LON-CAPA.').
1.23      albertel  211: 			  ' <br />'.&mt('Please change the extension.').
1.33      albertel  212: 			  '</span>');
1.22      albertel  213: 	    }
                    214: 	} else {
1.33      albertel  215: 	    $r->print('<span class="LC_error">'.&mt('Illegal filename.').'</span>');
1.22      albertel  216: 	}
                    217:     } else {
1.33      albertel  218: 	$r->print('<span class="LC_error">'.&mt('No upload file specified.').'</span>');
1.22      albertel  219:     }
1.1       www       220: }
                    221: 
                    222: sub phasetwo {
1.25      raeburn   223:     my ($r,$tfn,$uname,$udom,$mode)=@_;
1.37      raeburn   224:     my $output;
1.25      raeburn   225:     my $action = '/adm/upload';
                    226:     my $returnflag = '';
                    227:     if ($mode eq 'testbank') {
                    228:         $action = '/adm/testbank';
                    229:     } elsif ($mode eq 'imsimport') {
                    230:         $action = '/adm/imsimport';
                    231:     }
1.22      albertel  232:     my $fn='/priv/'.$uname.'/'.$tfn;
                    233:     $fn=~s/\/+/\//g;
                    234:     &Debug($r, "Filename is ".$tfn);
                    235:     if ($tfn) {
                    236: 	&Debug($r, "Filename for tfn = ".$tfn);
                    237: 	my $target='/home/'.$uname.'/public_html'.$tfn;
                    238: 	&Debug($r, "target -> ".$target);
1.13      foxr      239: #     target is the full filesystem path of the destination file.
1.22      albertel  240: 	my $base = &File::Basename::basename($fn);
                    241: 	my $path = &File::Basename::dirname($fn);
1.26      albertel  242: 	$base    = &HTML::Entities::encode($base,'<>&"');
1.22      albertel  243: 	my $url  = $path."/".$base; 
                    244: 	&Debug($r, "URL is now ".$url);
1.29      albertel  245: 	my $datatoken=$env{'form.datatoken'};
1.22      albertel  246: 	if (($fn) && ($datatoken)) {
1.36      www       247:             if ($env{'form.cancel'}) {
                    248:                 my $source=$r->dir_config('lonDaemons').'/tmp/'.$datatoken.'.tmp';
                    249:                 my $dirpath=$path.'/';
                    250:                 $dirpath=~s/\/+/\//g;
1.37      raeburn   251:                 $output .= &mt('Upload cancelled.').'<br /><font size="+2"><a href="'.$dirpath.'">'.
                    252:                           &mt('Back to Directory').'</a></font>';
1.36      www       253: 	    } elsif ((-e $target) && (!$env{'form.override'})) {
1.37      raeburn   254: 		$output .= '<form action="'.$action.'" method="post">'.
1.36      www       255: 			  &mt('File [_1] exists. Overwrite?','<span class="LC_filename">'.$fn.'</span>').
1.23      albertel  256: 			  '<input type="hidden" name="phase" value="two" />'.
1.37      raeburn   257: 			  '<input type="hidden" name="filename" value="'.$url.'" />'.
1.23      albertel  258: 			  '<input type="hidden" name="datatoken" value="'.$datatoken.'" />'.
1.36      www       259: 			  '<input type="submit" name="override" value="'.&mt('Yes').'" />'.
                    260:                           '<input type="submit" name="cancel" value="'.&mt('Cancel').'" />'.
1.37      raeburn   261:                           '</form>';
1.36      www       262:             } else {
1.22      albertel  263: 		my $source=$r->dir_config('lonDaemons').'/tmp/'.$datatoken.'.tmp';
1.27      www       264: 		my $dirpath=$path.'/';
                    265: 		$dirpath=~s/\/+/\//g;
1.22      albertel  266: 		# Check for bad extension and disallow upload
1.37      raeburn   267:                 my $result;
                    268:                 ($result,$returnflag) = &check_extension($fn,$mode,$source,$target,$action,$dirpath,$url);
                    269:                 $output .= $result;
1.22      albertel  270: 	    }
                    271: 	} else {
1.37      raeburn   272: 	    $output .= '<span class="LC_error">'.
1.22      albertel  273: 		      &mt('Please use browser "Back" button and pick a filename').
1.37      raeburn   274: 		      '</span><br />';
1.22      albertel  275: 	}
1.1       www       276:     } else {
1.37      raeburn   277: 	$output .= '<span class="LC_error">'.
                    278: 		   &mt('Please use browser "Back" button and pick a filename').
                    279: 		   '</span><br />';
                    280:     }
                    281:     return ($output,$returnflag);
                    282: }
                    283: 
                    284: sub check_extension {
                    285:     my ($fn,$mode,$source,$target,$action,$dirpath,$url) = @_;
                    286:     my ($result,$returnflag);
                    287:     # Check for bad extension and disallow upload
                    288:     if ($fn=~/\.(\w+)$/ &&
                    289:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
                    290:         $result .= &mt('File [_1] could not be copied.',
                    291:                       '<span class="LC_filename">'.$fn.'</span> ').
                    292:                   '<br /><span class="LC_error">'.
                    293:                   &mt('The extension on this file is reserved internally by LON-CAPA.').
                    294:                   '</span>';
                    295:     } elsif ($fn=~/\.(\w+)$/ &&
                    296:              !defined(&Apache::loncommon::fileembstyle($1))) {
                    297:         $result .= &mt('File [_1] could not be copied.',
                    298:                       '<span class="LC_filename">'.$fn.'</span> ').
                    299:                   '<br /><span class="LC_error">'.
                    300:                   &mt('The extension on this file is not recognized by LON-CAPA.').
                    301:                   '</span>';
                    302:     } elsif (-d $target) {
                    303:         $result .= &mt('File [_1] could not be copied.',
                    304:                       '<span class="LC_filename">'.$fn.'</span>').
                    305:                   '<br /><span class="LC_error">'.
                    306:                   &mt('The target is an existing directory.').
                    307:                   '</span>';
                    308:     } elsif (copy($source,$target)) {
                    309:         chmod(0660, $target); # Set permissions to rw-rw---.
                    310:         if ($mode eq 'testbank' || $mode eq 'imsimport') {
                    311:             $returnflag = 'ok';
                    312:             $result .= &mt('Your file - [_1] - was uploaded successfully',$fn).'<br /><br />';
                    313:         } else {
                    314:             $result .= &mt('File copied.').'<br />';
                    315:         }
                    316:         # Check for embedded objects.
                    317:         my (%allfiles,%codebase);
                    318:         my ($text,$header,$css,$js);
                    319:         if (($mode ne 'imsimport') && ($target =~ /\.(htm|html|shtml)$/i)) {
                    320:             my (%allfiles,%codebase);
                    321:             &Apache::lonnet::extract_embedded_items($target,\%allfiles,\%codebase);
                    322:             if (keys(%allfiles) > 0) {
                    323:                 my $state = <<STATE;
                    324:     <input type="hidden" name="action"      value="upload_embedded" />
                    325:     <input type="hidden" name="currentpath" value="$env{'form.currentpath'}" />
                    326:     <input type="hidden" name="mode"        value="$mode" />
                    327:     <input type="hidden" name="phase"       value="three" />
                    328:     <input type="hidden" name="filename" value="$url" />
                    329: STATE
                    330:                 $result .= "<h3>".&mt("Reference Warning")."</h3>".
                    331:                            "<p>".&mt("Completed upload of the file. This file contained references to other files.")."</p>".
                    332:                           "<p>".&mt("Please select the locations from which the referenced files are to be uploaded.")."</p>".
                    333:                           &Apache::loncommon::ask_for_embedded_content($action,$state,\%allfiles,\%codebase,
                    334:                                       {'error_on_invalid_names'   => 1,
                    335:                                        'ignore_remote_references' => 1,});
                    336:                 if ($mode eq 'testbank') {
                    337:                     $returnflag = 'embedded';
                    338:                     $result .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without these files','<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
                    339:                 }
                    340:             }
                    341:         }
                    342:         if (($mode ne 'imsimport') && ($mode ne 'testbank')) {
                    343:             $result .= '<br /><font size="+2"><a href="'.$url.'">'.
                    344:                         &mt('View file').'</a></font>';
                    345:         }
                    346:     } else {
                    347:         $result .= &mt('Failed to copy: [_1].',$!);
                    348:     }
                    349:     if ($mode ne 'imsimport' && $mode ne 'testbank') {
                    350:         $result .= '<br /><font size="+2"><a href="'.$dirpath.'">'.
                    351:                    &mt('Back to Directory').'</a></font><br />';
                    352:     }
                    353:     return ($result,$returnflag);
                    354: }
                    355: 
                    356: sub phasethree {
                    357:     my ($r,$fn,$uname,$udom,$mode) = @_;
                    358:     my $result;
                    359:     my $dir_root = '/home/'.$uname.'/public_html';
                    360:     my $url_root = '/priv/'.$uname;
                    361:     my $base = &File::Basename::basename($fn);
                    362:     my $path = &File::Basename::dirname($fn);
                    363:     $result = &Apache::loncommon::upload_embedded($mode,$path,$uname,$udom,
                    364:                                                   $dir_root,$url_root);
                    365:     if ($mode ne 'imsimport' && $mode ne 'testbank') {
                    366:         $result = '<br /><font size="+2"><a href="'.$url_root.$fn.'">'.
                    367:                   &mt('View main file').'</a></font>'.
                    368:                   '<br /><font size="+2"><a href="'.$url_root.$path.'">'.
                    369:                   &mt('Back to Directory').'</a></font><br />';
1.1       www       370:     }
1.37      raeburn   371:     return $result;
1.1       www       372: }
                    373: 
1.10      harris41  374: # ---------------------------------------------------------------- Main Handler
1.1       www       375: sub handler {
                    376: 
1.22      albertel  377:     my $r=shift;
1.1       www       378: 
1.22      albertel  379:     my $uname;
                    380:     my $udom;
1.25      raeburn   381:     my $javascript = '';
1.18      www       382: #
                    383: # phase two: re-attach user
                    384: #
1.29      albertel  385:     if ($env{'form.uploaduname'}) {
                    386: 	$env{'form.filename'}='/priv/'.$env{'form.uploaduname'}.'/'.
                    387: 	    $env{'form.filename'};
1.22      albertel  388:     }
                    389: 
1.29      albertel  390:     unless ($env{'form.phase'} eq 'two') {
1.25      raeburn   391:         $javascript = qq|
                    392: function verifyForm() {
1.28      raeburn   393:     var mode = document.fileupload.filetype.options[document.fileupload.filetype.selectedIndex].value
1.25      raeburn   394:     if (mode == "testbank") {
1.28      raeburn   395:         document.fileupload.action = "/adm/testbank";
1.25      raeburn   396:     }
                    397:     if (mode == "imsimport") {
1.28      raeburn   398:         document.fileupload.action = "/adm/imsimport";
1.25      raeburn   399:     }
                    400:     if (mode == "standard") {
1.28      raeburn   401:         document.fileupload.action = "/adm/upload";
1.25      raeburn   402:     }
1.28      raeburn   403:     document.fileupload.submit();
1.25      raeburn   404: }
1.33      albertel  405: 	|;
1.25      raeburn   406:     }
1.22      albertel  407:     ($uname,$udom)=
1.29      albertel  408: 	&Apache::loncacc::constructaccess($env{'form.filename'},
1.22      albertel  409: 					  $r->dir_config('lonDefDomain'));
1.37      raeburn   410: 
1.22      albertel  411:     unless (($uname) && ($udom)) {
                    412: 	$r->log_reason($uname.' at '.$udom.
1.29      albertel  413: 		       ' trying to publish file '.$env{'form.filename'}.
1.22      albertel  414: 		       ' - not authorized', 
                    415: 		       $r->filename); 
                    416: 	return HTTP_NOT_ACCEPTABLE;
                    417:     }
                    418:     
                    419:     my $fn;
1.29      albertel  420:     if ($env{'form.filename'}) {
                    421: 	$fn=$env{'form.filename'};
1.22      albertel  422: 	$fn=~s/^http\:\/\/[^\/]+\///;
                    423: 	$fn=~s/^\///;
1.34      albertel  424: 	$fn=~s{(~|priv/)($LONCAPA::username_re)}{};
1.22      albertel  425: 	$fn=~s/\/+/\//g;
                    426:     } else {
1.29      albertel  427: 	$r->log_reason($env{'user.name'}.' at '.$env{'user.domain'}.
1.22      albertel  428: 		       ' unspecified filename for upload', $r->filename); 
                    429: 	return HTTP_NOT_FOUND;
                    430:     }
1.1       www       431: 
                    432: # ----------------------------------------------------------- Start page output
                    433: 
                    434: 
1.22      albertel  435:     &Apache::loncommon::content_type($r,'text/html');
                    436:     $r->send_http_header;
1.1       www       437: 
1.31      albertel  438:    $javascript = "<script type=\"text/javascript\">\n//<!--\n".
                    439: 	$javascript."\n// --></script>\n";
1.1       www       440: 
1.31      albertel  441:     $r->print(&Apache::loncommon::start_page('Upload file to Construction Space',
                    442: 					     $javascript));
1.3       www       443:   
1.29      albertel  444:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.37      raeburn   445: 	$r->print('<h3><span class="LC_error">'.&mt('Co-Author').': '.$uname.
                    446: 		  &mt(' at ').$udom.'</span></h3>');
1.22      albertel  447:     }
                    448: 
1.37      raeburn   449:     if ($env{'form.phase'} eq 'three') {
                    450:         my $output = &phasethree($r,$fn,$uname,$udom,'author');
                    451:         $r->print($output);
                    452:     } elsif ($env{'form.phase'} eq 'two') {
                    453: 	my ($output,$returnflag) = &phasetwo($r,$fn,$uname,$udom);
                    454:         $r->print($output);
1.22      albertel  455:     } else {
                    456: 	&phaseone($r,$fn,$uname,$udom);
                    457:     }
1.1       www       458: 
1.31      albertel  459:     $r->print(&Apache::loncommon::end_page());
1.22      albertel  460:     return OK;  
1.1       www       461: }
1.7       www       462: 
                    463: 1;
                    464: __END__
1.10      harris41  465: 
                    466: 

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