Skip to content

Commit

Permalink
MDL-31112 Repository upload - check for completely null files (likely…
Browse files Browse the repository at this point in the history
… to be folders uploaded by mistake via drag and drop)
  • Loading branch information
davosmith committed Feb 14, 2012
1 parent 5fc420e commit 87ed3a5
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions repository/upload/lang/en/repository_upload.php
Expand Up @@ -34,3 +34,4 @@
$string['upload_error_no_tmp_dir'] = 'PHP is missing a temporary folder.';
$string['upload_error_cant_write'] = 'Failed to write file to disk.';
$string['upload_error_extension'] = 'A PHP extension stopped the file upload.';
$string['upload_error_invalid_file'] = 'The file \'{$a}\' has no data in it - did you try to upload a folder?';
32 changes: 32 additions & 0 deletions repository/upload/lib.php
Expand Up @@ -129,6 +129,12 @@ public function upload($saveas_filename, $maxbytes) {
}
}

// Check the file has some non-null contents - usually an indication that a user has
// tried to upload a folder by mistake
if (!$this->check_valid_contents($_FILES[$elname]['tmp_name'])) {
throw new moodle_exception('upload_error_invalid_file', 'repository_upload', '', $record->filename);
}

if ($this->mimetypes != '*') {
// check filetype
$filemimetype = mimeinfo('type', $_FILES[$elname]['name']);
Expand Down Expand Up @@ -178,6 +184,32 @@ public function upload($saveas_filename, $maxbytes) {
}
}

/**
* Checks the contents of the given file is not completely NULL - this can happen if a
* user drags & drops a folder onto a filemanager / filepicker element
* @param filepath full path (including filename) to file to check
* @return true if file has at least one non-null byte within it
*/
protected function check_valid_contents($filepath) {
$buffersize = 4096;

$fp = fopen($filepath, 'r');
if (!$fp) {
return false; // Cannot read the file - something has gone wrong
}
while (!feof($fp)) {
// Read the file 4k at a time
$data = fread($fp, $buffersize);
if (preg_match('/[^\0]+/', $data)) {
fclose($fp);
return true; // Return as soon as a non-null byte is found
}
}
// Entire file is NULL
fclose($fp);
return false;
}

/**
* Return a upload form
* @return array
Expand Down

0 comments on commit 87ed3a5

Please sign in to comment.