3 namespace Drupal\file\Tests;
5 use Drupal\file\Entity\File;
8 * Tests the file_save_upload() function.
12 class SaveUploadTest extends FileManagedTestBase {
18 public static $modules = ['dblog'];
21 * An image file path for uploading.
23 * @var \Drupal\file\FileInterface
28 * A PHP file path for upload security testing.
33 * The largest file id when the test starts.
35 protected $maxFidBefore;
38 * Extension of the image filename.
42 protected $imageExtension;
44 protected function setUp() {
46 $account = $this->drupalCreateUser(['access site reports']);
47 $this->drupalLogin($account);
49 $image_files = $this->drupalGetTestFiles('image');
50 $this->image = File::create((array) current($image_files));
52 list(, $this->imageExtension) = explode('.', $this->image->getFilename());
53 $this->assertTrue(is_file($this->image->getFileUri()), "The image file we're going to upload exists.");
55 $this->phpfile = current($this->drupalGetTestFiles('php'));
56 $this->assertTrue(is_file($this->phpfile->uri), 'The PHP file we are going to upload exists.');
58 $this->maxFidBefore = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
60 // Upload with replace to guarantee there's something there.
62 'file_test_replace' => FILE_EXISTS_REPLACE,
63 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
65 $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
66 $this->assertResponse(200, 'Received a 200 response for posted test file.');
67 $this->assertRaw(t('You WIN!'), 'Found the success message.');
69 // Check that the correct hooks were called then clean out the hook
71 $this->assertFileHooksCalled(['validate', 'insert']);
76 * Test the file_save_upload() function.
78 public function testNormal() {
79 $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
80 $this->assertTrue($max_fid_after > $this->maxFidBefore, 'A new file was created.');
81 $file1 = File::load($max_fid_after);
82 $this->assertTrue($file1, 'Loaded the file.');
83 // MIME type of the uploaded image may be either image/jpeg or image/png.
84 $this->assertEqual(substr($file1->getMimeType(), 0, 5), 'image', 'A MIME type was set.');
86 // Reset the hook counters to get rid of the 'load' we just called.
89 // Upload a second file.
90 $image2 = current($this->drupalGetTestFiles('image'));
91 $edit = ['files[file_test_upload]' => \Drupal::service('file_system')->realpath($image2->uri)];
92 $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
93 $this->assertResponse(200, 'Received a 200 response for posted test file.');
94 $this->assertRaw(t('You WIN!'));
95 $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
97 // Check that the correct hooks were called.
98 $this->assertFileHooksCalled(['validate', 'insert']);
100 $file2 = File::load($max_fid_after);
101 $this->assertTrue($file2, 'Loaded the file');
102 // MIME type of the uploaded image may be either image/jpeg or image/png.
103 $this->assertEqual(substr($file2->getMimeType(), 0, 5), 'image', 'A MIME type was set.');
105 // Load both files using File::loadMultiple().
106 $files = File::loadMultiple([$file1->id(), $file2->id()]);
107 $this->assertTrue(isset($files[$file1->id()]), 'File was loaded successfully');
108 $this->assertTrue(isset($files[$file2->id()]), 'File was loaded successfully');
110 // Upload a third file to a subdirectory.
111 $image3 = current($this->drupalGetTestFiles('image'));
112 $image3_realpath = \Drupal::service('file_system')->realpath($image3->uri);
113 $dir = $this->randomMachineName();
115 'files[file_test_upload]' => $image3_realpath,
116 'file_subdir' => $dir,
118 $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
119 $this->assertResponse(200, 'Received a 200 response for posted test file.');
120 $this->assertRaw(t('You WIN!'));
121 $this->assertTrue(is_file('temporary://' . $dir . '/' . trim(drupal_basename($image3_realpath))));
125 * Test extension handling.
127 public function testHandleExtension() {
128 // The file being tested is a .gif which is in the default safe list
129 // of extensions to allow when the extension validator isn't used. This is
130 // implicitly tested at the testNormal() test. Here we tell
131 // file_save_upload() to only allow ".foo".
134 'file_test_replace' => FILE_EXISTS_REPLACE,
135 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
136 'extensions' => $extensions,
139 $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
140 $this->assertResponse(200, 'Received a 200 response for posted test file.');
141 $message = t('Only files with the following extensions are allowed:') . ' <em class="placeholder">' . $extensions . '</em>';
142 $this->assertRaw($message, 'Cannot upload a disallowed extension');
143 $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
145 // Check that the correct hooks were called.
146 $this->assertFileHooksCalled(['validate']);
148 // Reset the hook counters.
151 $extensions = 'foo ' . $this->imageExtension;
152 // Now tell file_save_upload() to allow the extension of our test image.
154 'file_test_replace' => FILE_EXISTS_REPLACE,
155 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
156 'extensions' => $extensions,
159 $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
160 $this->assertResponse(200, 'Received a 200 response for posted test file.');
161 $this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload an allowed extension.');
162 $this->assertRaw(t('You WIN!'), 'Found the success message.');
164 // Check that the correct hooks were called.
165 $this->assertFileHooksCalled(['validate', 'load', 'update']);
167 // Reset the hook counters.
170 // Now tell file_save_upload() to allow any extension.
172 'file_test_replace' => FILE_EXISTS_REPLACE,
173 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
174 'allow_all_extensions' => TRUE,
176 $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
177 $this->assertResponse(200, 'Received a 200 response for posted test file.');
178 $this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload any extension.');
179 $this->assertRaw(t('You WIN!'), 'Found the success message.');
181 // Check that the correct hooks were called.
182 $this->assertFileHooksCalled(['validate', 'load', 'update']);
186 * Test dangerous file handling.
188 public function testHandleDangerousFile() {
189 $config = $this->config('system.file');
190 // Allow the .php extension and make sure it gets renamed to .txt for
191 // safety. Also check to make sure its MIME type was changed.
193 'file_test_replace' => FILE_EXISTS_REPLACE,
194 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->phpfile->uri),
195 'is_image_file' => FALSE,
196 'extensions' => 'php',
199 $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
200 $this->assertResponse(200, 'Received a 200 response for posted test file.');
201 $message = t('For security reasons, your upload has been renamed to') . ' <em class="placeholder">' . $this->phpfile->filename . '.txt' . '</em>';
202 $this->assertRaw($message, 'Dangerous file was renamed.');
203 $this->assertRaw(t('File MIME type is text/plain.'), "Dangerous file's MIME type was changed.");
204 $this->assertRaw(t('You WIN!'), 'Found the success message.');
206 // Check that the correct hooks were called.
207 $this->assertFileHooksCalled(['validate', 'insert']);
209 // Ensure dangerous files are not renamed when insecure uploads is TRUE.
210 // Turn on insecure uploads.
211 $config->set('allow_insecure_uploads', 1)->save();
212 // Reset the hook counters.
215 $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
216 $this->assertResponse(200, 'Received a 200 response for posted test file.');
217 $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
218 $this->assertRaw(t('File name is @filename', ['@filename' => $this->phpfile->filename]), 'Dangerous file was not renamed when insecure uploads is TRUE.');
219 $this->assertRaw(t('You WIN!'), 'Found the success message.');
221 // Check that the correct hooks were called.
222 $this->assertFileHooksCalled(['validate', 'insert']);
224 // Turn off insecure uploads.
225 $config->set('allow_insecure_uploads', 0)->save();
229 * Test file munge handling.
231 public function testHandleFileMunge() {
232 // Ensure insecure uploads are disabled for this test.
233 $this->config('system.file')->set('allow_insecure_uploads', 0)->save();
234 $this->image = file_move($this->image, $this->image->getFileUri() . '.foo.' . $this->imageExtension);
236 // Reset the hook counters to get rid of the 'move' we just called.
239 $extensions = $this->imageExtension;
241 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
242 'extensions' => $extensions,
245 $munged_filename = $this->image->getFilename();
246 $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
247 $munged_filename .= '_.' . $this->imageExtension;
249 $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
250 $this->assertResponse(200, 'Received a 200 response for posted test file.');
251 $this->assertRaw(t('For security reasons, your upload has been renamed'), 'Found security message.');
252 $this->assertRaw(t('File name is @filename', ['@filename' => $munged_filename]), 'File was successfully munged.');
253 $this->assertRaw(t('You WIN!'), 'Found the success message.');
255 // Check that the correct hooks were called.
256 $this->assertFileHooksCalled(['validate', 'insert']);
258 // Ensure we don't munge files if we're allowing any extension.
259 // Reset the hook counters.
263 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
264 'allow_all_extensions' => TRUE,
267 $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
268 $this->assertResponse(200, 'Received a 200 response for posted test file.');
269 $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
270 $this->assertRaw(t('File name is @filename', ['@filename' => $this->image->getFilename()]), 'File was not munged when allowing any extension.');
271 $this->assertRaw(t('You WIN!'), 'Found the success message.');
273 // Check that the correct hooks were called.
274 $this->assertFileHooksCalled(['validate', 'insert']);
278 * Test renaming when uploading over a file that already exists.
280 public function testExistingRename() {
282 'file_test_replace' => FILE_EXISTS_RENAME,
283 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri())
285 $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
286 $this->assertResponse(200, 'Received a 200 response for posted test file.');
287 $this->assertRaw(t('You WIN!'), 'Found the success message.');
289 // Check that the correct hooks were called.
290 $this->assertFileHooksCalled(['validate', 'insert']);
294 * Test replacement when uploading over a file that already exists.
296 public function testExistingReplace() {
298 'file_test_replace' => FILE_EXISTS_REPLACE,
299 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri())
301 $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
302 $this->assertResponse(200, 'Received a 200 response for posted test file.');
303 $this->assertRaw(t('You WIN!'), 'Found the success message.');
305 // Check that the correct hooks were called.
306 $this->assertFileHooksCalled(['validate', 'load', 'update']);
310 * Test for failure when uploading over a file that already exists.
312 public function testExistingError() {
314 'file_test_replace' => FILE_EXISTS_ERROR,
315 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri())
317 $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
318 $this->assertResponse(200, 'Received a 200 response for posted test file.');
319 $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
321 // Check that the no hooks were called while failing.
322 $this->assertFileHooksCalled([]);
326 * Test for no failures when not uploading a file.
328 public function testNoUpload() {
329 $this->drupalPostForm('file-test/upload', [], t('Submit'));
330 $this->assertNoRaw(t('Epic upload FAIL!'), 'Failure message not found.');
334 * Tests for log entry on failing destination.
336 public function testDrupalMovingUploadedFileError() {
337 // Create a directory and make it not writable.
338 $test_directory = 'test_drupal_move_uploaded_file_fail';
339 drupal_mkdir('temporary://' . $test_directory, 0000);
340 $this->assertTrue(is_dir('temporary://' . $test_directory));
343 'file_subdir' => $test_directory,
344 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri())
347 \Drupal::state()->set('file_test.disable_error_collection', TRUE);
348 $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
349 $this->assertResponse(200, 'Received a 200 response for posted test file.');
350 $this->assertRaw(t('File upload error. Could not move uploaded file.'), 'Found the failure message.');
351 $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
353 // Uploading failed. Now check the log.
354 $this->drupalGet('admin/reports/dblog');
355 $this->assertResponse(200);
356 $this->assertRaw(t('Upload error. Could not move uploaded file @file to destination @destination.', [
357 '@file' => $this->image->getFilename(),
358 '@destination' => 'temporary://' . $test_directory . '/' . $this->image->getFilename()
359 ]), 'Found upload error log entry.');