e8b14e6ba1200b9446df6c8d0ba568574eb4363a
[yaffs-website] / web / core / modules / file / tests / src / Functional / SaveUploadFormTest.php
1 <?php
2
3 namespace Drupal\Tests\file\Functional;
4
5 use Drupal\file\Entity\File;
6 use Drupal\Tests\TestFileCreationTrait;
7
8 /**
9  * Tests the _file_save_upload_from_form() function.
10  *
11  * @group file
12  *
13  * @see _file_save_upload_from_form()
14  */
15 class SaveUploadFormTest extends FileManagedTestBase {
16
17   use TestFileCreationTrait {
18     getTestFiles as drupalGetTestFiles;
19   }
20
21   /**
22    * Modules to enable.
23    *
24    * @var array
25    */
26   public static $modules = ['dblog'];
27
28   /**
29    * An image file path for uploading.
30    *
31    * @var \Drupal\file\FileInterface
32    */
33   protected $image;
34
35   /**
36    * A PHP file path for upload security testing.
37    */
38   protected $phpfile;
39
40   /**
41    * The largest file id when the test starts.
42    */
43   protected $maxFidBefore;
44
45   /**
46    * Extension of the image filename.
47    *
48    * @var string
49    */
50   protected $imageExtension;
51
52   /**
53    * {@inheritdoc}
54    */
55   protected function setUp() {
56     parent::setUp();
57     $account = $this->drupalCreateUser(['access site reports']);
58     $this->drupalLogin($account);
59
60     $image_files = $this->drupalGetTestFiles('image');
61     $this->image = File::create((array) current($image_files));
62
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.");
65
66     $this->phpfile = current($this->drupalGetTestFiles('php'));
67     $this->assertTrue(is_file($this->phpfile->uri), 'The PHP file we are going to upload exists.');
68
69     $this->maxFidBefore = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
70
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.
74     $edit = [
75       'file_test_replace' => FILE_EXISTS_REPLACE,
76       'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
77     ];
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.');
81
82     // Check that the correct hooks were called then clean out the hook
83     // counters.
84     $this->assertFileHooksCalled(['validate', 'insert']);
85     file_test_reset();
86   }
87
88   /**
89    * Tests the _file_save_upload_from_form() function.
90    */
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.');
98
99     // Reset the hook counters to get rid of the 'load' we just called.
100     file_test_reset();
101
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();
111
112     // Check that the correct hooks were called.
113     $this->assertFileHooksCalled(['validate', 'insert']);
114
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.');
119
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');
124
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();
129     $edit = [
130       'files[file_test_upload][]' => $image3_realpath,
131       'file_subdir' => $dir,
132     ];
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))));
137   }
138
139   /**
140    * Tests extension handling.
141    */
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".
149     $extensions = 'foo';
150     $edit = [
151       'file_test_replace' => FILE_EXISTS_REPLACE,
152       'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
153       'extensions' => $extensions,
154     ];
155
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.');
161
162     // Check that the correct hooks were called.
163     $this->assertFileHooksCalled(['validate']);
164
165     // Reset the hook counters.
166     file_test_reset();
167
168     $extensions = 'foo ' . $this->imageExtension;
169     // Now tell _file_save_upload_from_form() to allow the extension of our test image.
170     $edit = [
171       'file_test_replace' => FILE_EXISTS_REPLACE,
172       'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
173       'extensions' => $extensions,
174     ];
175
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.');
180
181     // Check that the correct hooks were called.
182     $this->assertFileHooksCalled(['validate', 'load', 'update']);
183
184     // Reset the hook counters.
185     file_test_reset();
186
187     // Now tell _file_save_upload_from_form() to allow any extension.
188     $edit = [
189       'file_test_replace' => FILE_EXISTS_REPLACE,
190       'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
191       'allow_all_extensions' => TRUE,
192     ];
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.');
197
198     // Check that the correct hooks were called.
199     $this->assertFileHooksCalled(['validate', 'load', 'update']);
200   }
201
202   /**
203    * Tests dangerous file handling.
204    */
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.
211     $edit = [
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',
216     ];
217
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.');
224
225     // Check that the correct hooks were called.
226     $this->assertFileHooksCalled(['validate', 'insert']);
227
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.
232     file_test_reset();
233
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.');
239
240     // Check that the correct hooks were called.
241     $this->assertFileHooksCalled(['validate', 'insert']);
242
243     // Turn off insecure uploads.
244     $config->set('allow_insecure_uploads', 0)->save();
245   }
246
247   /**
248    * Tests file munge handling.
249    */
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);
256
257     // Reset the hook counters to get rid of the 'move' we just called.
258     file_test_reset();
259
260     $extensions = $this->imageExtension;
261     $edit = [
262       'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
263       'extensions' => $extensions,
264     ];
265
266     $munged_filename = $this->image->getFilename();
267     $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
268     $munged_filename .= '_.' . $this->imageExtension;
269
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.');
275
276     // Check that the correct hooks were called.
277     $this->assertFileHooksCalled(['validate', 'insert']);
278
279     // Ensure we don't munge files if we're allowing any extension.
280     // Reset the hook counters.
281     file_test_reset();
282
283     $edit = [
284       'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
285       'allow_all_extensions' => TRUE,
286     ];
287
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.');
293
294     // Check that the correct hooks were called.
295     $this->assertFileHooksCalled(['validate', 'insert']);
296   }
297
298   /**
299    * Tests renaming when uploading over a file that already exists.
300    */
301   public function testExistingRename() {
302     /** @var \Drupal\Core\File\FileSystemInterface $file_system */
303     $file_system = \Drupal::service('file_system');
304     $edit = [
305       'file_test_replace' => FILE_EXISTS_RENAME,
306       'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
307     ];
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.');
311
312     // Check that the correct hooks were called.
313     $this->assertFileHooksCalled(['validate', 'insert']);
314   }
315
316   /**
317    * Tests replacement when uploading over a file that already exists.
318    */
319   public function testExistingReplace() {
320     /** @var \Drupal\Core\File\FileSystemInterface $file_system */
321     $file_system = \Drupal::service('file_system');
322     $edit = [
323       'file_test_replace' => FILE_EXISTS_REPLACE,
324       'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
325     ];
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.');
329
330     // Check that the correct hooks were called.
331     $this->assertFileHooksCalled(['validate', 'load', 'update']);
332   }
333
334   /**
335    * Tests for failure when uploading over a file that already exists.
336    */
337   public function testExistingError() {
338     /** @var \Drupal\Core\File\FileSystemInterface $file_system */
339     $file_system = \Drupal::service('file_system');
340     $edit = [
341       'file_test_replace' => FILE_EXISTS_ERROR,
342       'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
343     ];
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.');
347
348     // Check that the no hooks were called while failing.
349     $this->assertFileHooksCalled([]);
350   }
351
352   /**
353    * Tests for no failures when not uploading a file.
354    */
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.');
358   }
359
360   /**
361    * Tests for log entry on failing destination.
362    */
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));
368
369     /** @var \Drupal\Core\File\FileSystemInterface $file_system */
370     $file_system = \Drupal::service('file_system');
371     $edit = [
372       'file_subdir' => $test_directory,
373       'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
374     ];
375
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.');
381
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.');
389   }
390
391   /**
392    * Tests that form validation does not change error messages.
393    */
394   public function testErrorMessagesAreNotChanged() {
395     $error = 'An error message set before _file_save_upload_from_form()';
396
397     /** @var \Drupal\Core\File\FileSystemInterface $file_system */
398     $file_system = \Drupal::service('file_system');
399     $edit = [
400       'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
401       'error_message' => $error,
402     ];
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.');
406
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');
412
413     // Test that error messages are preserved when an error occurs.
414     $edit = [
415       'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
416       'error_message' => $error,
417       'extensions' => 'foo',
418     ];
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.');
422
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');
428
429     // Test a successful upload with no messages.
430     $edit = [
431       'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
432     ];
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.');
436
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');
442   }
443
444   /**
445    * Tests that multiple validation errors are combined in one message.
446    */
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.');
450
451     /** @var \Drupal\Core\File\FileSystemInterface $file_system */
452     $file_system = \Drupal::service('file_system');
453
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();
459     $edit = [
460       'allow_all_extensions' => FALSE,
461       'is_image_file' => TRUE,
462       'extensions' => 'jpeg',
463     ];
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);
468
469     $this->assertResponse(200, 'Received a 200 response for posted test file.');
470     $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
471
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.');
474   }
475
476   /**
477    * Tests highlighting of file upload field when it has an error.
478    */
479   public function testUploadFieldIsHighlighted() {
480     $this->assertEqual(0, count($this->cssSelect('input[name="files[file_test_upload][]"].error')), 'Successful file upload has no error.');
481
482     /** @var \Drupal\Core\File\FileSystemInterface $file_system */
483     $file_system = \Drupal::service('file_system');
484     $edit = [
485       'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
486       'extensions' => 'foo',
487     ];
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.');
492   }
493
494 }