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