1: # The LearningOnline Network with CAPA
2: # Handler to upload files into construction space
3: #
4: # $Id: lonupload.pm,v 1.68 2017/11/12 23:01:00 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 qw(:DEFAULT :match);
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;
154: if (($env{'user.name'} =~ /^$match_username$/) && ($env{'user.domain'} =~ /^$match_domain$/)) {
155: $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
156: '_upload_'.$fname.'_'.time.'_'.$$;
157: }
158: return if ($datatoken eq '');
159: {
160: my $fh=Apache::File->new('>'.$r->dir_config('lonDaemons').
161: '/tmp/'.$datatoken.'.tmp');
162: print $fh $env{'form.upfile'};
163: }
164: return $datatoken;
165: }
166:
167: sub phaseone {
168: my ($r,$fn,$mode,$uname,$udom)=@_;
169: my $action = '/adm/upload';
170: if ($mode eq 'testbank') {
171: $action = '/adm/testbank';
172: } elsif ($mode eq 'imsimport') {
173: $action = '/adm/imsimport';
174: }
175:
176: # Check for file to be uploaded
177: $env{'form.upfile.filename'}=~s/\\/\//g;
178: $env{'form.upfile.filename'}=~s/^.*\/([^\/]+)$/$1/;
179: if (!$env{'form.upfile.filename'}) {
180: $r->print('<p class="LC_warning">'.&mt('No upload file specified.').'</p>'.
181: &earlyout($fn,$uname,$udom));
182: return;
183: }
184:
185: # Append the name of the uploaded file
186: $fn.=$env{'form.upfile.filename'};
187: $fn=~s/(\/)+/\//g;
188:
189: # Check for illegal filename
190: &Debug($r, "Filename for upload: $fn");
191: if (!(($fn) && ($fn!~/\/$/))) {
192: $r->print('<p class="LC_warning">'.&mt('Illegal filename.').'</p>');
193: return;
194: }
195: # Check if quota exceeded
196: my $filesize = length($env{'form.upfile'});
197: if (!$filesize) {
198: $r->print('<p class="LC_warning">'.
199: &mt('Unable to upload [_1]. (size = [_2] bytes)',
200: '<span class="LC_filename">'.$env{'form.upfile.filename'}.'</span>',
201: $filesize).'<br />'.
202: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
203: '</p>'.
204: &earlyout($fn,$uname,$udom));
205: return;
206: }
207: $filesize = int($filesize/1000); #expressed in kb
208: my $output = &Apache::loncommon::excess_filesize_warning($uname,$udom,'author',
209: $env{'form.upfile.filename'},$filesize,'upload');
210: if ($output) {
211: $r->print($output.&earlyout($fn,$uname,$udom));
212: return;
213: }
214:
215: # Split part that I can change from the part that I cannot change
216: my ($fn1,$fn2)=($fn=~/^(\/priv\/[^\/]+\/[^\/]+\/)(.*)$/);
217: # Display additional options for upload
218: # and upload button
219: $r->print(
220: '<form action="'.$action.'" method="post" name="fileupload">'
221: .'<input type="hidden" name="phase" value="two" />'
222: .'<input type="hidden" name="datatoken" value="'.&upfile_store.'" />'
223: );
224: $r->print(
225: &Apache::lonhtmlcommon::start_pick_box()
226: .&Apache::lonhtmlcommon::row_title(&mt('Save uploaded file as'))
227: .'<span class="LC_filename">'.$fn1.'</span>'
228: .'<input type="hidden" name="filename1" value="'.$fn1.'" />'
229: .'<input type="text" size="50" name="filename2" value="'.$fn2.'" />'
230: .&Apache::lonhtmlcommon::row_closure()
231: .&Apache::lonhtmlcommon::row_title(&mt('File Type'))
232: .'<select name="filetype">'
233: .'<option value="standard" selected="selected">'.&mt('Regular file').'</option>'
234: .'<option value="testbank">'.&mt('Testbank file').'</option>'
235: .'<option value="imsimport">'.&mt('IMS package').'</option>'
236: .'</select>'.&Apache::loncommon::help_open_topic("Uploading_File_Options")
237: .&Apache::lonhtmlcommon::row_closure(1)
238: .&Apache::lonhtmlcommon::end_pick_box()
239: );
240: $r->print(
241: '<p>'
242: .'<input type="button" value="'.&mt('Upload').'" onclick="javascript:verifyForm()"/>'
243: .'</p>'
244: .'</form>'
245: );
246:
247: # Check for bad extension and warn user
248: if ($fn=~/\.(\w+)$/ &&
249: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
250: $r->print('<p class="LC_error">'
251: .&mt('The extension on this file, [_1], is reserved internally by LON-CAPA.',
252: '<span class="LC_filename">'.$1.'</span>')
253: .' <br />'.&mt('Please change the extension.')
254: .'</p>');
255: } elsif($fn=~/\.(\w+)$/ &&
256: !defined(&Apache::loncommon::fileembstyle($1))) {
257: $r->print('<p class="LC_error">'
258: .&mt('The extension on this file, [_1], is not recognized by LON-CAPA.',
259: '<span class="LC_filename">'.$1.'</span>')
260: .' <br />'.&mt('Please change the extension.')
261: .'</p>');
262: }
263: }
264:
265: sub phasetwo {
266: my ($r,$fn,$mode)=@_;
267:
268: my $output;
269: my $action = '/adm/upload';
270: my $returnflag = '';
271: if ($mode eq 'testbank') {
272: $action = '/adm/testbank';
273: } elsif ($mode eq 'imsimport') {
274: $action = '/adm/imsimport';
275: }
276: $fn=~s/\/+/\//g;
277: if ($fn) {
278: my $target= $r->dir_config('lonDocRoot').'/'.$fn;
279: &Debug($r, "target -> ".$target);
280: # target is the full filesystem path of the destination file.
281: my $base = &File::Basename::basename($fn);
282: my $path = &File::Basename::dirname($fn);
283: $base = &HTML::Entities::encode($base,'<>&"');
284: my $url = $path."/".$base;
285: &Debug($r, "URL is now ".$url);
286: my $datatoken;
287: if ($env{'form.datatoken'} =~ /^$match_username\_$match_domain\_upload_\w*_\d+_\d+$/) {
288: $datatoken = $env{'form.datatoken'};
289: }
290: if (($fn) && ($datatoken)) {
291: if ($env{'form.cancel'}) {
292: my $source=$r->dir_config('lonDaemons').'/tmp/'.$datatoken.'.tmp';
293: my $dirpath=$path.'/';
294: $dirpath=~s/\/+/\//g;
295: $output .= '<p class="LC_warning">'.&mt('Upload cancelled.').'</p>'
296: .'<p><a href="'.$dirpath.'">'.
297: &mt('Back to Directory').'</a></p>';
298: } elsif ((-e $target) && (!$env{'form.override'})) {
299: $output .= '<form action="'.$action.'" method="post">'
300: .'<p class="LC_warning">'
301: .&mt('File [_1] already exists.',
302: '<span class="LC_filename">'.$fn.'</span>')
303: .'<input type="hidden" name="phase" value="two" />'
304: .'<input type="hidden" name="filename" value="'.$url.'" />'
305: .'<input type="hidden" name="datatoken" value="'.$datatoken.'" />'
306: .'<p>'
307: .'<input type="submit" name="cancel" value="'.&mt('Cancel').'" />'
308: .' <input type="submit" name="override" value="'.&mt('Overwrite').'" />'
309: .'</p>'
310: .'</form>';
311: } else {
312: my $source=$r->dir_config('lonDaemons').'/tmp/'.$datatoken.'.tmp';
313: my $dirpath=$path.'/';
314: $dirpath=~s/\/+/\//g;
315: # Check for bad extension and disallow upload
316: my $result;
317: ($result,$returnflag) = &check_extension($fn,$mode,$source,$target,$action,$dirpath,$url);
318: $output .= $result;
319: }
320: } else {
321: $output .= '<span class="LC_error">'.
322: &mt('Please use browser "Back" button and pick a filename').
323: '</span><br />';
324: }
325: } else {
326: $output .= '<span class="LC_error">'.
327: &mt('Please use browser "Back" button and pick a filename').
328: '</span><br />';
329: }
330: return ($output,$returnflag);
331: }
332:
333: sub check_extension {
334: my ($fn,$mode,$source,$target,$action,$dirpath,$url) = @_;
335: my ($result,$returnflag);
336: # Check for bad extension and disallow upload
337: if ($fn=~/\.(\w+)$/ &&
338: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
339: $result .= '<p class="LC_warning">'.
340: &mt('File [_1] could not be copied.',
341: '<span class="LC_filename">'.$fn.'</span> ').
342: '<br />'.
343: &mt('The extension on this file is reserved internally by LON-CAPA.').
344: '</p>';
345: } elsif ($fn=~/\.(\w+)$/ &&
346: !defined(&Apache::loncommon::fileembstyle($1))) {
347: $result .= '<p class="LC_warning">'.
348: &mt('File [_1] could not be copied.',
349: '<span class="LC_filename">'.$fn.'</span> ').
350: '<br />'.
351: &mt('The extension on this file is not recognized by LON-CAPA.').
352: '</p>';
353: } elsif (-d $target) {
354: $result .= '<p class="LC_warning">'.
355: &mt('File [_1] could not be copied.',
356: '<span class="LC_filename">'.$fn.'</span>').
357: '<br />'.
358: &mt('The target is an existing directory.').
359: '</p>';
360: } elsif (copy($source,$target)) {
361: chmod(0660, $target); # Set permissions to rw-rw---.
362: if ($mode eq 'testbank' || $mode eq 'imsimport') {
363: $returnflag = 'ok';
364: $result .= '<p class="LC_success">'
365: .&mt('Your file - [_1] - was uploaded successfully.',
366: '<span class="LC_filename">'.$fn.'<span>')
367: .'</p>';
368: } else {
369: $result .= '<p class="LC_success">'
370: .&mt('File copied.')
371: .'</p>';
372: }
373: # Check for embedded objects.
374: my (%allfiles,%codebase);
375: my ($text,$header,$css,$js);
376: if (($mode ne 'imsimport') && ($target =~ /\.(htm|html|shtml)$/i)) {
377: my (%allfiles,%codebase);
378: &Apache::lonnet::extract_embedded_items($target,\%allfiles,\%codebase);
379: if (keys(%allfiles) > 0) {
380: my ($currentpath) = ($url =~ m{^(.+)/[^/]+$});
381: my $state = &embedded_form_elems('upload_embedded',$url,$mode);
382: my ($embedded,$num,$pathchg) =
383: &Apache::loncommon::ask_for_embedded_content($action,$state,\%allfiles,
384: \%codebase,
385: {'error_on_invalid_names' => 1,
386: 'ignore_remote_references' => 1,
387: 'current_path' => $currentpath});
388: if ($embedded) {
389: $result .= '<h3>'.&mt('Reference Warning').'</h3>';
390: if ($num) {
391: $result .= '<p>'.&mt('Completed upload of the file.').' '.&mt('This file contained references to other files.').'</p>'.
392: '<p>'.&mt('Please select the locations from which the referenced files are to be uploaded.').'</p>'.
393: $embedded;
394: if ($mode eq 'testbank') {
395: $returnflag = 'embedded';
396: $result .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without these files.','<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
397: }
398: } else {
399: $result .= '<p>'.&mt('Completed upload of the file.').'</p>'.$embedded;
400: if ($pathchg) {
401: if ($mode eq 'testbank') {
402: $returnflag = 'embedded';
403: $result .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).','<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
404: }
405: }
406: }
407: }
408: }
409: }
410: if (($mode ne 'imsimport') && ($mode ne 'testbank')) {
411: $result .= '<br /><a href="'.$url.'">'.
412: &mt('View file').'</a>';
413: }
414: } else {
415: $result .= &mt('Failed to copy: [_1].',$!);
416: }
417: if ($mode ne 'imsimport' && $mode ne 'testbank') {
418: $result .= '<br /><a href="'.$dirpath.'">'.
419: &mt('Back to Directory').'</a><br />';
420: }
421: return ($result,$returnflag);
422: }
423:
424: sub phasethree {
425: my ($r,$fn,$uname,$udom,$mode) = @_;
426:
427: my $action = '/adm/upload';
428: if ($mode eq 'testbank') {
429: $action = '/adm/testbank';
430: } elsif ($mode eq 'imsimport') {
431: $action = '/adm/imsimport';
432: }
433: my $url_root = "/priv/$udom/$uname";
434: my $dir_root = $r->dir_config('lonDocRoot').$url_root;
435: my $path = &File::Basename::dirname($fn);
436: $path =~ s{^\Q$url_root\E}{};
437: my $dirpath = $url_root.$path.'/';
438: $dirpath=~s{/+}{/}g;
439: my $filename = &HTML::Entities::encode($env{'form.filename'},'<>&"');
440: my $state = &embedded_form_elems('modify_orightml',$filename,$mode).
441: '<input type="hidden" name="phase" value="four" />';
442: my ($result,$returnflag) =
443: &Apache::loncommon::upload_embedded($mode,$path,$uname,$udom,
444: $dir_root,$url_root,undef,
445: undef,undef,$state,$action);
446: if ($mode ne 'imsimport' && $mode ne 'testbank') {
447: $result .= '<br /><h3><a href="'.$fn.'">'.
448: &mt('View main file').'</a></h3>'.
449: '<h3><a href="'.$dirpath.'">'.
450: &mt('Back to Directory').'</a></h3><br />';
451: }
452: return ($result,$returnflag);
453: }
454:
455: sub embedded_form_elems {
456: my ($action,$filename,$mode) = @_;
457: return <<STATE;
458: <input type="hidden" name="action" value="$action" />
459: <input type="hidden" name="mode" value="$mode" />
460: <input type="hidden" name="filename" value="$filename" />
461: STATE
462: }
463:
464: sub phasefour {
465: my ($r,$fn,$uname,$udom,$mode) = @_;
466:
467: my $action = '/adm/upload';
468: if ($mode eq 'testbank') {
469: $action = '/adm/testbank';
470: } elsif ($mode eq 'imsimport') {
471: $action = '/adm/imsimport';
472: }
473: my $result;
474: my $url_root = "/priv/$udom/$uname";
475: my $dir_root = $r->dir_config('lonDocRoot').$url_root;
476: my $path = &File::Basename::dirname($fn);
477: $path =~ s{^\Q$url_root\E}{};
478: my $dirpath = $url_root.$path.'/';
479: $dirpath=~s{/+}{/}g;
480: my $outcome =
481: &Apache::loncommon::modify_html_refs($mode,$path,$uname,$udom,$dir_root);
482: $result .= $outcome;
483: if ($mode ne 'imsimport' && $mode ne 'testbank') {
484: $result .= '<br /><h3><a href="'.$fn.'">'.
485: &mt('View main file').'</a></h3>'.
486: '<h3><a href="'.$dirpath.'">'.
487: &mt('Back to Directory').'</a></h3><br />';
488: }
489: return $result;
490: }
491:
492: sub earlyout {
493: my ($fn,$uname,$udom) = @_;
494: if ($fn =~ m{^(/priv/$udom/$uname(?:.*)/)[^/]*}) {
495: return &Apache::lonhtmlcommon::actionbox(
496: ['<a href="'.$1.'">'.&mt('Return to Directory').'</a>']);
497: }
498: return;
499: }
500:
501: # ---------------------------------------------------------------- Main Handler
502: sub handler {
503:
504: my $r=shift;
505: my $javascript = '';
506: my $fn=$env{'form.filename'};
507:
508: if ($env{'form.filename1'}) {
509: $fn=$env{'form.filename1'}.$env{'form.filename2'};
510: }
511: $fn=~s/\/+/\//g;
512:
513: unless ($fn) {
514: $r->log_reason($env{'user.name'}.' at '.$env{'user.domain'}.
515: ' unspecified filename for upload', $r->filename);
516: return HTTP_NOT_FOUND;
517: }
518:
519: my ($uname,$udom)=&Apache::lonnet::constructaccess($fn);
520:
521: unless (($uname) && ($udom)) {
522: $r->log_reason($uname.' at '.$udom.
523: ' trying to publish file '.$env{'form.filename'}.
524: ' - not authorized',
525: $r->filename);
526: return HTTP_NOT_ACCEPTABLE;
527: }
528:
529: # ----------------------------------------------------------- Start page output
530:
531: &Apache::loncommon::content_type($r,'text/html');
532: $r->send_http_header;
533:
534: unless ($env{'form.phase'} eq 'two') {
535: $javascript = <<"ENDJS";
536: <script type="text/javascript">
537: // <![CDATA[
538: function verifyForm() {
539: var mode = document.fileupload.filetype.options[document.fileupload.filetype.selectedIndex].value
540: if (mode == "testbank") {
541: document.fileupload.action = "/adm/testbank";
542: }
543: if (mode == "imsimport") {
544: document.fileupload.action = "/adm/imsimport";
545: }
546: if (mode == "standard") {
547: document.fileupload.action = "/adm/upload";
548: }
549: document.fileupload.submit();
550: }
551: // ]]>
552: </script>
553: ENDJS
554: }
555:
556: my $londocroot = $r->dir_config('lonDocRoot');
557: my $trailfile = $fn;
558: $trailfile =~ s{^/(priv/)}{$londocroot/$1};
559:
560: # Breadcrumbs
561: my $brcrum = [{'href' => &Apache::loncommon::authorspace($fn),
562: 'text' => 'Authoring Space'},
563: {'href' => '/adm/upload',
564: 'text' => 'Upload file to Authoring Space'}];
565: $r->print(&Apache::loncommon::start_page('Upload file to Authoring Space',
566: $javascript,
567: {'bread_crumbs' => $brcrum,})
568: .&Apache::loncommon::head_subbox(
569: &Apache::loncommon::CSTR_pageheader($trailfile))
570: );
571:
572: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
573: $r->print('<p class="LC_info">'
574: .&mt('Co-Author [_1]',$uname.':'.$udom)
575: .'</p>'
576: );
577: }
578: if ($env{'form.phase'} eq 'four') {
579: my $output = &phasefour($r,$fn,$uname,$udom,'author');
580: $r->print($output);
581: } elsif ($env{'form.phase'} eq 'three') {
582: my ($output,$rtnflag) = &phasethree($r,$fn,$uname,$udom,'author');
583: $r->print($output);
584: } elsif ($env{'form.phase'} eq 'two') {
585: my ($output,$returnflag) = &phasetwo($r,$fn);
586: $r->print($output);
587: } else {
588: &phaseone($r,$fn,undef,$uname,$udom);
589: }
590:
591: $r->print(&Apache::loncommon::end_page());
592: return OK;
593: }
594:
595: 1;
596: __END__
597:
598:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>