File:  [LON-CAPA] / loncom / publisher / lonupload.pm
Revision 1.62: download - view: text, annotated - select for diffs
Tue Jun 4 22:20:16 2013 UTC (11 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Replace term: "Construction Space" with "Authoring Space" for
  consistency with type of role used to access it, and action taken there.

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

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