File:  [LON-CAPA] / loncom / publisher / lonupload.pm
Revision 1.38.2.2: download - view: text, annotated - select for diffs
Wed Dec 17 19:18:47 2008 UTC (15 years, 5 months ago) by raeburn
Branches: version_2_8_X
Diff to branchpoint 1.38: preferred, unified
- Remove duplicate concatenation operator.

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

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