File:  [LON-CAPA] / loncom / publisher / lonupload.pm
Revision 1.56: download - view: text, annotated - select for diffs
Mon Oct 31 01:28:47 2011 UTC (12 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Use lonDocRoot perlvar in place of static string: '/home/httpd/html'.

    1: 
    2: # The LearningOnline Network with CAPA
    3: # Handler to upload files into construction space
    4: #
    5: # $Id: lonupload.pm,v 1.56 2011/10/31 01:28: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: =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, phasetwo, phasethree or phasefour)
   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 phasefour()
  103: 
  104: Interface for handling optional renaming of links to embedded
  105: objects. 
  106: 
  107: =item upfile_store()
  108: 
  109: Store contents of uploaded file into temporary space.  Invoked
  110: by phaseone subroutine.
  111: 
  112: =item check_extension()
  113: 
  114: Checks if filename extension is permitted and checks type
  115:  of file - if html file, calls parser to check for embedded objects.
  116:  Invoked by phasetwo subroutine.
  117: 
  118: =back
  119: 
  120: =cut
  121: 
  122: package Apache::lonupload;
  123: 
  124: use strict;
  125: use Apache::File;
  126: use File::Copy;
  127: use File::Basename;
  128: use Apache::Constants qw(:common :http :methods);
  129: use Apache::loncacc;
  130: use Apache::loncommon();
  131: use Apache::lonnet;
  132: use HTML::Entities();
  133: use Apache::lonlocal;
  134: use Apache::lonnet;
  135: use LONCAPA();
  136: 
  137: my $DEBUG=0;
  138: 
  139: sub Debug {
  140:     # Put out the indicated message but only if DEBUG is true.
  141:     if ($DEBUG) {
  142: 	my ($r,$message) = @_;
  143: 	$r->log_reason($message);
  144:     }
  145: }
  146: 
  147: sub upfile_store {
  148:     my $r=shift;
  149: 	
  150:     my $fname=$env{'form.upfile.filename'};
  151:     $fname=~s/\W//g;
  152:     
  153:     chomp($env{'form.upfile'});
  154:   
  155:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
  156: 		  '_upload_'.$fname.'_'.time.'_'.$$;
  157:     {
  158:        my $fh=Apache::File->new('>'.$r->dir_config('lonDaemons').
  159:                                    '/tmp/'.$datatoken.'.tmp');
  160:        print $fh $env{'form.upfile'};
  161:     }
  162:     return $datatoken;
  163: }
  164: 
  165: sub phaseone {
  166:     my ($r,$fn,$uname,$udom,$mode)=@_;
  167:     my $action = '/adm/upload';
  168:     if ($mode eq 'testbank') {
  169:         $action = '/adm/testbank';
  170:     } elsif ($mode eq 'imsimport') {
  171:         $action = '/adm/imsimport';
  172:     }
  173: 
  174:     # Check for file to be uploaded
  175:     $env{'form.upfile.filename'}=~s/\\/\//g;
  176:     $env{'form.upfile.filename'}=~s/^.*\/([^\/]+)$/$1/;
  177:     if (!$env{'form.upfile.filename'}) {
  178:         $r->print('<p class="LC_warning">'.&mt('No upload file specified.').'</p>');
  179:         return;
  180:     }
  181: 
  182:     # Append the name of the uploaded file
  183:     $fn.=$env{'form.upfile.filename'};
  184:     $fn=~s/(\/)+/\//g;
  185: 
  186:     # Check for illegal filename
  187:     &Debug($r, "Filename for upload: $fn");
  188:     if (!(($fn) && ($fn!~/\/$/))) {
  189:         $r->print('<p class="LC_warning">'.&mt('Illegal filename.').'</p>');
  190:         return;
  191:     }
  192: # Split part that I can change from the part that I cannot change
  193:     my ($fn1,$fn2)=($fn=~/^(\/priv\/[^\/]+\/[^\/]+\/)(.*)$/);
  194:     # Display additional options for upload
  195:     # and upload button
  196:     $r->print(
  197:         '<form action="'.$action.'" method="post" name="fileupload">'
  198:        .'<input type="hidden" name="phase" value="two" />'
  199:        .'<input type="hidden" name="datatoken" value="'.&upfile_store.'" />'
  200:     );
  201:     $r->print(
  202:         &Apache::lonhtmlcommon::start_pick_box()
  203:        .&Apache::lonhtmlcommon::row_title(&mt('Save uploaded file as'))
  204:        .'<span class="LC_filename">'.$fn1.'</span>'
  205:        .'<input type="hidden" name="filename1" value="'.$fn1.'" />'
  206:        .'<input type="text" size="50" name="filename2" value="'.$fn2.'" />'
  207:        .&Apache::lonhtmlcommon::row_closure()
  208:        .&Apache::lonhtmlcommon::row_title(&mt('File Type'))
  209:        .'<select name="filetype">'
  210:        .'<option value="standard" selected="selected">'.&mt('Regular file').'</option>'
  211:        .'<option value="testbank">'.&mt('Testbank file').'</option>'
  212:        .'<option value="imsimport">'.&mt('IMS package').'</option>'
  213:        .'</select>'.&Apache::loncommon::help_open_topic("Uploading_File_Options")
  214:        .&Apache::lonhtmlcommon::row_closure(1)
  215:        .&Apache::lonhtmlcommon::end_pick_box()
  216:     );
  217:     $r->print(
  218:         '<p>'
  219:        .'<input type="button" value="'.&mt('Upload').'" onclick="javascript:verifyForm()"/>'
  220:        .'</p>'
  221:        .'</form>'
  222:     );
  223: 
  224:    # Check for bad extension and warn user
  225:     if ($fn=~/\.(\w+)$/ && 
  226:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
  227:                 $r->print('<p class="LC_error">'
  228:                           .&mt('The extension on this file, [_1], is reserved internally by LON-CAPA.',
  229:                                '<span class="LC_filename">'.$1.'</span>')
  230:                           .' <br />'.&mt('Please change the extension.')
  231:                           .'</p>');
  232:     } elsif($fn=~/\.(\w+)$/ && 
  233:                     !defined(&Apache::loncommon::fileembstyle($1))) {
  234:                 $r->print('<p class="LC_error">'
  235:                          .&mt('The extension on this file, [_1], is not recognized by LON-CAPA.',
  236:                               '<span class="LC_filename">'.$1.'</span>')
  237:                          .' <br />'.&mt('Please change the extension.')
  238:                          .'</p>');
  239:     }
  240: }
  241: 
  242: sub phasetwo {
  243:     my ($r,$fn,$uname,$udom,$mode)=@_;
  244: 
  245:     my $output;
  246:     my $action = '/adm/upload';
  247:     my $returnflag = '';
  248:     if ($mode eq 'testbank') {
  249:         $action = '/adm/testbank';
  250:     } elsif ($mode eq 'imsimport') {
  251:         $action = '/adm/imsimport';
  252:     }
  253:     $fn=~s/\/+/\//g;
  254:     if ($fn) {
  255: 	my $target='/home/httpd/html/'.$fn;
  256: 	&Debug($r, "target -> ".$target);
  257: #     target is the full filesystem path of the destination file.
  258: 	my $base = &File::Basename::basename($fn);
  259: 	my $path = &File::Basename::dirname($fn);
  260: 	$base    = &HTML::Entities::encode($base,'<>&"');
  261: 	my $url  = $path."/".$base; 
  262: 	&Debug($r, "URL is now ".$url);
  263: 	my $datatoken=$env{'form.datatoken'};
  264: 	if (($fn) && ($datatoken)) {
  265:             if ($env{'form.cancel'}) {
  266:                 my $source=$r->dir_config('lonDaemons').'/tmp/'.$datatoken.'.tmp';
  267:                 my $dirpath=$path.'/';
  268:                 $dirpath=~s/\/+/\//g;
  269:                 $output .= '<p class="LC_warning">'.&mt('Upload cancelled.').'</p>'
  270:                           .'<p><a href="'.$dirpath.'">'.
  271:                           &mt('Back to Directory').'</a></p>';
  272:             } elsif ((-e $target) && (!$env{'form.override'})) {
  273:                 $output .= '<form action="'.$action.'" method="post">'
  274:                           .'<p class="LC_warning">'
  275:                           .&mt('File [_1] already exists.',
  276:                                '<span class="LC_filename">'.$fn.'</span>')
  277:                          .'<input type="hidden" name="phase" value="two" />'
  278:                          .'<input type="hidden" name="filename" value="'.$url.'" />'
  279:                          .'<input type="hidden" name="datatoken" value="'.$datatoken.'" />'
  280:                          .'<p>'
  281:                          .'<input type="submit" name="cancel" value="'.&mt('Cancel').'" />'
  282:                          .' <input type="submit" name="override" value="'.&mt('Overwrite').'" />'
  283:                          .'</p>'
  284:                          .'</form>';
  285:             } else {
  286: 		my $source=$r->dir_config('lonDaemons').'/tmp/'.$datatoken.'.tmp';
  287: 		my $dirpath=$path.'/';
  288: 		$dirpath=~s/\/+/\//g;
  289: 		# Check for bad extension and disallow upload
  290:                 my $result;
  291:                 ($result,$returnflag) = &check_extension($fn,$mode,$source,$target,$action,$dirpath,$url);
  292:                 $output .= $result;
  293: 	    }
  294: 	} else {
  295: 	    $output .= '<span class="LC_error">'.
  296: 		      &mt('Please use browser "Back" button and pick a filename').
  297: 		      '</span><br />';
  298: 	}
  299:     } else {
  300: 	$output .= '<span class="LC_error">'.
  301: 		   &mt('Please use browser "Back" button and pick a filename').
  302: 		   '</span><br />';
  303:     }
  304:     return ($output,$returnflag);
  305: }
  306: 
  307: sub check_extension {
  308:     my ($fn,$mode,$source,$target,$action,$dirpath,$url) = @_;
  309:     my ($result,$returnflag);
  310:     # Check for bad extension and disallow upload
  311:     if ($fn=~/\.(\w+)$/ &&
  312:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
  313:         $result .= '<p class="LC_warning">'.
  314:                    &mt('File [_1] could not be copied.',
  315:                        '<span class="LC_filename">'.$fn.'</span> ').
  316:                    '<br />'.
  317:                    &mt('The extension on this file is reserved internally by LON-CAPA.').
  318:                    '</p>';
  319:     } elsif ($fn=~/\.(\w+)$/ &&
  320:              !defined(&Apache::loncommon::fileembstyle($1))) {
  321:         $result .= '<p class="LC_warning">'.
  322:                    &mt('File [_1] could not be copied.',
  323:                        '<span class="LC_filename">'.$fn.'</span> ').
  324:                    '<br />'.
  325:                    &mt('The extension on this file is not recognized by LON-CAPA.').
  326:                    '</p>';
  327:     } elsif (-d $target) {
  328:         $result .= '<p class="LC_warning">'.
  329:                    &mt('File [_1] could not be copied.',
  330:                        '<span class="LC_filename">'.$fn.'</span>').
  331:                    '<br />'.
  332:                    &mt('The target is an existing directory.').
  333:                    '</p>';
  334:     } elsif (copy($source,$target)) {
  335:         chmod(0660, $target); # Set permissions to rw-rw---.
  336:         if ($mode eq 'testbank' || $mode eq 'imsimport') {
  337:             $returnflag = 'ok';
  338:             $result .= '<p class="LC_success">'
  339:                       .&mt('Your file - [_1] - was uploaded successfully.',
  340:                            '<span class="LC_filename">'.$fn.'<span>')
  341:                       .'</p>';
  342:         } else {
  343:             $result .= '<p class="LC_success">'
  344:                       .&mt('File copied.')  
  345:                       .'</p>';
  346:         }
  347:         # Check for embedded objects.
  348:         my (%allfiles,%codebase);
  349:         my ($text,$header,$css,$js);
  350:         if (($mode ne 'imsimport') && ($target =~ /\.(htm|html|shtml)$/i)) {
  351:             my (%allfiles,%codebase);
  352:             &Apache::lonnet::extract_embedded_items($target,\%allfiles,\%codebase);
  353:             if (keys(%allfiles) > 0) {
  354:                 my ($currentpath) = ($url =~ m{^(.+)/[^/]+$});
  355:                 my $state = &embedded_form_elems('upload_embedded',$url,$mode);
  356:                 my ($embedded,$num,$pathchg) = 
  357:                     &Apache::loncommon::ask_for_embedded_content($action,$state,\%allfiles,
  358:                                                                  \%codebase,
  359:                                                                  {'error_on_invalid_names'   => 1,
  360:                                                                   'ignore_remote_references' => 1,
  361:                                                                   'current_path'             => $currentpath});
  362:                 if ($embedded) {
  363:                     $result .= '<h3>'.&mt('Reference Warning').'</h3>';
  364:                     if ($num) {
  365:                         $result .= '<p>'.&mt('Completed upload of the file.').' '.&mt('This file contained references to other files.').'</p>'.
  366:                                    '<p>'.&mt('Please select the locations from which the referenced files are to be uploaded.').'</p>'.
  367:                                    $embedded;
  368:                         if ($mode eq 'testbank') {
  369:                             $returnflag = 'embedded';
  370:                             $result .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without these files.','<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
  371:                         }
  372:                     } else {
  373:                         $result .= '<p>'.&mt('Completed upload of the file.').'</p>'.$embedded;
  374:                         if ($pathchg) {
  375:                             if ($mode eq 'testbank') {
  376:                                 $returnflag = 'embedded';
  377:                                 $result .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the references(s).','<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
  378:                             }
  379:                         }
  380:                     }
  381:                 }
  382:             }
  383:         }
  384:         if (($mode ne 'imsimport') && ($mode ne 'testbank')) {
  385:             $result .= '<br /><a href="'.$url.'">'.
  386:                         &mt('View file').'</a>';
  387:         }
  388:     } else {
  389:         $result .= &mt('Failed to copy: [_1].',$!);
  390:     }
  391:     if ($mode ne 'imsimport' && $mode ne 'testbank') {
  392:         $result .= '<br /><a href="'.$dirpath.'">'.
  393:                    &mt('Back to Directory').'</a><br />';
  394:     }
  395:     return ($result,$returnflag);
  396: }
  397: 
  398: sub phasethree {
  399:     my ($r,$fn,$uname,$udom,$mode) = @_;
  400: 
  401:     my $action = '/adm/upload'; 
  402:     if ($mode eq 'testbank') {
  403:         $action = '/adm/testbank';
  404:     } elsif ($mode eq 'imsimport') {
  405:         $action = '/adm/imsimport';
  406:     }
  407:     my $url_root = "/priv/$udom/$uname";
  408:     my $dir_root = $r->dir_config('lonDocRoot').$url_root;
  409:     my $url_root = '/priv/'.$udom.'/'.$uname;
  410:     my $path = &File::Basename::dirname($fn);
  411:     my $filename = &HTML::Entities::encode($env{'form.filename'},'<>&"');
  412:     my $state = &embedded_form_elems('modify_orightml',$filename,$mode).
  413:                 '<input type="hidden" name="phase" value="four" />';
  414:     my ($result,$returnflag) = 
  415:         &Apache::loncommon::upload_embedded($mode,$path,$uname,$udom,
  416:                                             $dir_root,$url_root,undef,
  417:                                             undef,undef,$state,$action);
  418:     if ($mode ne 'imsimport' && $mode ne 'testbank') {
  419:         $result .= '<br /><h3><a href="'.$url_root.$fn.'">'.
  420:                   &mt('View main file').'</a></h3>'.
  421:                   '<h3><a href="'.$url_root.$path.'">'.
  422:                   &mt('Back to Directory').'</a></h3><br />';
  423:     }
  424:     return ($result,$returnflag);
  425: }
  426: 
  427: sub embedded_form_elems {
  428:     my ($action,$filename,$mode) = @_;
  429:     return <<STATE;
  430:     <input type="hidden" name="action" value="$action" />
  431:     <input type="hidden" name="mode" value="$mode" />
  432:     <input type="hidden" name="filename" value="$filename" />
  433: STATE
  434: }
  435: 
  436: sub phasefour {
  437:     my ($r,$fn,$uname,$udom,$mode) = @_;
  438: 
  439:     my $action = '/adm/upload';
  440:     if ($mode eq 'testbank') {
  441:         $action = '/adm/testbank';
  442:     } elsif ($mode eq 'imsimport') {
  443:         $action = '/adm/imsimport';
  444:     }
  445:     my $result;
  446:     my $url_root = "/priv/$udom/$uname";
  447:     my $dir_root = $r->dir_config('lonDocRoot').$url_root;
  448:     my $path = &File::Basename::dirname($fn);
  449:     $result .= &Apache::loncommon::modify_html_refs($mode,$path,
  450:                               $uname,$udom,$dir_root);
  451:     if ($mode ne 'imsimport' && $mode ne 'testbank') {
  452:         $result .= '<br /><h3><a href="'.$url_root.$fn.'">'.
  453:                   &mt('View main file').'</a></h3>'.
  454:                   '<h3><a href="'.$url_root.$path.'">'.
  455:                   &mt('Back to Directory').'</a></h3><br />';
  456:     }
  457:     return $result;
  458: }
  459: 
  460: # ---------------------------------------------------------------- Main Handler
  461: sub handler {
  462: 
  463:     my $r=shift;
  464: 
  465:     my $uname;
  466:     my $udom;
  467:     my $javascript = '';
  468: 
  469:     my $fn=$env{'form.filename'};
  470: 
  471:     if ($env{'form.filename1'}) {
  472:        $fn=$env{'form.filename1'}.$env{'form.filename2'};
  473:     }
  474:     $fn=~s/\/+/\//g;
  475: 
  476:     unless ($fn) {
  477:         $r->log_reason($env{'user.name'}.' at '.$env{'user.domain'}.
  478:                        ' unspecified filename for upload', $r->filename);
  479:         return HTTP_NOT_FOUND;
  480:     }
  481: 
  482:     unless ($env{'form.phase'} eq 'two') {
  483:         $javascript = qq|
  484: function verifyForm() {
  485:     var mode = document.fileupload.filetype.options[document.fileupload.filetype.selectedIndex].value
  486:     if (mode == "testbank") {
  487:         document.fileupload.action = "/adm/testbank";
  488:     }
  489:     if (mode == "imsimport") {
  490:         document.fileupload.action = "/adm/imsimport";
  491:     }
  492:     if (mode == "standard") {
  493:         document.fileupload.action = "/adm/upload";
  494:     }
  495:     document.fileupload.submit();
  496: }
  497: 	|;
  498:     }
  499:     ($uname,$udom)=&Apache::loncacc::constructaccess($fn);
  500: 
  501:     unless (($uname) && ($udom)) {
  502: 	$r->log_reason($uname.' at '.$udom.
  503: 		       ' trying to publish file '.$env{'form.filename'}.
  504: 		       ' - not authorized', 
  505: 		       $r->filename); 
  506: 	return HTTP_NOT_ACCEPTABLE;
  507:     }
  508:     
  509: # ----------------------------------------------------------- Start page output
  510: 
  511: 
  512:     &Apache::loncommon::content_type($r,'text/html');
  513:     $r->send_http_header;
  514: 
  515:    $javascript = "<script type=\"text/javascript\">\n//<!--\n".
  516: 	$javascript."\n// --></script>\n";
  517: 
  518:     # Breadcrumbs
  519:     my $brcrum = [{'href' => &Apache::loncommon::authorspace(),
  520:                    'text' => 'Construction Space'},
  521:                   {'href' => '/adm/upload',
  522:                    'text' => 'Upload file to Construction Space'}];
  523:     $r->print(&Apache::loncommon::start_page('Upload file to Construction Space',
  524:                                              $javascript,
  525:                                              {'bread_crumbs' => $brcrum,})
  526:              .&Apache::loncommon::head_subbox(
  527:                 &Apache::loncommon::CSTR_pageheader())
  528:     );
  529:   
  530:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
  531:         $r->print('<p class="LC_info">'
  532:                  .&mt('Co-Author [_1]',$uname.':'.$udom)
  533:                  .'</p>'
  534:         );
  535:     }
  536:     if ($env{'form.phase'} eq 'four') {
  537:         my $output = &phasefour($r,$fn,$uname,$udom,'author');
  538:         $r->print($output);
  539:     } elsif ($env{'form.phase'} eq 'three') {
  540:         my ($output,$rtnflag) = &phasethree($r,$fn,$uname,$udom,'author');
  541:         $r->print($output);
  542:     } elsif ($env{'form.phase'} eq 'two') {
  543: 	my ($output,$returnflag) = &phasetwo($r,$fn,$uname,$udom);
  544:         $r->print($output);
  545:     } else {
  546: 	&phaseone($r,$fn,$uname,$udom);
  547:     }
  548: 
  549:     $r->print(&Apache::loncommon::end_page());
  550:     return OK;  
  551: }
  552: 
  553: 1;
  554: __END__
  555: 
  556: 

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