MDL-72254 filesapi: reject itemid=false in file_save_draft_area_files

This should never happen, and if it does, it causes many files to be deleted.
This commit is contained in:
Tim Hunt 2021-07-29 12:02:31 +01:00
parent dc437b5171
commit e756c7f73d
2 changed files with 28 additions and 0 deletions

View File

@ -1107,6 +1107,12 @@ function file_save_draft_area_files($draftitemid, $contextid, $component, $filea
return $text;
}
if ($itemid === false) {
// Catch a potentially dangerous coding error.
throw new coding_exception('file_save_draft_area_files was called with $itemid false. ' .
"This suggests a bug, because it would wipe all ($contextid, $component, $filearea) files.");
}
$usercontext = context_user::instance($USER->id);
$fs = get_file_storage();

View File

@ -828,6 +828,28 @@ class core_filelib_testcase extends advanced_testcase {
$this->assertEquals($inlinetext, $text);
}
/**
* Testing deleting file_save_draft_area_files won't accidentally wipe unintended files.
*/
public function test_file_save_draft_area_files_itemid_cannot_be_false() {
global $USER, $DB;
$this->resetAfterTest();
$generator = $this->getDataGenerator();
$user = $generator->create_user();
$usercontext = context_user::instance($user->id);
$USER = $DB->get_record('user', ['id' => $user->id]);
$draftitemid = 0;
file_prepare_draft_area($draftitemid, $usercontext->id, 'user', 'private', 0);
// Call file_save_draft_area_files with itemid false - which could only happen due to a bug.
// This should throw an exception.
$this->expectExceptionMessage('file_save_draft_area_files was called with $itemid false. ' .
'This suggests a bug, because it would wipe all (' . $usercontext->id . ', user, private) files.');
file_save_draft_area_files($draftitemid, $usercontext->id, 'user', 'private', false);
}
/**
* Tests the strip_double_headers function in the curl class.
*/