File:  [LON-CAPA] / loncom / publisher / lonupload.pm
Revision 1.43: download - view: text, annotated - select for diffs
Fri Dec 19 03:57:24 2008 UTC (15 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Regular Expression for both http and https.

    1: 
    2: # The LearningOnline Network with CAPA
    3: # Handler to upload files into construction space
    4: #
    5: # $Id: lonupload.pm,v 1.43 2008/12/19 03:57:24 raeburn 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
   87: 
   88: =item phaseone()
   89: 
   90: Interface for specifying file to upload.
   91: 
   92: =item phasetwo()
   93: 
   94: Interface for handling post-conditions about uploading (such
   95: as overwriting an existing file).
   96: 
   97: =item phasethree()
   98: 
   99: Interface for handling secondary uploads of embedded objects
  100: in an html file.
  101: 
  102: =item upfile_store()
  103: 
  104: Store contents of uploaded file into temporary space.  Invoked
  105: by phaseone subroutine.
  106: 
  107: =item check_extension()
  108: 
  109: 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 [_1]',
  188:                       "<span class='LC_filename'>/priv/$uname/</span>".
  189:                       '<input type="text" size="50" name="filename" value="'.$fn.
  190:                       '" />').
  191:                       '<br />'.
  192: 		      '<br />'.&mt('Choose file type:').'
  193: <select name="filetype">
  194:  <option value="standard" selected>'.&mt('Regular file').'
  195:  <option value="testbank">'.&mt('Testbank file').'
  196:  <option value="imsimport">'.&mt('IMS package').'
  197: </select>'.&Apache::loncommon::help_open_topic("Uploading_File_Options").'
  198: <br />
  199: <br />
  200: ');
  201:             $r->print('<input type="button" value="'.&mt('Save').'" onClick="javascript:verifyForm()"/></form>');
  202: 	    # Check for bad extension and warn user
  203: 	    if ($fn=~/\.(\w+)$/ && 
  204: 		(&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
  205:                 $r->print('<p class="LC_error">'
  206:                           .&mt('The extension on this file, [_1], is reserved internally by LON-CAPA.','"'.$1.'"')
  207:                           .' <br />'.&mt('Please change the extension.')
  208:                           .'</p>');
  209: 	    } elsif($fn=~/\.(\w+)$/ && 
  210: 		    !defined(&Apache::loncommon::fileembstyle($1))) {
  211:                 $r->print('<p class="LC_error">'
  212:                          .&mt('The extension on this file, [_1], is not recognized by LON-CAPA.','"'.$1.'"')
  213:                          .' <br />'.&mt('Please change the extension.')
  214:                          .'</p>');
  215: 	    }
  216: 	} else {
  217: 	    $r->print('<span class="LC_error">'.&mt('Illegal filename.').'</span>');
  218: 	}
  219:     } else {
  220: 	$r->print('<span class="LC_error">'.&mt('No upload file specified.').'</span>');
  221:     }
  222: }
  223: 
  224: sub phasetwo {
  225:     my ($r,$tfn,$uname,$udom,$mode)=@_;
  226:     my $output;
  227:     my $action = '/adm/upload';
  228:     my $returnflag = '';
  229:     if ($mode eq 'testbank') {
  230:         $action = '/adm/testbank';
  231:     } elsif ($mode eq 'imsimport') {
  232:         $action = '/adm/imsimport';
  233:     }
  234:     my $fn='/priv/'.$uname.'/'.$tfn;
  235:     $fn=~s/\/+/\//g;
  236:     &Debug($r, "Filename is ".$tfn);
  237:     if ($tfn) {
  238: 	&Debug($r, "Filename for tfn = ".$tfn);
  239: 	my $target='/home/'.$uname.'/public_html'.$tfn;
  240: 	&Debug($r, "target -> ".$target);
  241: #     target is the full filesystem path of the destination file.
  242: 	my $base = &File::Basename::basename($fn);
  243: 	my $path = &File::Basename::dirname($fn);
  244: 	$base    = &HTML::Entities::encode($base,'<>&"');
  245: 	my $url  = $path."/".$base; 
  246: 	&Debug($r, "URL is now ".$url);
  247: 	my $datatoken=$env{'form.datatoken'};
  248: 	if (($fn) && ($datatoken)) {
  249:             if ($env{'form.cancel'}) {
  250:                 my $source=$r->dir_config('lonDaemons').'/tmp/'.$datatoken.'.tmp';
  251:                 my $dirpath=$path.'/';
  252:                 $dirpath=~s/\/+/\//g;
  253:                 $output .= &mt('Upload cancelled.').'<br /><font size="+2"><a href="'.$dirpath.'">'.
  254:                           &mt('Back to Directory').'</a></font>';
  255: 	    } elsif ((-e $target) && (!$env{'form.override'})) {
  256: 		$output .= '<form action="'.$action.'" method="post">'.
  257: 			  &mt('File [_1] exists. Overwrite?','<span class="LC_filename">'.$fn.'</span>').
  258: 			  '<input type="hidden" name="phase" value="two" />'.
  259: 			  '<input type="hidden" name="filename" value="'.$url.'" />'.
  260: 			  '<input type="hidden" name="datatoken" value="'.$datatoken.'" />'.
  261: 			  '<input type="submit" name="override" value="'.&mt('Yes').'" />'.
  262:                           '<input type="submit" name="cancel" value="'.&mt('Cancel').'" />'.
  263:                           '</form>';
  264:             } else {
  265: 		my $source=$r->dir_config('lonDaemons').'/tmp/'.$datatoken.'.tmp';
  266: 		my $dirpath=$path.'/';
  267: 		$dirpath=~s/\/+/\//g;
  268: 		# Check for bad extension and disallow upload
  269:                 my $result;
  270:                 ($result,$returnflag) = &check_extension($fn,$mode,$source,$target,$action,$dirpath,$url);
  271:                 $output .= $result;
  272: 	    }
  273: 	} else {
  274: 	    $output .= '<span class="LC_error">'.
  275: 		      &mt('Please use browser "Back" button and pick a filename').
  276: 		      '</span><br />';
  277: 	}
  278:     } else {
  279: 	$output .= '<span class="LC_error">'.
  280: 		   &mt('Please use browser "Back" button and pick a filename').
  281: 		   '</span><br />';
  282:     }
  283:     return ($output,$returnflag);
  284: }
  285: 
  286: sub check_extension {
  287:     my ($fn,$mode,$source,$target,$action,$dirpath,$url) = @_;
  288:     my ($result,$returnflag);
  289:     # Check for bad extension and disallow upload
  290:     if ($fn=~/\.(\w+)$/ &&
  291:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
  292:         $result .= &mt('File [_1] could not be copied.',
  293:                       '<span class="LC_filename">'.$fn.'</span> ').
  294:                   '<p class="LC_error">'.
  295:                   &mt('The extension on this file is reserved internally by LON-CAPA.').
  296:                   '</p>';
  297:     } elsif ($fn=~/\.(\w+)$/ &&
  298:              !defined(&Apache::loncommon::fileembstyle($1))) {
  299:         $result .= &mt('File [_1] could not be copied.',
  300:                       '<span class="LC_filename">'.$fn.'</span> ').
  301:                   '<p class="LC_error">'.
  302:                   &mt('The extension on this file is not recognized by LON-CAPA.').
  303:                   '</p>';
  304:     } elsif (-d $target) {
  305:         $result .= &mt('File [_1] could not be copied.',
  306:                       '<span class="LC_filename">'.$fn.'</span>').
  307:                   '<p class="LC_error">'.
  308:                   &mt('The target is an existing directory.').
  309:                   '</p>';
  310:     } elsif (copy($source,$target)) {
  311:         chmod(0660, $target); # Set permissions to rw-rw---.
  312:         if ($mode eq 'testbank' || $mode eq 'imsimport') {
  313:             $returnflag = 'ok';
  314:             $result .= &mt('Your file - [_1] - was uploaded successfully',$fn).'<br /><br />';
  315:         } else {
  316:             $result .= &mt('File copied.').'<br />';
  317:         }
  318:         # Check for embedded objects.
  319:         my (%allfiles,%codebase);
  320:         my ($text,$header,$css,$js);
  321:         if (($mode ne 'imsimport') && ($target =~ /\.(htm|html|shtml)$/i)) {
  322:             my (%allfiles,%codebase);
  323:             &Apache::lonnet::extract_embedded_items($target,\%allfiles,\%codebase);
  324:             if (keys(%allfiles) > 0) {
  325:                 my $state = <<STATE;
  326:     <input type="hidden" name="action"      value="upload_embedded" />
  327:     <input type="hidden" name="currentpath" value="$env{'form.currentpath'}" />
  328:     <input type="hidden" name="mode"        value="$mode" />
  329:     <input type="hidden" name="phase"       value="three" />
  330:     <input type="hidden" name="filename" value="$url" />
  331: STATE
  332:                 $result .= "<h3>".&mt("Reference Warning")."</h3>".
  333:                            "<p>".&mt("Completed upload of the file. This file contained references to other files.")."</p>".
  334:                           "<p>".&mt("Please select the locations from which the referenced files are to be uploaded.")."</p>".
  335:                           &Apache::loncommon::ask_for_embedded_content($action,$state,\%allfiles,\%codebase,
  336:                                       {'error_on_invalid_names'   => 1,
  337:                                        'ignore_remote_references' => 1,});
  338:                 if ($mode eq 'testbank') {
  339:                     $returnflag = 'embedded';
  340:                     $result .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without these files','<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
  341:                 }
  342:             }
  343:         }
  344:         if (($mode ne 'imsimport') && ($mode ne 'testbank')) {
  345:             $result .= '<br /><font size="+2"><a href="'.$url.'">'.
  346:                         &mt('View file').'</a></font>';
  347:         }
  348:     } else {
  349:         $result .= &mt('Failed to copy: [_1].',$!);
  350:     }
  351:     if ($mode ne 'imsimport' && $mode ne 'testbank') {
  352:         $result .= '<br /><font size="+2"><a href="'.$dirpath.'">'.
  353:                    &mt('Back to Directory').'</a></font><br />';
  354:     }
  355:     return ($result,$returnflag);
  356: }
  357: 
  358: sub phasethree {
  359:     my ($r,$fn,$uname,$udom,$mode) = @_;
  360:     my $result;
  361:     my $dir_root = '/home/'.$uname.'/public_html';
  362:     my $url_root = '/priv/'.$uname;
  363:     my $base = &File::Basename::basename($fn);
  364:     my $path = &File::Basename::dirname($fn);
  365:     $result = &Apache::loncommon::upload_embedded($mode,$path,$uname,$udom,
  366:                                                   $dir_root,$url_root);
  367:     if ($mode ne 'imsimport' && $mode ne 'testbank') {
  368:         $result = '<br /><font size="+2"><a href="'.$url_root.$fn.'">'.
  369:                   &mt('View main file').'</a></font>'.
  370:                   '<br /><font size="+2"><a href="'.$url_root.$path.'">'.
  371:                   &mt('Back to Directory').'</a></font><br />';
  372:     }
  373:     return $result;
  374: }
  375: 
  376: # ---------------------------------------------------------------- Main Handler
  377: sub handler {
  378: 
  379:     my $r=shift;
  380: 
  381:     my $uname;
  382:     my $udom;
  383:     my $javascript = '';
  384: #
  385: # phase two: re-attach user
  386: #
  387:     if ($env{'form.uploaduname'}) {
  388: 	$env{'form.filename'}='/priv/'.$env{'form.uploaduname'}.'/'.
  389: 	    $env{'form.filename'};
  390:     }
  391: 
  392:     unless ($env{'form.phase'} eq 'two') {
  393:         $javascript = qq|
  394: function verifyForm() {
  395:     var mode = document.fileupload.filetype.options[document.fileupload.filetype.selectedIndex].value
  396:     if (mode == "testbank") {
  397:         document.fileupload.action = "/adm/testbank";
  398:     }
  399:     if (mode == "imsimport") {
  400:         document.fileupload.action = "/adm/imsimport";
  401:     }
  402:     if (mode == "standard") {
  403:         document.fileupload.action = "/adm/upload";
  404:     }
  405:     document.fileupload.submit();
  406: }
  407: 	|;
  408:     }
  409:     ($uname,$udom)=
  410: 	&Apache::loncacc::constructaccess($env{'form.filename'},
  411: 					  $r->dir_config('lonDefDomain'));
  412: 
  413:     unless (($uname) && ($udom)) {
  414: 	$r->log_reason($uname.' at '.$udom.
  415: 		       ' trying to publish file '.$env{'form.filename'}.
  416: 		       ' - not authorized', 
  417: 		       $r->filename); 
  418: 	return HTTP_NOT_ACCEPTABLE;
  419:     }
  420:     
  421:     my $fn;
  422:     if ($env{'form.filename'}) {
  423: 	$fn=$env{'form.filename'};
  424: 	$fn=~s/^https?\:\/\/[^\/]+\///;
  425: 	$fn=~s/^\///;
  426: 	$fn=~s{(~|priv/)($LONCAPA::username_re)}{};
  427: 	$fn=~s/\/+/\//g;
  428:     } else {
  429: 	$r->log_reason($env{'user.name'}.' at '.$env{'user.domain'}.
  430: 		       ' unspecified filename for upload', $r->filename); 
  431: 	return HTTP_NOT_FOUND;
  432:     }
  433: 
  434: # ----------------------------------------------------------- Start page output
  435: 
  436: 
  437:     &Apache::loncommon::content_type($r,'text/html');
  438:     $r->send_http_header;
  439: 
  440:    $javascript = "<script type=\"text/javascript\">\n//<!--\n".
  441: 	$javascript."\n// --></script>\n";
  442: 
  443:     $r->print(&Apache::loncommon::start_page('Upload file to Construction Space',
  444: 					     $javascript));
  445:   
  446:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
  447: 	$r->print('<h3><span class="LC_error">'.&mt('Co-Author').': '.$uname.
  448: 		  &mt(' at ').$udom.'</span></h3>');
  449:     }
  450: 
  451:     if ($env{'form.phase'} eq 'three') {
  452:         my $output = &phasethree($r,$fn,$uname,$udom,'author');
  453:         $r->print($output);
  454:     } elsif ($env{'form.phase'} eq 'two') {
  455: 	my ($output,$returnflag) = &phasetwo($r,$fn,$uname,$udom);
  456:         $r->print($output);
  457:     } else {
  458: 	&phaseone($r,$fn,$uname,$udom);
  459:     }
  460: 
  461:     $r->print(&Apache::loncommon::end_page());
  462:     return OK;  
  463: }
  464: 
  465: 1;
  466: __END__
  467: 
  468: 

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