Merge from stable branch: Convert tabs to spaces in files where there were only a...
[moodle.git] / lib / uploadlib.php
CommitLineData
18b8fbfa 1<?php
c9b5ebf5 2
3/**
4 * uploadlib.php - This class handles all aspects of fileuploading
5 *
6 * @author ?
7 * @version 1.5
8 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
9 * @package moodlecore
10 */
11
18b8fbfa 12error_reporting(E_ALL ^ E_NOTICE);
13/**
c9b5ebf5 14 * This class handles all aspects of fileuploading
18b8fbfa 15 */
16class upload_manager {
17
c9b5ebf5 18 /**
19 * Array to hold local copies of stuff in $_FILES
20 * @var array $files
21 */
22 var $files;
23 /**
24 * Holds all configuration stuff
25 * @var array $config
26 */
27 var $config;
28 /**
29 * Keep track of if we're ok
30 * (errors for each file are kept in $files['whatever']['uploadlog']
31 * @var boolean $status
32 */
33 var $status;
34 /**
35 * The course this file has been uploaded for. {@link $COURSE}
36 * (for logging and virus notifications)
37 * @var course $course
38 */
39 var $course;
40 /**
41 * If we're only getting one file.
42 * (for logging and virus notifications)
43 * @var string $inputname
44 */
45 var $inputname;
46 /**
47 * If we're given silent=true in the constructor, this gets built
48 * up to hold info about the process.
49 * @var string $notify
50 */
51 var $notify;
18b8fbfa 52
53 /**
54 * Constructor, sets up configuration stuff so we know how to act.
c9b5ebf5 55 *
18b8fbfa 56 * 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.
c9b5ebf5 57 *
58 * @uses $CFG
59 * @param string $inputname If this is given the upload manager will only process the file in $_FILES with this name.
60 * @param boolean $deleteothers Whether to delete other files in the destination directory (optional, defaults to false)
61 * @param boolean $handlecollisions Whether to use {@link handle_filename_collision()} or not. (optional, defaults to false)
62 * @param course $course The course the files are being uploaded for (for logging and virus notifications) {@link $COURSE}
63 * @param boolean $recoverifmultiple If we come across a virus, or if a file doesn't validate or whatever, do we continue? optional, defaults to true.
64 * @param int $modbytes Max bytes for this module - this and $course->maxbytes are used to get the maxbytes from {@link get_max_upload_file_size()}.
65 * @param boolean $silent Whether to notify errors or not.
66 * @param boolean $allownull Whether we care if there's no file when we've set the input name.
aff2944e 67 * @param boolean $allownullmultiple Whether we care if there's no files AT ALL when we've got multiples. This won't complain if we have file 1 and file 3 but not file 2, only for NO FILES AT ALL.
18b8fbfa 68 */
aff2944e 69 function upload_manager($inputname='', $deleteothers=false, $handlecollisions=false, $course=null, $recoverifmultiple=false, $modbytes=0, $silent=false, $allownull=false, $allownullmultiple=true) {
18b8fbfa 70
71 global $CFG;
72
73 $this->config->deleteothers = $deleteothers;
74 $this->config->handlecollisions = $handlecollisions;
75 $this->config->recoverifmultiple = $recoverifmultiple;
c9b5ebf5 76 $this->config->maxbytes = get_max_upload_file_size($CFG->maxbytes, $course->maxbytes, $modbytes);
81d425b4 77 $this->config->silent = $silent;
96038147 78 $this->config->allownull = $allownull;
18b8fbfa 79 $this->files = array();
80 $this->status = false;
81 $this->course = $course;
82 $this->inputname = $inputname;
96038147 83 if (empty($this->inputname)) {
aff2944e 84 $this->config->allownull = $allownullmultiple;
96038147 85 }
18b8fbfa 86 }
87
88 /**
c9b5ebf5 89 * Gets all entries out of $_FILES and stores them locally in $files and then
90 * checks each one against {@link get_max_upload_file_size()} and calls {@link cleanfilename()}
91 * and scans them for viruses etc.
92 * @uses $CFG
93 * @uses $_FILES
94 * @return boolean
18b8fbfa 95 */
96 function preprocess_files() {
97 global $CFG;
9056cec0 98
18b8fbfa 99 foreach ($_FILES as $name => $file) {
100 $this->status = true; // only set it to true here so that we can check if this function has been called.
101 if (empty($this->inputname) || $name == $this->inputname) { // if we have input name, only process if it matches.
102 $file['originalname'] = $file['name']; // do this first for the log.
103 $this->files[$name] = $file; // put it in first so we can get uploadlog out in print_upload_log.
96038147 104 $this->status = $this->validate_file($this->files[$name]); // default to only allowing empty on multiple uploads.
aff2944e 105 if (!$this->status && ($this->files[$name]['error'] == 0 || $this->files[$name]['error'] == 4) && ($this->config->allownull || empty($this->inputname))) {
18b8fbfa 106 // this shouldn't cause everything to stop.. modules should be responsible for knowing which if any are compulsory.
107 continue;
108 }
109 if ($this->status && $CFG->runclamonupload) {
110 $this->status = clam_scan_file($this->files[$name],$this->course);
111 }
112 if (!$this->status) {
113 if (!$this->config->recoverifmultiple && count($this->files) > 1) {
114 $a->name = $this->files[$name]['originalname'];
115 $a->problem = $this->files[$name]['uploadlog'];
81d425b4 116 if (!$this->config->silent) {
117 notify(get_string('uploadfailednotrecovering','moodle',$a));
118 }
119 else {
c9b5ebf5 120 $this->notify .= '<br />'. get_string('uploadfailednotrecovering','moodle',$a);
81d425b4 121 }
18b8fbfa 122 $this->status = false;
123 return false;
9056cec0 124
125 } else if (count($this->files) == 1) {
126
127 if (!$this->config->silent and !$this->config->allownull) {
81d425b4 128 notify($this->files[$name]['uploadlog']);
9056cec0 129 } else {
c9b5ebf5 130 $this->notify .= '<br />'. $this->files[$name]['uploadlog'];
81d425b4 131 }
18b8fbfa 132 $this->status = false;
133 return false;
134 }
135 }
136 else {
137 $newname = clean_filename($this->files[$name]['name']);
138 if ($newname != $this->files[$name]['name']) {
139 $a->oldname = $this->files[$name]['name'];
140 $a->newname = $newname;
c9b5ebf5 141 $this->files[$name]['uploadlog'] .= get_string('uploadrenamedchars','moodle', $a);
18b8fbfa 142 }
143 $this->files[$name]['name'] = $newname;
144 $this->files[$name]['clear'] = true; // ok to save.
3abd1a55 145 $this->config->somethingtosave = true;
18b8fbfa 146 }
147 }
148 }
46c5446e 149 if (!is_array($_FILES) || count($_FILES) == 0) {
96038147 150 return $this->config->allownull;
46c5446e 151 }
18b8fbfa 152 $this->status = true;
153 return true; // if we've got this far it means that we're recovering so we want status to be ok.
154 }
155
156 /**
157 * Validates a single file entry from _FILES
c9b5ebf5 158 *
159 * @param object $file The entry from _FILES to validate
160 * @return boolean True if ok.
18b8fbfa 161 */
96038147 162 function validate_file(&$file) {
18b8fbfa 163 if (empty($file)) {
96038147 164 return false;
18b8fbfa 165 }
166 if (!is_uploaded_file($file['tmp_name']) || $file['size'] == 0) {
167 $file['uploadlog'] .= "\n".$this->get_file_upload_error($file);
18b8fbfa 168 return false;
169 }
170 if ($file['size'] > $this->config->maxbytes) {
c9b5ebf5 171 $file['uploadlog'] .= "\n". get_string('uploadedfiletoobig', 'moodle', $this->config->maxbytes);
18b8fbfa 172 return false;
173 }
174 return true;
175 }
176
177 /**
178 * Moves all the files to the destination directory.
c9b5ebf5 179 *
180 * @uses $CFG
181 * @uses $USER
182 * @param string $destination The destination directory.
183 * @return boolean status;
18b8fbfa 184 */
185 function save_files($destination) {
c9b5ebf5 186 global $CFG, $USER;
18b8fbfa 187
188 if (!$this->status) { // preprocess_files hasn't been run
189 $this->preprocess_files();
190 }
3abd1a55 191
192 // if there are no files, bail before we create an empty directory.
193 if (empty($this->config->somethingtosave)) {
194 return true;
195 }
196
18b8fbfa 197 if ($this->status) {
c9b5ebf5 198 if (!(strpos($destination, $CFG->dataroot) === false)) {
18b8fbfa 199 // take it out for giving to make_upload_directory
c9b5ebf5 200 $destination = substr($destination, strlen($CFG->dataroot)+1);
18b8fbfa 201 }
202
c9b5ebf5 203 if ($destination{strlen($destination)-1} == '/') { // strip off a trailing / if we have one
204 $destination = substr($destination, 0, -1);
18b8fbfa 205 }
206
c9b5ebf5 207 if (!make_upload_directory($destination, true)) { //TODO maybe put this function here instead of moodlelib.php now.
18b8fbfa 208 $this->status = false;
209 return false;
210 }
211
c9b5ebf5 212 $destination = $CFG->dataroot .'/'. $destination; // now add it back in so we have a full path
18b8fbfa 213
214 $exceptions = array(); //need this later if we're deleting other files.
215
216 foreach (array_keys($this->files) as $i) {
217
218 if (!$this->files[$i]['clear']) {
219 // not ok to save
220 continue;
221 }
222
223 if ($this->config->handlecollisions) {
c9b5ebf5 224 $this->handle_filename_collision($destination, $this->files[$i]);
18b8fbfa 225 }
226 if (move_uploaded_file($this->files[$i]['tmp_name'], $destination.'/'.$this->files[$i]['name'])) {
c9b5ebf5 227 chmod($destination .'/'. $this->files[$i]['name'], $CFG->directorypermissions);
18b8fbfa 228 $this->files[$i]['fullpath'] = $destination.'/'.$this->files[$i]['name'];
229 $this->files[$i]['uploadlog'] .= "\n".get_string('uploadedfile');
230 $this->files[$i]['saved'] = true;
231 $exceptions[] = $this->files[$i]['name'];
232 // now add it to the log (this is important so we know who to notify if a virus is found later on)
c9b5ebf5 233 clam_log_upload($this->files[$i]['fullpath'], $this->course);
18b8fbfa 234 $savedsomething=true;
235 }
236 }
237 if ($savedsomething && $this->config->deleteothers) {
c9b5ebf5 238 $this->delete_other_files($destination, $exceptions);
18b8fbfa 239 }
240 }
aff2944e 241 if (empty($savedsomething)) {
18b8fbfa 242 $this->status = false;
aba94550 243 if ((empty($this->config->allownull) && !empty($this->inputname)) || (empty($this->inputname) && empty($this->config->allownullmultiple))) {
aff2944e 244 notify(get_string('uploadnofilefound'));
245 }
18b8fbfa 246 return false;
247 }
248 return $this->status;
249 }
250
251 /**
c9b5ebf5 252 * Wrapper function that calls {@link preprocess_files()} and {@link viruscheck_files()} and then {@link save_files()}
18b8fbfa 253 * Modules that require the insert id in the filepath should not use this and call these functions seperately in the required order.
c9b5ebf5 254 * @parameter string $destination Where to save the uploaded files to.
255 * @return boolean
18b8fbfa 256 */
257 function process_file_uploads($destination) {
258 if ($this->preprocess_files()) {
259 return $this->save_files($destination);
260 }
261 return false;
262 }
263
264 /**
265 * Deletes all the files in a given directory except for the files in $exceptions (full paths)
c9b5ebf5 266 *
267 * @param string $destination The directory to clean up.
268 * @param array $exceptions Full paths of files to KEEP.
18b8fbfa 269 */
c9b5ebf5 270 function delete_other_files($destination, $exceptions=null) {
18b8fbfa 271 if ($filestodel = get_directory_list($destination)) {
272 foreach ($filestodel as $file) {
c9b5ebf5 273 if (!is_array($exceptions) || !in_array($file, $exceptions)) {
274 unlink($destination .'/'. $file);
18b8fbfa 275 $deletedsomething = true;
276 }
277 }
278 }
279 if ($deletedsomething) {
81d425b4 280 if (!$this->config->silent) {
281 notify(get_string('uploadoldfilesdeleted'));
282 }
283 else {
c9b5ebf5 284 $this->notify .= '<br />'. get_string('uploadoldfilesdeleted');
81d425b4 285 }
18b8fbfa 286 }
287 }
288
289 /**
290 * Handles filename collisions - if the desired filename exists it will rename it according to the pattern in $format
c9b5ebf5 291 * @param string $destination Destination directory (to check existing files against)
292 * @param object $file Passed in by reference. The current file from $files we're processing.
293 * @param string $format The printf style format to rename the file to (defaults to filename_number.extn)
294 * @return string The new filename.
295 * @todo verify return type - this function does not appear to return anything since $file is passed in by reference
18b8fbfa 296 */
c9b5ebf5 297 function handle_filename_collision($destination, &$file, $format='%s_%d.%s') {
298 $bits = explode('.', $file['name']);
18b8fbfa 299 // check for collisions and append a nice numberydoo.
c9b5ebf5 300 if (file_exists($destination .'/'. $file['name'])) {
18b8fbfa 301 $a->oldname = $file['name'];
302 for ($i = 1; true; $i++) {
c9b5ebf5 303 $try = sprintf($format, $bits[0], $i, $bits[1]);
304 if ($this->check_before_renaming($destination, $try, $file)) {
18b8fbfa 305 $file['name'] = $try;
306 break;
307 }
308 }
309 $a->newname = $file['name'];
c9b5ebf5 310 $file['uploadlog'] .= "\n". get_string('uploadrenamedcollision','moodle', $a);
18b8fbfa 311 }
312 }
313
314 /**
315 * This function checks a potential filename against what's on the filesystem already and what's been saved already.
c9b5ebf5 316 * @param string $destination Destination directory (to check existing files against)
317 * @param string $nametocheck The filename to be compared.
318 * @param object $file The current file from $files we're processing.
319 * return boolean
18b8fbfa 320 */
c9b5ebf5 321 function check_before_renaming($destination, $nametocheck, $file) {
322 if (!file_exists($destination .'/'. $nametocheck)) {
18b8fbfa 323 return true;
324 }
325 if ($this->config->deleteothers) {
326 foreach ($this->files as $tocheck) {
327 // 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..
328 if ($file['tmp_name'] != $tocheck['tmp_name'] && $tocheck['clear'] && $nametocheck == $tocheck['name'] && $tocheck['saved']) {
329 $collision = true;
330 }
331 }
332 if (!$collision) {
333 return true;
334 }
335 }
336 return false;
337 }
338
c9b5ebf5 339 /**
340 * ?
341 *
342 * @param object $file Passed in by reference. The current file from $files we're processing.
343 * @return string
344 * @todo Finish documenting this function
345 */
18b8fbfa 346 function get_file_upload_error(&$file) {
347
348 switch ($file['error']) {
349 case 0: // UPLOAD_ERR_OK
350 if ($file['size'] > 0) {
351 $errmessage = get_string('uploadproblem', $file['name']);
352 } else {
353 $errmessage = get_string('uploadnofilefound'); /// probably a dud file name
354 }
355 break;
356
357 case 1: // UPLOAD_ERR_INI_SIZE
358 $errmessage = get_string('uploadserverlimit');
359 break;
360
361 case 2: // UPLOAD_ERR_FORM_SIZE
362 $errmessage = get_string('uploadformlimit');
363 break;
364
365 case 3: // UPLOAD_ERR_PARTIAL
366 $errmessage = get_string('uploadpartialfile');
367 break;
368
369 case 4: // UPLOAD_ERR_NO_FILE
370 $errmessage = get_string('uploadnofilefound');
371 break;
372
373 default:
374 $errmessage = get_string('uploadproblem', $file['name']);
375 }
376 return $errmessage;
377 }
378
379 /**
380 * prints a log of everything that happened (of interest) to each file in _FILES
381 * @param $return - optional, defaults to false (log is echoed)
382 */
aff2944e 383 function print_upload_log($return=false,$skipemptyifmultiple=false) {
18b8fbfa 384 foreach (array_keys($this->files) as $i => $key) {
aff2944e 385 if (count($this->files) > 1 && !empty($skipemptyifmultiple) && $this->files[$key]['error'] == 4) {
386 continue;
387 }
c9b5ebf5 388 $str .= '<strong>'. get_string('uploadfilelog', 'moodle', $i+1) .' '
18b8fbfa 389 .((!empty($this->files[$key]['originalname'])) ? '('.$this->files[$key]['originalname'].')' : '')
c9b5ebf5 390 .'</strong> :'. nl2br($this->files[$key]['uploadlog']) .'<br />';
18b8fbfa 391 }
392 if ($return) {
393 return $str;
394 }
395 echo $str;
396 }
397
398 /**
399 * If we're only handling one file (if inputname was given in the constructor) this will return the (possibly changed) filename of the file.
c9b5ebf5 400 @return boolean
18b8fbfa 401 */
402 function get_new_filename() {
403 if (!empty($this->inputname) && count($this->files) == 1) {
404 return $this->files[$this->inputname]['name'];
405 }
406 return false;
407 }
408
81d425b4 409 /**
410 * If we're only handling one file (if input name was given in the constructor) this will return the full path to the saved file.
c9b5ebf5 411 * @return boolean
81d425b4 412 */
413 function get_new_filepath() {
414 if (!empty($this->inputname) && count($this->files) == 1) {
415 return $this->files[$this->inputname]['fullpath'];
416 }
417 return false;
418 }
419
18b8fbfa 420 /**
421 * If we're only handling one file (if inputname was given in the constructor) this will return the ORIGINAL filename of the file.
c9b5ebf5 422 * @return boolean
18b8fbfa 423 */
424 function get_original_filename() {
425 if (!empty($this->inputname) && count($this->files) == 1) {
426 return $this->files[$this->inputname]['originalname'];
427 }
428 return false;
429 }
96038147 430
431 /**
c9b5ebf5 432 * This function returns any errors wrapped up in red.
433 * @return string
96038147 434 */
435 function get_errors() {
430c6392 436 return '<p class="notifyproblem">'. $this->notify .'</p>';
96038147 437 }
18b8fbfa 438}
439
440/**************************************************************************************
441THESE FUNCTIONS ARE OUTSIDE THE CLASS BECAUSE THEY NEED TO BE CALLED FROM OTHER PLACES.
442FOR EXAMPLE CLAM_HANDLE_INFECTED_FILE AND CLAM_REPLACE_INFECTED_FILE USED FROM CRON
443UPLOAD_PRINT_FORM_FRAGMENT DOESN'T REALLY BELONG IN THE CLASS BUT CERTAINLY IN THIS FILE
444***************************************************************************************/
445
446
447/**
c9b5ebf5 448 * This function prints out a number of upload form elements.
449 *
450 * @param int $numfiles The number of elements required (optional, defaults to 1)
451 * @param array $names Array of element names to use (optional, defaults to FILE_n)
452 * @param array $descriptions Array of strings to be printed out before each file bit.
453 * @param boolean $uselabels -Whether to output text fields for file descriptions or not (optional, defaults to false)
454 * @param array $labelnames Array of element names to use for labels (optional, defaults to LABEL_n)
455 * @param int $coursebytes $coursebytes and $maxbytes are used to calculate upload max size ( using {@link get_max_upload_file_size})
456 * @param int $modbytes $coursebytes and $maxbytes are used to calculate upload max size ( using {@link get_max_upload_file_size})
457 * @param boolean $return -Whether to return the string (defaults to false - string is echoed)
458 * @return string Form returned as string if $return is true
18b8fbfa 459 */
c9b5ebf5 460function upload_print_form_fragment($numfiles=1, $names=null, $descriptions=null, $uselabels=false, $labelnames=null, $coursebytes=0, $modbytes=0, $return=false) {
18b8fbfa 461 global $CFG;
c9b5ebf5 462 $maxbytes = get_max_upload_file_size($CFG->maxbytes, $coursebytes, $modbytes);
463 $str = '<input type="hidden" name="MAX_FILE_SIZE" value="'. $maxbytes .'" />'."\n";
18b8fbfa 464 for ($i = 0; $i < $numfiles; $i++) {
465 if (is_array($descriptions) && !empty($descriptions[$i])) {
c9b5ebf5 466 $str .= '<strong>'. $descriptions[$i] .'</strong><br />';
18b8fbfa 467 }
09e8a2f8 468 $name = ((is_array($names) && !empty($names[$i])) ? $names[$i] : 'FILE_'.$i);
c9b5ebf5 469 $str .= '<input type="file" size="50" name="'. $name .'" alt="'. $name .'" /><br />'."\n";
18b8fbfa 470 if ($uselabels) {
09e8a2f8 471 $lname = ((is_array($labelnames) && !empty($labelnames[$i])) ? $labelnames[$i] : 'LABEL_'.$i);
c9b5ebf5 472 $str .= get_string('uploadlabel').' <input type="text" size="50" name="'. $lname .'" alt="'. $lname
18b8fbfa 473 .'" /><br /><br />'."\n";
474 }
475 }
476 if ($return) {
477 return $str;
478 }
479 else {
480 echo $str;
481 }
482}
483
484
485/**
486 * Deals with an infected file - either moves it to a quarantinedir
487 * (specified in CFG->quarantinedir) or deletes it.
c9b5ebf5 488 *
18b8fbfa 489 * If moving it fails, it deletes it.
c9b5ebf5 490 *
491 *@uses $CFG
492 * @uses $USER
493 * @param string $file Full path to the file
494 * @param int $userid If not used, defaults to $USER->id (there in case called from cron)
495 * @param boolean $basiconly Admin level reporting or user level reporting.
496 * @return string Details of what the function did.
18b8fbfa 497 */
c9b5ebf5 498function clam_handle_infected_file($file, $userid=0, $basiconly=false) {
18b8fbfa 499
c9b5ebf5 500 global $CFG, $USER;
18b8fbfa 501 if ($USER && !$userid) {
502 $userid = $USER->id;
503 }
504 $delete = true;
505 if (file_exists($CFG->quarantinedir) && is_dir($CFG->quarantinedir) && is_writable($CFG->quarantinedir)) {
506 $now = date('YmdHis');
c9b5ebf5 507 if (rename($file, $CFG->quarantinedir .'/'. $now .'-user-'. $userid .'-infected')) {
18b8fbfa 508 $delete = false;
c9b5ebf5 509 clam_log_infected($file, $CFG->quarantinedir.'/'. $now .'-user-'. $userid .'-infected', $userid);
18b8fbfa 510 if ($basiconly) {
c9b5ebf5 511 $notice .= "\n". get_string('clammovedfilebasic');
18b8fbfa 512 }
513 else {
c9b5ebf5 514 $notice .= "\n". get_string('clammovedfile', 'moodle', $CFG->quarantinedir.'/'. $now .'-user-'. $userid .'-infected');
18b8fbfa 515 }
516 }
517 else {
518 if ($basiconly) {
c9b5ebf5 519 $notice .= "\n". get_string('clamdeletedfile');
18b8fbfa 520 }
521 else {
c9b5ebf5 522 $notice .= "\n". get_string('clamquarantinedirfailed', 'moodle', $CFG->quarantinedir);
18b8fbfa 523 }
524 }
525 }
526 else {
527 if ($basiconly) {
c9b5ebf5 528 $notice .= "\n". get_string('clamdeletedfile');
18b8fbfa 529 }
530 else {
c9b5ebf5 531 $notice .= "\n". get_string('clamquarantinedirfailed', 'moodle', $CFG->quarantinedir);
18b8fbfa 532 }
533 }
534 if ($delete) {
535 if (unlink($file)) {
c9b5ebf5 536 clam_log_infected($file, '', $userid);
537 $notice .= "\n". get_string('clamdeletedfile');
18b8fbfa 538 }
539 else {
540 if ($basiconly) {
541 // still tell the user the file has been deleted. this is only for admins.
c9b5ebf5 542 $notice .= "\n". get_string('clamdeletedfile');
18b8fbfa 543 }
544 else {
c9b5ebf5 545 $notice .= "\n". get_string('clamdeletedfilefailed');
18b8fbfa 546 }
547 }
548 }
549 return $notice;
550}
551
552/**
c9b5ebf5 553 * Replaces the given file with a string.
554 *
555 * The replacement string is used to notify that the original file had a virus
18b8fbfa 556 * This is to avoid missing files but could result in the wrong content-type.
c9b5ebf5 557 * @param string $file Full path to the file.
558 * @return boolean
18b8fbfa 559 */
560function clam_replace_infected_file($file) {
561 $newcontents = get_string('virusplaceholder');
c9b5ebf5 562 if (!$f = fopen($file, 'w')) {
18b8fbfa 563 return false;
564 }
c9b5ebf5 565 if (!fwrite($f, $newcontents)) {
18b8fbfa 566 return false;
567 }
568 return true;
569}
570
571
572/**
c9b5ebf5 573 * If $CFG->runclamonupload is set, we scan a given file. (called from {@link preprocess_files()})
574 *
18b8fbfa 575 * This function will add on a uploadlog index in $file.
c9b5ebf5 576 * @param mixed $file The file to scan from $files. or an absolute path to a file.
577 * @param course $course {@link $COURSE}
578 * @return int 1 if good, 0 if something goes wrong (opposite from actual error code from clam)
18b8fbfa 579 */
c9b5ebf5 580function clam_scan_file(&$file, $course) {
581 global $CFG, $USER;
18b8fbfa 582
583 if (is_array($file) && is_uploaded_file($file['tmp_name'])) { // it's from $_FILES
584 $appendlog = true;
585 $fullpath = $file['tmp_name'];
586 }
587 else if (file_exists($file)) { // it's a path to somewhere on the filesystem!
588 $fullpath = $file;
589 }
590 else {
591 return false; // erm, what is this supposed to be then, huh?
592 }
593
96038147 594 $CFG->pathtoclam = trim($CFG->pathtoclam);
595
18b8fbfa 596 if (!$CFG->pathtoclam || !file_exists($CFG->pathtoclam) || !is_executable($CFG->pathtoclam)) {
597 $newreturn = 1;
c9b5ebf5 598 $notice = get_string('clamlost', 'moodle', $CFG->pathtoclam);
18b8fbfa 599 if ($CFG->clamfailureonupload == 'actlikevirus') {
c9b5ebf5 600 $notice .= "\n". get_string('clamlostandactinglikevirus');
601 $notice .= "\n". clam_handle_infected_file($fullpath);
18b8fbfa 602 $newreturn = false;
603 }
604 clam_mail_admins($notice);
96038147 605 if ($appendlog) {
c9b5ebf5 606 $file['uploadlog'] .= "\n". get_string('clambroken');
96038147 607 $file['clam'] = 1;
608 }
18b8fbfa 609 return $newreturn; // return 1 if we're allowing clam failures
610 }
611
c9b5ebf5 612 $cmd = $CFG->pathtoclam .' '. $fullpath ." 2>&1";
18b8fbfa 613
614 // before we do anything we need to change perms so that clamscan can read the file (clamdscan won't work otherwise)
615 chmod($fullpath,0644);
616
c9b5ebf5 617 exec($cmd, $output, $return);
18b8fbfa 618
619
620 switch ($return) {
621 case 0: // glee! we're ok.
622 return 1; // translate clam return code into reasonable return code consistent with everything else.
623 case 1: // bad wicked evil, we have a virus.
624 if (!empty($course)) {
625 $info->course = $course->fullname;
626 }
627 else {
628 $info->course = 'No course';
629 }
92e754eb 630 $info->user = fullname($USER);
c9b5ebf5 631 $notice = get_string('virusfound', 'moodle', $info);
632 $notice .= "\n\n". implode("\n", $output);
633 $notice .= "\n\n". clam_handle_infected_file($fullpath);
18b8fbfa 634 clam_mail_admins($notice);
635 if ($appendlog) {
636 $info->filename = $file['originalname'];
c9b5ebf5 637 $file['uploadlog'] .= "\n". get_string('virusfounduser', 'moodle', $info);
18b8fbfa 638 $file['virus'] = 1;
639 }
640 return false; // in this case, 0 means bad.
641 default:
642 // error - clam failed to run or something went wrong
c9b5ebf5 643 $notice .= get_string('clamfailed', 'moodle', get_clam_error_code($return));
644 $notice .= "\n\n". implode("\n", $output);
18b8fbfa 645 $newreturn = true;
646 if ($CFG->clamfailureonupload == 'actlikevirus') {
c9b5ebf5 647 $notice .= "\n". clam_handle_infected_file($fullpath);
18b8fbfa 648 $newreturn = false;
649 }
650 clam_mail_admins($notice);
651 if ($appendlog) {
c9b5ebf5 652 $file['uploadlog'] .= "\n". get_string('clambroken');
18b8fbfa 653 $file['clam'] = 1;
654 }
655 return $newreturn; // return 1 if we're allowing failures.
656 }
657}
658
659/**
c9b5ebf5 660 * Emails admins about a clam outcome
661 *
662 * @param string $notice The body of the email to be sent.
18b8fbfa 663 */
664function clam_mail_admins($notice) {
665
666 $site = get_site();
667
c9b5ebf5 668 $subject = get_string('clamemailsubject', 'moodle', $site->fullname);
18b8fbfa 669 $admins = get_admins();
670 foreach ($admins as $admin) {
c9b5ebf5 671 email_to_user($admin, get_admin(), $subject, $notice);
18b8fbfa 672 }
673}
674
675
c9b5ebf5 676/**
677 * Returns the string equivalent of a numeric clam error code
678 *
679 * @param int $returncode The numeric error code in question.
680 * return string The definition of the error code
681 */
18b8fbfa 682function get_clam_error_code($returncode) {
683 $returncodes = array();
684 $returncodes[0] = 'No virus found.';
685 $returncodes[1] = 'Virus(es) found.';
686 $returncodes[2] = ' An error occured'; // specific to clamdscan
687 // all after here are specific to clamscan
688 $returncodes[40] = 'Unknown option passed.';
689 $returncodes[50] = 'Database initialization error.';
690 $returncodes[52] = 'Not supported file type.';
691 $returncodes[53] = 'Can\'t open directory.';
692 $returncodes[54] = 'Can\'t open file. (ofm)';
693 $returncodes[55] = 'Error reading file. (ofm)';
694 $returncodes[56] = 'Can\'t stat input file / directory.';
695 $returncodes[57] = 'Can\'t get absolute path name of current working directory.';
696 $returncodes[58] = 'I/O error, please check your filesystem.';
697 $returncodes[59] = 'Can\'t get information about current user from /etc/passwd.';
698 $returncodes[60] = 'Can\'t get information about user \'clamav\' (default name) from /etc/passwd.';
699 $returncodes[61] = 'Can\'t fork.';
700 $returncodes[63] = 'Can\'t create temporary files/directories (check permissions).';
701 $returncodes[64] = 'Can\'t write to temporary directory (please specify another one).';
702 $returncodes[70] = 'Can\'t allocate and clear memory (calloc).';
703 $returncodes[71] = 'Can\'t allocate memory (malloc).';
704 if ($returncodes[$returncode])
705 return $returncodes[$returncode];
706 return get_string('clamunknownerror');
707
708}
709
710/**
c9b5ebf5 711 * Adds a file upload to the log table so that clam can resolve the filename to the user later if necessary
712 *
713 * @uses $CFG
714 * @uses $USER
715 * @param string $newfilepath ?
716 * @param course $course {@link $COURSE}
717 * @param boolean $nourl ?
718 * @todo Finish documenting this function
18b8fbfa 719 */
c9b5ebf5 720function clam_log_upload($newfilepath, $course=null, $nourl=false) {
721 global $CFG, $USER;
18b8fbfa 722 // get rid of any double // that might have appeared
c9b5ebf5 723 $newfilepath = preg_replace('/\/\//', '/', $newfilepath);
724 if (strpos($newfilepath, $CFG->dataroot) === false) {
725 $newfilepath = $CFG->dataroot .'/'. $newfilepath;
18b8fbfa 726 }
18b8fbfa 727 $courseid = 0;
728 if ($course) {
729 $courseid = $course->id;
730 }
c9b5ebf5 731 add_to_log($courseid, 'upload', 'upload', ((!$nourl) ? substr($_SERVER['HTTP_REFERER'], 0, 100) : ''), $newfilepath);
18b8fbfa 732}
733
7604c7db 734/**
735 * This function logs to error_log and to the log table that an infected file has been found and what's happened to it.
c9b5ebf5 736 *
737 * @param string $oldfilepath Full path to the infected file before it was moved.
738 * @param string $newfilepath Full path to the infected file since it was moved to the quarantine directory (if the file was deleted, leave empty).
739 * @param int $userid The user id of the user who uploaded the file.
7604c7db 740 */
c9b5ebf5 741function clam_log_infected($oldfilepath='', $newfilepath='', $userid=0) {
7604c7db 742
c9b5ebf5 743 add_to_log(0, 'upload', 'infected', $_SERVER['HTTP_REFERER'], $oldfilepath, 0, $userid);
7604c7db 744
c9b5ebf5 745 $user = get_record('user', 'id', $userid);
7604c7db 746
747 $errorstr = 'Clam AV has found a file that is infected with a virus. It was uploaded by '
436d4c6b 748 . ((empty($user)) ? ' an unknown user ' : fullname($user))
7604c7db 749 . ((empty($oldfilepath)) ? '. The infected file was caught on upload ('.$oldfilepath.')'
c9b5ebf5 750 : '. The original file path of the infected file was '. $oldfilepath)
751 . ((empty($newfilepath)) ? '. The file has been deleted ' : '. The file has been moved to a quarantine directory and the new path is '. $newfilepath);
7604c7db 752
753 error_log($errorstr);
754}
755
756
18b8fbfa 757/**
c9b5ebf5 758 * Some of the modules allow moving attachments (glossary), in which case we need to hunt down an original log and change the path.
759 *
760 * @uses $CFG
761 * @param string $oldpath The old path to the file (should be in the log)
762 * @param string $newpath The new path to the file
763 * @param boolean $update If true this function will overwrite old record (used for forum moving etc).
18b8fbfa 764 */
c9b5ebf5 765function clam_change_log($oldpath, $newpath, $update=true) {
18b8fbfa 766 global $CFG;
8930f900 767
c9b5ebf5 768 if (!$record = get_record('log', 'info', $oldpath, 'module', 'upload')) {
8930f900 769 return false;
770 }
771 $record->info = $newpath;
772 if ($update) {
f8688e0f 773 update_record('log', $record);
8930f900 774 }
775 else {
776 unset($record->id);
f8688e0f 777 insert_record('log', $record);
8930f900 778 }
18b8fbfa 779}
9056cec0 780?>