File:  [LON-CAPA] / loncom / publisher / lonupload.pm
Revision 1.39: download - view: text, annotated - select for diffs
Mon Nov 10 13:20:04 2008 UTC (15 years, 6 months ago) by jms
Branches: MAIN
CVS tags: HEAD
POD documentation changes

    1: 
    2: # The LearningOnline Network with CAPA
    3: # Handler to upload files into construction space
    4: #
    5: # $Id: lonupload.pm,v 1.39 2008/11/10 13:20:04 jms Exp $
    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: #
   29: ###
   30: 
   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: 
  117: package Apache::lonupload;
  118: 
  119: use strict;
  120: use Apache::File;
  121: use File::Copy;
  122: use File::Basename;
  123: use Apache::Constants qw(:common :http :methods);
  124: use Apache::loncacc;
  125: use Apache::loncommon();
  126: use Apache::lonnet;
  127: use HTML::Entities();
  128: use Apache::lonlocal;
  129: use Apache::lonnet;
  130: use LONCAPA();
  131: 
  132: my $DEBUG=0;
  133: 
  134: sub Debug {
  135:     # Put out the indicated message but only if DEBUG is true.
  136:     if ($DEBUG) {
  137: 	my ($r,$message) = @_;
  138: 	$r->log_reason($message);
  139:     }
  140: }
  141: 
  142: sub upfile_store {
  143:     my $r=shift;
  144: 	
  145:     my $fname=$env{'form.upfile.filename'};
  146:     $fname=~s/\W//g;
  147:     
  148:     chomp($env{'form.upfile'});
  149:   
  150:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
  151: 		  '_upload_'.$fname.'_'.time.'_'.$$;
  152:     {
  153:        my $fh=Apache::File->new('>'.$r->dir_config('lonDaemons').
  154:                                    '/tmp/'.$datatoken.'.tmp');
  155:        print $fh $env{'form.upfile'};
  156:     }
  157:     return $datatoken;
  158: }
  159: 
  160: sub phaseone {
  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:     }
  168:     $env{'form.upfile.filename'}=~s/\\/\//g;
  169:     $env{'form.upfile.filename'}=~s/^.*\/([^\/]+)$/$1/;
  170:     if ($env{'form.upfile.filename'}) {
  171: 	$fn=~s/\/[^\/]+$//;
  172: 	$fn=~s/([^\/])$/$1\//;
  173: 	$fn.=$env{'form.upfile.filename'};
  174: 	$fn=~s/^\///;
  175: 	$fn=~s/(\/)+/\//g;
  176: 
  177: #    Fn is the full path to the destination filename.
  178: #    
  179: 
  180: 	&Debug($r, "Filename for upload: $fn");
  181: 	if (($fn) && ($fn!~/\/$/)) {
  182: 	    $r->print('<form action="'.$action.'" method="post" name="fileupload">'.
  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.
  187: 		      '" />'.&mt('Save uploaded file as ').
  188:                       "<span class='LC_filename'>/priv/$uname/</span>".
  189:                       '<input type="text" size="50" name="filename" value="'.$fn.
  190:                       '" /><br />'.
  191: 		      '<br />'.&mt('Choose file type:').'
  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').'
  196: </select>'.&Apache::loncommon::help_open_topic("Uploading_File_Options").'
  197: <br />
  198: <br />
  199: ');
  200:             $r->print('<input type="button" value="'.&mt('Save').'" onClick="javascript:verifyForm()"/></form>');
  201: 	    # Check for bad extension and warn user
  202: 	    if ($fn=~/\.(\w+)$/ && 
  203: 		(&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
  204: 		$r->print('<span class="LC_error">'.&mt('The extension on this file,').
  205: 			  ' "'.$1.'"'.&mt(', is reserved internally by LON-CAPA.').
  206: 			  ' <br />'.&mt('Please change the extension.').'</span>');
  207: 	    } elsif($fn=~/\.(\w+)$/ && 
  208: 		    !defined(&Apache::loncommon::fileembstyle($1))) {
  209: 		$r->print('<span class="LC_error">'.&mt('The extension on this file,').
  210: 			  ' "'.$1.'"'.&mt(', is not recognized by LON-CAPA.').
  211: 			  ' <br />'.&mt('Please change the extension.').
  212: 			  '</span>');
  213: 	    }
  214: 	} else {
  215: 	    $r->print('<span class="LC_error">'.&mt('Illegal filename.').'</span>');
  216: 	}
  217:     } else {
  218: 	$r->print('<span class="LC_error">'.&mt('No upload file specified.').'</span>');
  219:     }
  220: }
  221: 
  222: sub phasetwo {
  223:     my ($r,$tfn,$uname,$udom,$mode)=@_;
  224:     my $output;
  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:     }
  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);
  239: #     target is the full filesystem path of the destination file.
  240: 	my $base = &File::Basename::basename($fn);
  241: 	my $path = &File::Basename::dirname($fn);
  242: 	$base    = &HTML::Entities::encode($base,'<>&"');
  243: 	my $url  = $path."/".$base; 
  244: 	&Debug($r, "URL is now ".$url);
  245: 	my $datatoken=$env{'form.datatoken'};
  246: 	if (($fn) && ($datatoken)) {
  247:             if ($env{'form.cancel'}) {
  248:                 my $source=$r->dir_config('lonDaemons').'/tmp/'.$datatoken.'.tmp';
  249:                 my $dirpath=$path.'/';
  250:                 $dirpath=~s/\/+/\//g;
  251:                 $output .= &mt('Upload cancelled.').'<br /><font size="+2"><a href="'.$dirpath.'">'.
  252:                           &mt('Back to Directory').'</a></font>';
  253: 	    } elsif ((-e $target) && (!$env{'form.override'})) {
  254: 		$output .= '<form action="'.$action.'" method="post">'.
  255: 			  &mt('File [_1] exists. Overwrite?','<span class="LC_filename">'.$fn.'</span>').
  256: 			  '<input type="hidden" name="phase" value="two" />'.
  257: 			  '<input type="hidden" name="filename" value="'.$url.'" />'.
  258: 			  '<input type="hidden" name="datatoken" value="'.$datatoken.'" />'.
  259: 			  '<input type="submit" name="override" value="'.&mt('Yes').'" />'.
  260:                           '<input type="submit" name="cancel" value="'.&mt('Cancel').'" />'.
  261:                           '</form>';
  262:             } else {
  263: 		my $source=$r->dir_config('lonDaemons').'/tmp/'.$datatoken.'.tmp';
  264: 		my $dirpath=$path.'/';
  265: 		$dirpath=~s/\/+/\//g;
  266: 		# Check for bad extension and disallow upload
  267:                 my $result;
  268:                 ($result,$returnflag) = &check_extension($fn,$mode,$source,$target,$action,$dirpath,$url);
  269:                 $output .= $result;
  270: 	    }
  271: 	} else {
  272: 	    $output .= '<span class="LC_error">'.
  273: 		      &mt('Please use browser "Back" button and pick a filename').
  274: 		      '</span><br />';
  275: 	}
  276:     } else {
  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 />';
  370:     }
  371:     return $result;
  372: }
  373: 
  374: # ---------------------------------------------------------------- Main Handler
  375: sub handler {
  376: 
  377:     my $r=shift;
  378: 
  379:     my $uname;
  380:     my $udom;
  381:     my $javascript = '';
  382: #
  383: # phase two: re-attach user
  384: #
  385:     if ($env{'form.uploaduname'}) {
  386: 	$env{'form.filename'}='/priv/'.$env{'form.uploaduname'}.'/'.
  387: 	    $env{'form.filename'};
  388:     }
  389: 
  390:     unless ($env{'form.phase'} eq 'two') {
  391:         $javascript = qq|
  392: function verifyForm() {
  393:     var mode = document.fileupload.filetype.options[document.fileupload.filetype.selectedIndex].value
  394:     if (mode == "testbank") {
  395:         document.fileupload.action = "/adm/testbank";
  396:     }
  397:     if (mode == "imsimport") {
  398:         document.fileupload.action = "/adm/imsimport";
  399:     }
  400:     if (mode == "standard") {
  401:         document.fileupload.action = "/adm/upload";
  402:     }
  403:     document.fileupload.submit();
  404: }
  405: 	|;
  406:     }
  407:     ($uname,$udom)=
  408: 	&Apache::loncacc::constructaccess($env{'form.filename'},
  409: 					  $r->dir_config('lonDefDomain'));
  410: 
  411:     unless (($uname) && ($udom)) {
  412: 	$r->log_reason($uname.' at '.$udom.
  413: 		       ' trying to publish file '.$env{'form.filename'}.
  414: 		       ' - not authorized', 
  415: 		       $r->filename); 
  416: 	return HTTP_NOT_ACCEPTABLE;
  417:     }
  418:     
  419:     my $fn;
  420:     if ($env{'form.filename'}) {
  421: 	$fn=$env{'form.filename'};
  422: 	$fn=~s/^http\:\/\/[^\/]+\///;
  423: 	$fn=~s/^\///;
  424: 	$fn=~s{(~|priv/)($LONCAPA::username_re)}{};
  425: 	$fn=~s/\/+/\//g;
  426:     } else {
  427: 	$r->log_reason($env{'user.name'}.' at '.$env{'user.domain'}.
  428: 		       ' unspecified filename for upload', $r->filename); 
  429: 	return HTTP_NOT_FOUND;
  430:     }
  431: 
  432: # ----------------------------------------------------------- Start page output
  433: 
  434: 
  435:     &Apache::loncommon::content_type($r,'text/html');
  436:     $r->send_http_header;
  437: 
  438:    $javascript = "<script type=\"text/javascript\">\n//<!--\n".
  439: 	$javascript."\n// --></script>\n";
  440: 
  441:     $r->print(&Apache::loncommon::start_page('Upload file to Construction Space',
  442: 					     $javascript));
  443:   
  444:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
  445: 	$r->print('<h3><span class="LC_error">'.&mt('Co-Author').': '.$uname.
  446: 		  &mt(' at ').$udom.'</span></h3>');
  447:     }
  448: 
  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);
  455:     } else {
  456: 	&phaseone($r,$fn,$uname,$udom);
  457:     }
  458: 
  459:     $r->print(&Apache::loncommon::end_page());
  460:     return OK;  
  461: }
  462: 
  463: 1;
  464: __END__
  465: 
  466: 

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