Integration of new centralised upload code with admin/uploaduser.php and fix in uploa...
[moodle.git] / lib / uploadlib.php
CommitLineData
18b8fbfa 1<?php
2error_reporting(E_ALL ^ E_NOTICE);
3/**
4 * This class handles all aspects of fileuploading
5 */
6class upload_manager {
7
8 var $files; // array to hold local copies of stuff in $_FILES
9 var $config; // holds all configuration stuff.
10 var $status; // keep track of if we're ok (errors for each file are kept in $files['whatever']['uploadlog']
11 var $course; // the course this file has been uploaded for (for logging and virus notifications)
12 var $inputname; // if we're only getting one file.
13
14 /**
15 * Constructor, sets up configuration stuff so we know how to act.
16 * Note: destination not taken as parameter as some modules want to use the insertid in the path and we need to check the other stuff first.
17 * @param $inputname - if this is given the upload manager will only process the file in $_FILES with this name.
18 * @param $deleteothers - whether to delete other files in the destination directory (optional,defaults to false)
19 * @param $handlecollisions - whether to use handle_filename_collision() or not. (optional, defaults to false)
20 * @param $course - the course the files are being uploaded for (for logging and virus notifications)
21 * @param $recoverifmultiple - if we come across a virus, or if a file doesn't validate or whatever, do we continue? optional, defaults to true.
22 * @param $modbytes - max bytes for this module - this and $course->maxbytes are used to get the maxbytes to use (lowest) from get_max_upload_file_size().
23 */
24 function upload_manager($inputname='',$deleteothers=false,$handlecollisions=false,$course=null,$recoverifmultiple=false,$modbytes=0) {
25
26 global $CFG;
27
28 $this->config->deleteothers = $deleteothers;
29 $this->config->handlecollisions = $handlecollisions;
30 $this->config->recoverifmultiple = $recoverifmultiple;
31 $this->config->maxbytes = get_max_upload_file_size($CFG->maxbytes,$course->maxbytes,$modbytes);
32 $this->files = array();
33 $this->status = false;
34 $this->course = $course;
35 $this->inputname = $inputname;
36 }
37
38 /**
39 * Gets all entries out of $_FILES and stores them locally in $files
40 * Checks each one against get_max_upload_file_size and calls cleanfilename and scans them for viruses etc.
41 */
42 function preprocess_files() {
43 global $CFG;
44 foreach ($_FILES as $name => $file) {
45 $this->status = true; // only set it to true here so that we can check if this function has been called.
46 if (empty($this->inputname) || $name == $this->inputname) { // if we have input name, only process if it matches.
47 $file['originalname'] = $file['name']; // do this first for the log.
48 $this->files[$name] = $file; // put it in first so we can get uploadlog out in print_upload_log.
49 $this->status = $this->validate_file($this->files[$name],empty($this->inputname)); // default to only allowing empty on multiple uploads.
50 if (!$this->status && $this->files[$name]['error'] = 0 || $this->files[$name]['error'] == 4 && empty($this->inputname)) {
51 // this shouldn't cause everything to stop.. modules should be responsible for knowing which if any are compulsory.
52 continue;
53 }
54 if ($this->status && $CFG->runclamonupload) {
55 $this->status = clam_scan_file($this->files[$name],$this->course);
56 }
57 if (!$this->status) {
58 if (!$this->config->recoverifmultiple && count($this->files) > 1) {
59 $a->name = $this->files[$name]['originalname'];
60 $a->problem = $this->files[$name]['uploadlog'];
61 notify(get_string('uploadfailednotrecovering','moodle',$a));
62 $this->status = false;
63 return false;
64 }
65 else if (count($this->files) == 1) {
66 notify($this->files[$name]['uploadlog']);
67 $this->status = false;
68 return false;
69 }
70 }
71 else {
72 $newname = clean_filename($this->files[$name]['name']);
73 if ($newname != $this->files[$name]['name']) {
74 $a->oldname = $this->files[$name]['name'];
75 $a->newname = $newname;
76 $this->files[$name]['uploadlog'] .= get_string('uploadrenamedchars','moodle',$a);
77 }
78 $this->files[$name]['name'] = $newname;
79 $this->files[$name]['clear'] = true; // ok to save.
80 }
81 }
82 }
46c5446e 83 if (!is_array($_FILES) || count($_FILES) == 0) {
84 return false;
85 }
18b8fbfa 86 $this->status = true;
87 return true; // if we've got this far it means that we're recovering so we want status to be ok.
88 }
89
90 /**
91 * Validates a single file entry from _FILES
92 * @param $file - the entry from _FILES to validate
93 * @param $allowempty - this is to allow module owners to control which files are compulsory if this function is being called straight from the module.
94 * @return true if ok.
95 */
96 function validate_file(&$file,$allowempty=true) {
97 if (empty($file)) {
98 return $allowempty; // this shouldn't cause everything to stop.. modules should be responsible for knowing which if any are compulsory.
99 }
100 if (!is_uploaded_file($file['tmp_name']) || $file['size'] == 0) {
101 $file['uploadlog'] .= "\n".$this->get_file_upload_error($file);
102 if ($file['error'] == 0 || $file['error'] == 4) {
103 return $allowempty;
104 }
105 return false;
106 }
107 if ($file['size'] > $this->config->maxbytes) {
108 $file['uploadlog'] .= "\n".get_string("uploadedfiletoobig", "moodle", $this->config->maxbytes);
109 return false;
110 }
111 return true;
112 }
113
114 /**
115 * Moves all the files to the destination directory.
116 * @param $destination - the destination directory.
117 * @return status;
118 */
119 function save_files($destination) {
120 global $CFG,$USER;
121
122 if (!$this->status) { // preprocess_files hasn't been run
123 $this->preprocess_files();
124 }
125 if ($this->status) {
126 if (!(strpos($destination,$CFG->dataroot) === false)) {
127 // take it out for giving to make_upload_directory
128 $destination = substr($destination,strlen($CFG->dataroot)+1);
129 }
130
131 if ($destination{strlen($destination)-1} == "/") { // strip off a trailing / if we have one
132 $destination = substr($destination,0,-1);
133 }
134
135 if (!make_upload_directory($destination,true)) { //TODO maybe put this function here instead of moodlelib.php now.
136 $this->status = false;
137 return false;
138 }
139
140 $destination = $CFG->dataroot.'/'.$destination; // now add it back in so we have a full path
141
142 $exceptions = array(); //need this later if we're deleting other files.
143
144 foreach (array_keys($this->files) as $i) {
145
146 if (!$this->files[$i]['clear']) {
147 // not ok to save
148 continue;
149 }
150
151 if ($this->config->handlecollisions) {
152 $this->handle_filename_collision($destination,$this->files[$i]);
153 }
154 if (move_uploaded_file($this->files[$i]['tmp_name'], $destination.'/'.$this->files[$i]['name'])) {
155 chmod($destination.'/'.$this->files[$i]['name'], $CFG->directorypermissions);
156 $this->files[$i]['fullpath'] = $destination.'/'.$this->files[$i]['name'];
157 $this->files[$i]['uploadlog'] .= "\n".get_string('uploadedfile');
158 $this->files[$i]['saved'] = true;
159 $exceptions[] = $this->files[$i]['name'];
160 // now add it to the log (this is important so we know who to notify if a virus is found later on)
161 clam_log_upload($this->files[$i]['fullpath'],$this->course);
162 $savedsomething=true;
163 }
164 }
165 if ($savedsomething && $this->config->deleteothers) {
166 $this->delete_other_files($destination,$exceptions);
167 }
168 }
169 if (!$savedsomething) {
170 $this->status = false;
171 return false;
172 }
173 return $this->status;
174 }
175
176 /**
177 * Wrapper function that calls preprocess_files and viruscheck_files and then save_files
178 * Modules that require the insert id in the filepath should not use this and call these functions seperately in the required order.
179 * @parameter $destination - where to save the uploaded files to.
180 */
181 function process_file_uploads($destination) {
182 if ($this->preprocess_files()) {
183 return $this->save_files($destination);
184 }
185 return false;
186 }
187
188 /**
189 * Deletes all the files in a given directory except for the files in $exceptions (full paths)
190 * @param $destination - the directory to clean up.
191 * @param $exceptions - array of full paths of files to KEEP.
192 */
193 function delete_other_files($destination,$exceptions=null) {
194 if ($filestodel = get_directory_list($destination)) {
195 foreach ($filestodel as $file) {
196 if (!is_array($exceptions) || !in_array($file,$exceptions)) {
197 unlink("$destination/$file");
198 $deletedsomething = true;
199 }
200 }
201 }
202 if ($deletedsomething) {
203 notify(get_string('uploadoldfilesdeleted'));
204 }
205 }
206
207 /**
208 * Handles filename collisions - if the desired filename exists it will rename it according to the pattern in $format
209 * @param $destination - destination directory (to check existing files against)
210 * @param $file - the current file from $files we're processing.
211 * @param $format - the printf style format to rename the file to (defaults to filename_number.extn)
212 * @return new filename.
213 */
214 function handle_filename_collision($destination,&$file,$format='%s_%d.%s') {
215 $bits = explode('.',$file['name']);
216 // check for collisions and append a nice numberydoo.
217 if (file_exists($destination.'/'.$file['name'])) {
218 $a->oldname = $file['name'];
219 for ($i = 1; true; $i++) {
220 $try = sprintf($format,$bits[0],$i,$bits[1]);
221 if ($this->check_before_renaming($destination,$try,$file)) {
222 $file['name'] = $try;
223 break;
224 }
225 }
226 $a->newname = $file['name'];
227 $file['uploadlog'] .= "\n".get_string('uploadrenamedcollision','moodle',$a);
228 }
229 }
230
231 /**
232 * This function checks a potential filename against what's on the filesystem already and what's been saved already.
233 */
234 function check_before_renaming($destination,$nametocheck,$file) {
235 if (!file_exists($destination.'/'.$nametocheck)) {
236 return true;
237 }
238 if ($this->config->deleteothers) {
239 foreach ($this->files as $tocheck) {
240 // if we're deleting files anyway, it's not THIS file and we care about it and it has the same name and has already been saved..
241 if ($file['tmp_name'] != $tocheck['tmp_name'] && $tocheck['clear'] && $nametocheck == $tocheck['name'] && $tocheck['saved']) {
242 $collision = true;
243 }
244 }
245 if (!$collision) {
246 return true;
247 }
248 }
249 return false;
250 }
251
252
253 function get_file_upload_error(&$file) {
254
255 switch ($file['error']) {
256 case 0: // UPLOAD_ERR_OK
257 if ($file['size'] > 0) {
258 $errmessage = get_string('uploadproblem', $file['name']);
259 } else {
260 $errmessage = get_string('uploadnofilefound'); /// probably a dud file name
261 }
262 break;
263
264 case 1: // UPLOAD_ERR_INI_SIZE
265 $errmessage = get_string('uploadserverlimit');
266 break;
267
268 case 2: // UPLOAD_ERR_FORM_SIZE
269 $errmessage = get_string('uploadformlimit');
270 break;
271
272 case 3: // UPLOAD_ERR_PARTIAL
273 $errmessage = get_string('uploadpartialfile');
274 break;
275
276 case 4: // UPLOAD_ERR_NO_FILE
277 $errmessage = get_string('uploadnofilefound');
278 break;
279
280 default:
281 $errmessage = get_string('uploadproblem', $file['name']);
282 }
283 return $errmessage;
284 }
285
286 /**
287 * prints a log of everything that happened (of interest) to each file in _FILES
288 * @param $return - optional, defaults to false (log is echoed)
289 */
290 function print_upload_log($return=false) {
291 foreach (array_keys($this->files) as $i => $key) {
292 $str .= '<b>'.get_string('uploadfilelog','moodle',$i+1).' '
293 .((!empty($this->files[$key]['originalname'])) ? '('.$this->files[$key]['originalname'].')' : '')
294 .'</b> :'.nl2br($this->files[$key]['uploadlog']).'<br />';
295 }
296 if ($return) {
297 return $str;
298 }
299 echo $str;
300 }
301
302 /**
303 * If we're only handling one file (if inputname was given in the constructor) this will return the (possibly changed) filename of the file.
304 */
305 function get_new_filename() {
306 if (!empty($this->inputname) && count($this->files) == 1) {
307 return $this->files[$this->inputname]['name'];
308 }
309 return false;
310 }
311
312 /**
313 * If we're only handling one file (if inputname was given in the constructor) this will return the ORIGINAL filename of the file.
314 */
315 function get_original_filename() {
316 if (!empty($this->inputname) && count($this->files) == 1) {
317 return $this->files[$this->inputname]['originalname'];
318 }
319 return false;
320 }
321}
322
323/**************************************************************************************
324THESE FUNCTIONS ARE OUTSIDE THE CLASS BECAUSE THEY NEED TO BE CALLED FROM OTHER PLACES.
325FOR EXAMPLE CLAM_HANDLE_INFECTED_FILE AND CLAM_REPLACE_INFECTED_FILE USED FROM CRON
326UPLOAD_PRINT_FORM_FRAGMENT DOESN'T REALLY BELONG IN THE CLASS BUT CERTAINLY IN THIS FILE
327***************************************************************************************/
328
329
330/**
331 * This function prints out a number of upload form elements
332 * @param $numfiles - the number of elements required (optional, defaults to 1)
333 * @param $names - array of element names to use (optional, defaults to FILE_n)
334 * @param $descriptions - array of strings to be printed out before each file bit.
335 * @param $uselabels - whether to output text fields for file descriptions or not (optional, defaults to false)
336 * @param $labelnames - array of element names to use for labels (optional, defaults to LABEL_n)
337 * @param $coursebytes
338 * @param $modbytes - these last two are used to calculate upload max size ( using get_max_upload_file_size)
339 * @param $return - whether to return the string (defaults to false - string is echoed)
340 */
341function upload_print_form_fragment($numfiles=1,$names=null,$descriptions=null,$uselabels=false,$labelnames=null,$coursebytes=0,$modbytes=0,$return=false) {
342 global $CFG;
343 $maxbytes = get_max_upload_file_size($CFG->maxbytes,$coursebytes,$modbytes);
344 $str = '<input type="hidden" name="MAX_FILE_SIZE" value="'.$maxbytes.'" />'."\n";
345 for ($i = 0; $i < $numfiles; $i++) {
346 if (is_array($descriptions) && !empty($descriptions[$i])) {
347 $str .= '<b>'.$descriptions[$i].'</b><br />';
348 }
349 $str .= '<input type="file" size="50" name="'.((is_array($names) && !empty($names[$i])) ? $names[$i] : 'FILE_'.$i).'" /><br />'."\n";
350 if ($uselabels) {
351 $str .= get_string('uploadlabel').' <input type="text" size="50" name="'
352 .((is_array($labelnames) && !empty($labelnames[$i])) ? $labelnames[$i] : 'LABEL_'.$i)
353 .'" /><br /><br />'."\n";
354 }
355 }
356 if ($return) {
357 return $str;
358 }
359 else {
360 echo $str;
361 }
362}
363
364
365/**
366 * Deals with an infected file - either moves it to a quarantinedir
367 * (specified in CFG->quarantinedir) or deletes it.
368 * If moving it fails, it deletes it.
369 * @param file full path to the file
370 * @param userid - if not used, defaults to $USER->id (there in case called from cron)
371 * @param basiconly - admin level reporting or user level reporting.
372 * @return a string of what it did.
373 */
374function clam_handle_infected_file($file,$userid=0,$basiconly=false) {
375
376 global $CFG,$USER;
377 if ($USER && !$userid) {
378 $userid = $USER->id;
379 }
380 $delete = true;
381 if (file_exists($CFG->quarantinedir) && is_dir($CFG->quarantinedir) && is_writable($CFG->quarantinedir)) {
382 $now = date('YmdHis');
383 if (rename($file,$CFG->quarantinedir.'/'.$now.'-user-'.$userid.'-infected')) {
384 $delete = false;
385 if ($basiconly) {
386 $notice .= "\n".get_string('clammovedfilebasic');
387 }
388 else {
389 $notice .= "\n".get_string('clammovedfile','moodle',$CFG->quarantinedir.'/'.$now.'-user-'.$userid.'-infected');
390 }
391 }
392 else {
393 if ($basiconly) {
394 $notice .= "\n".get_string('clamdeletedfile');
395 }
396 else {
397 $notice .= "\n".get_string('clamquarantinedirfailed','moodle',$CFG->quarantinedir);
398 }
399 }
400 }
401 else {
402 if ($basiconly) {
403 $notice .= "\n".get_string('clamdeletedfile');
404 }
405 else {
406 $notice .= "\n".get_string('clamquarantinedirfailed','moodle',$CFG->quarantinedir);
407 }
408 }
409 if ($delete) {
410 if (unlink($file)) {
411 $notice .= "\n".get_string('clamdeletedfile');
412 }
413 else {
414 if ($basiconly) {
415 // still tell the user the file has been deleted. this is only for admins.
416 $notice .= "\n".get_string('clamdeletedfile');
417 }
418 else {
419 $notice .= "\n".get_string('clamdeletedfilefailed');
420 }
421 }
422 }
423 return $notice;
424}
425
426/**
427 * Replaces the given file with a string to notify that the original file had a virus.
428 * This is to avoid missing files but could result in the wrong content-type.
429 * @param file - full path to the file.
430 */
431function clam_replace_infected_file($file) {
432 $newcontents = get_string('virusplaceholder');
433 if (!$f = fopen($file,'w')) {
434 return false;
435 }
436 if (!fwrite($f,$newcontents)) {
437 return false;
438 }
439 return true;
440}
441
442
443/**
444 * If $CFG->runclamonupload is set, we scan a given file. (called from preprocess_files)
445 * This function will add on a uploadlog index in $file.
446 * @param $file - the file to scan from $files. or an absolute path to a file.
447 * @return 1 if good, 0 if something goes wrong (opposite from actual error code from clam)
448 */
449function clam_scan_file(&$file,$course) {
450 global $CFG,$USER;
451
452 if (is_array($file) && is_uploaded_file($file['tmp_name'])) { // it's from $_FILES
453 $appendlog = true;
454 $fullpath = $file['tmp_name'];
455 }
456 else if (file_exists($file)) { // it's a path to somewhere on the filesystem!
457 $fullpath = $file;
458 }
459 else {
460 return false; // erm, what is this supposed to be then, huh?
461 }
462
463 if (!$CFG->pathtoclam || !file_exists($CFG->pathtoclam) || !is_executable($CFG->pathtoclam)) {
464 $newreturn = 1;
465 $notice = get_string('clamlost','moodle',$CFG->pathtoclam);
466 if ($CFG->clamfailureonupload == 'actlikevirus') {
467 $notice .= "\n".get_string('clamlostandactinglikevirus');
468 $notice .= "\n".clam_handle_infected_file($fullpath);
469 $newreturn = false;
470 }
471 clam_mail_admins($notice);
472 return $newreturn; // return 1 if we're allowing clam failures
473 }
474
475 $cmd = $CFG->pathtoclam.' '.$fullpath." 2>&1";
476
477 // before we do anything we need to change perms so that clamscan can read the file (clamdscan won't work otherwise)
478 chmod($fullpath,0644);
479
480 exec($cmd,$output,$return);
481
482
483 switch ($return) {
484 case 0: // glee! we're ok.
485 return 1; // translate clam return code into reasonable return code consistent with everything else.
486 case 1: // bad wicked evil, we have a virus.
487 if (!empty($course)) {
488 $info->course = $course->fullname;
489 }
490 else {
491 $info->course = 'No course';
492 }
493 $info->user = $USER->firstname.' '.$USER->lastname;
494 $notice = get_string('virusfound','moodle',$info);
495 $notice .= "\n\n".implode("\n",$output);
496 $notice .= "\n\n".clam_handle_infected_file($fullpath);
497 clam_mail_admins($notice);
498 if ($appendlog) {
499 $info->filename = $file['originalname'];
500 $file['uploadlog'] .= "\n".get_string('virusfounduser','moodle',$info);
501 $file['virus'] = 1;
502 }
503 return false; // in this case, 0 means bad.
504 default:
505 // error - clam failed to run or something went wrong
506 $notice .= get_string('clamfailed','moodle',get_clam_error_code($return));
507 $notice .= "\n\n".implode("\n",$output);
508 $newreturn = true;
509 if ($CFG->clamfailureonupload == 'actlikevirus') {
510 $notice .= "\n".clam_handle_infected_file($fullpath);
511 $newreturn = false;
512 }
513 clam_mail_admins($notice);
514 if ($appendlog) {
515 $file['uploadlog'] .= "\n".get_string('clambroken');
516 $file['clam'] = 1;
517 }
518 return $newreturn; // return 1 if we're allowing failures.
519 }
520}
521
522/**
523 * emails admins about a clam outcome
524 * @param notice - the body of the email.
525 */
526function clam_mail_admins($notice) {
527
528 $site = get_site();
529
530 $subject = get_string('clamemailsubject','moodle',$site->fullname);
531 $admins = get_admins();
532 foreach ($admins as $admin) {
533 email_to_user($admin,get_admin(),$subject,$notice);
534 }
535}
536
537
538function get_clam_error_code($returncode) {
539 $returncodes = array();
540 $returncodes[0] = 'No virus found.';
541 $returncodes[1] = 'Virus(es) found.';
542 $returncodes[2] = ' An error occured'; // specific to clamdscan
543 // all after here are specific to clamscan
544 $returncodes[40] = 'Unknown option passed.';
545 $returncodes[50] = 'Database initialization error.';
546 $returncodes[52] = 'Not supported file type.';
547 $returncodes[53] = 'Can\'t open directory.';
548 $returncodes[54] = 'Can\'t open file. (ofm)';
549 $returncodes[55] = 'Error reading file. (ofm)';
550 $returncodes[56] = 'Can\'t stat input file / directory.';
551 $returncodes[57] = 'Can\'t get absolute path name of current working directory.';
552 $returncodes[58] = 'I/O error, please check your filesystem.';
553 $returncodes[59] = 'Can\'t get information about current user from /etc/passwd.';
554 $returncodes[60] = 'Can\'t get information about user \'clamav\' (default name) from /etc/passwd.';
555 $returncodes[61] = 'Can\'t fork.';
556 $returncodes[63] = 'Can\'t create temporary files/directories (check permissions).';
557 $returncodes[64] = 'Can\'t write to temporary directory (please specify another one).';
558 $returncodes[70] = 'Can\'t allocate and clear memory (calloc).';
559 $returncodes[71] = 'Can\'t allocate memory (malloc).';
560 if ($returncodes[$returncode])
561 return $returncodes[$returncode];
562 return get_string('clamunknownerror');
563
564}
565
566/**
567 * adds a file upload to the log table so that clam can resolve the filename to the user later if necessary
568 */
569function clam_log_upload($newfilepath,$course=null) {
570 global $CFG,$USER;
571 // get rid of any double // that might have appeared
572 $newfilepath = preg_replace('/\/\//','/',$newfilepath);
573 if (strpos($newfilepath,$CFG->dataroot) === false) {
574 $newfilepath = $CFG->dataroot.'/'.$newfilepath;
575 }
576 $CFG->debug=10;
577 $courseid = 0;
578 if ($course) {
579 $courseid = $course->id;
580 }
581 add_to_log($courseid,"upload","upload","",$newfilepath);
582}
583
584/**
585 * some of the modules allow moving attachments (glossary), in which case we need to hunt down an original log and change the path.
586 */
587function clam_change_log($oldpath,$newpath) {
588 global $CFG;
589 $sql = "UPDATE {$CFG->prefix}log SET info = '$newpath' WHERE module = 'upload' AND info = '$oldpath'";
590 execute_sql($sql);
591}
592?>