3 namespace Drupal\Tests\file\Functional;
5 use Drupal\file\Entity\File;
6 use Drupal\Tests\TestFileCreationTrait;
9 * Tests the _file_save_upload_from_form() function.
13 * @see _file_save_upload_from_form()
15 class SaveUploadFormTest extends FileManagedTestBase {
17 use TestFileCreationTrait {
18 getTestFiles as drupalGetTestFiles;
26 public static $modules = ['dblog'];
29 * An image file path for uploading.
31 * @var \Drupal\file\FileInterface
36 * A PHP file path for upload security testing.
41 * The largest file id when the test starts.
43 protected $maxFidBefore;
46 * Extension of the image filename.
50 protected $imageExtension;
55 protected function setUp() {
57 $account = $this->drupalCreateUser(['access site reports']);
58 $this->drupalLogin($account);
60 $image_files = $this->drupalGetTestFiles('image');
61 $this->image = File::create((array) current($image_files));
63 list(, $this->imageExtension) = explode('.', $this->image->getFilename());
64 $this->assertTrue(is_file($this->image->getFileUri()), "The image file we're going to upload exists.");
66 $this->phpfile = current($this->drupalGetTestFiles('php'));
67 $this->assertTrue(is_file($this->phpfile->uri), 'The PHP file we are going to upload exists.');
69 $this->maxFidBefore = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
71 /** @var \Drupal\Core\File\FileSystemInterface $file_system */
72 $file_system = \Drupal::service('file_system');
73 // Upload with replace to guarantee there's something there.
75 'file_test_replace' => FILE_EXISTS_REPLACE,
76 'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
78 $this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
79 $this->assertResponse(200, 'Received a 200 response for posted test file.');
80 $this->assertRaw(t('You WIN!'), 'Found the success message.');
82 // Check that the correct hooks were called then clean out the hook
84 $this->assertFileHooksCalled(['validate', 'insert']);
89 * Tests the _file_save_upload_from_form() function.
91 public function testNormal() {
92 $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
93 $this->assertTrue($max_fid_after > $this->maxFidBefore, 'A new file was created.');
94 $file1 = File::load($max_fid_after);
95 $this->assertTrue($file1, 'Loaded the file.');
96 // MIME type of the uploaded image may be either image/jpeg or image/png.
97 $this->assertEqual(substr($file1->getMimeType(), 0, 5), 'image', 'A MIME type was set.');
99 // Reset the hook counters to get rid of the 'load' we just called.
102 // Upload a second file.
103 $image2 = current($this->drupalGetTestFiles('image'));
104 /** @var \Drupal\Core\File\FileSystemInterface $file_system */
105 $file_system = \Drupal::service('file_system');
106 $edit = ['files[file_test_upload][]' => $file_system->realpath($image2->uri)];
107 $this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
108 $this->assertResponse(200, 'Received a 200 response for posted test file.');
109 $this->assertRaw(t('You WIN!'));
110 $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
112 // Check that the correct hooks were called.
113 $this->assertFileHooksCalled(['validate', 'insert']);
115 $file2 = File::load($max_fid_after);
116 $this->assertTrue($file2, 'Loaded the file');
117 // MIME type of the uploaded image may be either image/jpeg or image/png.
118 $this->assertEqual(substr($file2->getMimeType(), 0, 5), 'image', 'A MIME type was set.');
120 // Load both files using File::loadMultiple().
121 $files = File::loadMultiple([$file1->id(), $file2->id()]);
122 $this->assertTrue(isset($files[$file1->id()]), 'File was loaded successfully');
123 $this->assertTrue(isset($files[$file2->id()]), 'File was loaded successfully');
125 // Upload a third file to a subdirectory.
126 $image3 = current($this->drupalGetTestFiles('image'));
127 $image3_realpath = $file_system->realpath($image3->uri);
128 $dir = $this->randomMachineName();
130 'files[file_test_upload][]' => $image3_realpath,
131 'file_subdir' => $dir,
133 $this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
134 $this->assertResponse(200, 'Received a 200 response for posted test file.');
135 $this->assertRaw(t('You WIN!'));
136 $this->assertTrue(is_file('temporary://' . $dir . '/' . trim(drupal_basename($image3_realpath))));
140 * Tests extension handling.
142 public function testHandleExtension() {
143 /** @var \Drupal\Core\File\FileSystemInterface $file_system */
144 $file_system = \Drupal::service('file_system');
145 // The file being tested is a .gif which is in the default safe list
146 // of extensions to allow when the extension validator isn't used. This is
147 // implicitly tested at the testNormal() test. Here we tell
148 // _file_save_upload_from_form() to only allow ".foo".
151 'file_test_replace' => FILE_EXISTS_REPLACE,
152 'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
153 'extensions' => $extensions,
156 $this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
157 $this->assertResponse(200, 'Received a 200 response for posted test file.');
158 $message = t('Only files with the following extensions are allowed:') . ' <em class="placeholder">' . $extensions . '</em>';
159 $this->assertRaw($message, 'Cannot upload a disallowed extension');
160 $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
162 // Check that the correct hooks were called.
163 $this->assertFileHooksCalled(['validate']);
165 // Reset the hook counters.
168 $extensions = 'foo ' . $this->imageExtension;
169 // Now tell _file_save_upload_from_form() to allow the extension of our test image.
171 'file_test_replace' => FILE_EXISTS_REPLACE,
172 'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
173 'extensions' => $extensions,
176 $this->drupalPostForm('file-test/save_upload_from_form_test', $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 an allowed 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']);
184 // Reset the hook counters.
187 // Now tell _file_save_upload_from_form() to allow any extension.
189 'file_test_replace' => FILE_EXISTS_REPLACE,
190 'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
191 'allow_all_extensions' => TRUE,
193 $this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
194 $this->assertResponse(200, 'Received a 200 response for posted test file.');
195 $this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload any extension.');
196 $this->assertRaw(t('You WIN!'), 'Found the success message.');
198 // Check that the correct hooks were called.
199 $this->assertFileHooksCalled(['validate', 'load', 'update']);
203 * Tests dangerous file handling.
205 public function testHandleDangerousFile() {
206 $config = $this->config('system.file');
207 /** @var \Drupal\Core\File\FileSystemInterface $file_system */
208 $file_system = \Drupal::service('file_system');
209 // Allow the .php extension and make sure it gets renamed to .txt for
210 // safety. Also check to make sure its MIME type was changed.
212 'file_test_replace' => FILE_EXISTS_REPLACE,
213 'files[file_test_upload][]' => $file_system->realpath($this->phpfile->uri),
214 'is_image_file' => FALSE,
215 'extensions' => 'php',
218 $this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
219 $this->assertResponse(200, 'Received a 200 response for posted test file.');
220 $message = t('For security reasons, your upload has been renamed to') . ' <em class="placeholder">' . $this->phpfile->filename . '.txt' . '</em>';
221 $this->assertRaw($message, 'Dangerous file was renamed.');
222 $this->assertRaw(t('File MIME type is text/plain.'), "Dangerous file's MIME type was changed.");
223 $this->assertRaw(t('You WIN!'), 'Found the success message.');
225 // Check that the correct hooks were called.
226 $this->assertFileHooksCalled(['validate', 'insert']);
228 // Ensure dangerous files are not renamed when insecure uploads is TRUE.
229 // Turn on insecure uploads.
230 $config->set('allow_insecure_uploads', 1)->save();
231 // Reset the hook counters.
234 $this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
235 $this->assertResponse(200, 'Received a 200 response for posted test file.');
236 $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
237 $this->assertRaw(t('File name is @filename', ['@filename' => $this->phpfile->filename]), 'Dangerous file was not renamed when insecure uploads is TRUE.');
238 $this->assertRaw(t('You WIN!'), 'Found the success message.');
240 // Check that the correct hooks were called.
241 $this->assertFileHooksCalled(['validate', 'insert']);
243 // Turn off insecure uploads.
244 $config->set('allow_insecure_uploads', 0)->save();
248 * Tests file munge handling.
250 public function testHandleFileMunge() {
251 /** @var \Drupal\Core\File\FileSystemInterface $file_system */
252 $file_system = \Drupal::service('file_system');
253 // Ensure insecure uploads are disabled for this test.
254 $this->config('system.file')->set('allow_insecure_uploads', 0)->save();
255 $this->image = file_move($this->image, $this->image->getFileUri() . '.foo.' . $this->imageExtension);
257 // Reset the hook counters to get rid of the 'move' we just called.
260 $extensions = $this->imageExtension;
262 'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
263 'extensions' => $extensions,
266 $munged_filename = $this->image->getFilename();
267 $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
268 $munged_filename .= '_.' . $this->imageExtension;
270 $this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
271 $this->assertResponse(200, 'Received a 200 response for posted test file.');
272 $this->assertRaw(t('For security reasons, your upload has been renamed'), 'Found security message.');
273 $this->assertRaw(t('File name is @filename', ['@filename' => $munged_filename]), 'File was successfully munged.');
274 $this->assertRaw(t('You WIN!'), 'Found the success message.');
276 // Check that the correct hooks were called.
277 $this->assertFileHooksCalled(['validate', 'insert']);
279 // Ensure we don't munge files if we're allowing any extension.
280 // Reset the hook counters.
284 'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
285 'allow_all_extensions' => TRUE,
288 $this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
289 $this->assertResponse(200, 'Received a 200 response for posted test file.');
290 $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
291 $this->assertRaw(t('File name is @filename', ['@filename' => $this->image->getFilename()]), 'File was not munged when allowing any extension.');
292 $this->assertRaw(t('You WIN!'), 'Found the success message.');
294 // Check that the correct hooks were called.
295 $this->assertFileHooksCalled(['validate', 'insert']);
299 * Tests renaming when uploading over a file that already exists.
301 public function testExistingRename() {
302 /** @var \Drupal\Core\File\FileSystemInterface $file_system */
303 $file_system = \Drupal::service('file_system');
305 'file_test_replace' => FILE_EXISTS_RENAME,
306 'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
308 $this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
309 $this->assertResponse(200, 'Received a 200 response for posted test file.');
310 $this->assertRaw(t('You WIN!'), 'Found the success message.');
312 // Check that the correct hooks were called.
313 $this->assertFileHooksCalled(['validate', 'insert']);
317 * Tests replacement when uploading over a file that already exists.
319 public function testExistingReplace() {
320 /** @var \Drupal\Core\File\FileSystemInterface $file_system */
321 $file_system = \Drupal::service('file_system');
323 'file_test_replace' => FILE_EXISTS_REPLACE,
324 'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
326 $this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
327 $this->assertResponse(200, 'Received a 200 response for posted test file.');
328 $this->assertRaw(t('You WIN!'), 'Found the success message.');
330 // Check that the correct hooks were called.
331 $this->assertFileHooksCalled(['validate', 'load', 'update']);
335 * Tests for failure when uploading over a file that already exists.
337 public function testExistingError() {
338 /** @var \Drupal\Core\File\FileSystemInterface $file_system */
339 $file_system = \Drupal::service('file_system');
341 'file_test_replace' => FILE_EXISTS_ERROR,
342 'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
344 $this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
345 $this->assertResponse(200, 'Received a 200 response for posted test file.');
346 $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
348 // Check that the no hooks were called while failing.
349 $this->assertFileHooksCalled([]);
353 * Tests for no failures when not uploading a file.
355 public function testNoUpload() {
356 $this->drupalPostForm('file-test/save_upload_from_form_test', [], t('Submit'));
357 $this->assertNoRaw(t('Epic upload FAIL!'), 'Failure message not found.');
361 * Tests for log entry on failing destination.
363 public function testDrupalMovingUploadedFileError() {
364 // Create a directory and make it not writable.
365 $test_directory = 'test_drupal_move_uploaded_file_fail';
366 drupal_mkdir('temporary://' . $test_directory, 0000);
367 $this->assertTrue(is_dir('temporary://' . $test_directory));
369 /** @var \Drupal\Core\File\FileSystemInterface $file_system */
370 $file_system = \Drupal::service('file_system');
372 'file_subdir' => $test_directory,
373 'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
376 \Drupal::state()->set('file_test.disable_error_collection', TRUE);
377 $this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
378 $this->assertResponse(200, 'Received a 200 response for posted test file.');
379 $this->assertRaw(t('File upload error. Could not move uploaded file.'), 'Found the failure message.');
380 $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
382 // Uploading failed. Now check the log.
383 $this->drupalGet('admin/reports/dblog');
384 $this->assertResponse(200);
385 $this->assertRaw(t('Upload error. Could not move uploaded file @file to destination @destination.', [
386 '@file' => $this->image->getFilename(),
387 '@destination' => 'temporary://' . $test_directory . '/' . $this->image->getFilename(),
388 ]), 'Found upload error log entry.');
392 * Tests that form validation does not change error messages.
394 public function testErrorMessagesAreNotChanged() {
395 $error = 'An error message set before _file_save_upload_from_form()';
397 /** @var \Drupal\Core\File\FileSystemInterface $file_system */
398 $file_system = \Drupal::service('file_system');
400 'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
401 'error_message' => $error,
403 $this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
404 $this->assertResponse(200, 'Received a 200 response for posted test file.');
405 $this->assertRaw(t('You WIN!'), 'Found the success message.');
407 // Ensure the expected error message is present and the counts before and
408 // after calling _file_save_upload_from_form() are correct.
409 $this->assertText($error);
410 $this->assertRaw('Number of error messages before _file_save_upload_from_form(): 1');
411 $this->assertRaw('Number of error messages after _file_save_upload_from_form(): 1');
413 // Test that error messages are preserved when an error occurs.
415 'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
416 'error_message' => $error,
417 'extensions' => 'foo',
419 $this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
420 $this->assertResponse(200, 'Received a 200 response for posted test file.');
421 $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
423 // Ensure the expected error message is present and the counts before and
424 // after calling _file_save_upload_from_form() are correct.
425 $this->assertText($error);
426 $this->assertRaw('Number of error messages before _file_save_upload_from_form(): 1');
427 $this->assertRaw('Number of error messages after _file_save_upload_from_form(): 1');
429 // Test a successful upload with no messages.
431 'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
433 $this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
434 $this->assertResponse(200, 'Received a 200 response for posted test file.');
435 $this->assertRaw(t('You WIN!'), 'Found the success message.');
437 // Ensure the error message is not present and the counts before and after
438 // calling _file_save_upload_from_form() are correct.
439 $this->assertNoText($error);
440 $this->assertRaw('Number of error messages before _file_save_upload_from_form(): 0');
441 $this->assertRaw('Number of error messages after _file_save_upload_from_form(): 0');
445 * Tests that multiple validation errors are combined in one message.
447 public function testCombinedErrorMessages() {
448 $textfile = current($this->drupalGetTestFiles('text'));
449 $this->assertTrue(is_file($textfile->uri), 'The text file we are going to upload exists.');
451 /** @var \Drupal\Core\File\FileSystemInterface $file_system */
452 $file_system = \Drupal::service('file_system');
454 // Can't use drupalPostForm() for set nonexistent fields.
455 $this->drupalGet('file-test/save_upload_from_form_test');
456 $client = $this->getSession()->getDriver()->getClient();
457 $submit_xpath = $this->assertSession()->buttonExists('Submit')->getXpath();
458 $form = $client->getCrawler()->filterXPath($submit_xpath)->form();
460 'allow_all_extensions' => FALSE,
461 'is_image_file' => TRUE,
462 'extensions' => 'jpeg',
464 $edit += $form->getPhpValues();
465 $files['files']['file_test_upload'][0] = $file_system->realpath($this->phpfile->uri);
466 $files['files']['file_test_upload'][1] = $file_system->realpath($textfile->uri);
467 $client->request($form->getMethod(), $form->getUri(), $edit, $files);
469 $this->assertResponse(200, 'Received a 200 response for posted test file.');
470 $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
472 // Search for combined error message followed by a formatted list of messages.
473 $this->assertRaw(t('One or more files could not be uploaded.') . '<div class="item-list">', 'Error message contains combined list of validation errors.');
477 * Tests highlighting of file upload field when it has an error.
479 public function testUploadFieldIsHighlighted() {
480 $this->assertEqual(0, count($this->cssSelect('input[name="files[file_test_upload][]"].error')), 'Successful file upload has no error.');
482 /** @var \Drupal\Core\File\FileSystemInterface $file_system */
483 $file_system = \Drupal::service('file_system');
485 'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
486 'extensions' => 'foo',
488 $this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
489 $this->assertResponse(200, 'Received a 200 response for posted test file.');
490 $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
491 $this->assertEqual(1, count($this->cssSelect('input[name="files[file_test_upload][]"].error')), 'File upload field has error.');