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