bebf47e076e2821869a5ac31199dc648fd7d0069
[yaffs-website] / web / core / modules / file / tests / src / Functional / SaveUploadTest.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() function.
10  *
11  * @group file
12  */
13 class SaveUploadTest extends FileManagedTestBase {
14
15   use TestFileCreationTrait {
16     getTestFiles as drupalGetTestFiles;
17   }
18
19   /**
20    * Modules to enable.
21    *
22    * @var array
23    */
24   public static $modules = ['dblog'];
25
26   /**
27    * An image file path for uploading.
28    *
29    * @var \Drupal\file\FileInterface
30    */
31   protected $image;
32
33   /**
34    * A PHP file path for upload security testing.
35    */
36   protected $phpfile;
37
38   /**
39    * The largest file id when the test starts.
40    */
41   protected $maxFidBefore;
42
43   /**
44    * Extension of the image filename.
45    *
46    * @var string
47    */
48   protected $imageExtension;
49
50   protected function setUp() {
51     parent::setUp();
52     $account = $this->drupalCreateUser(['access site reports']);
53     $this->drupalLogin($account);
54
55     $image_files = $this->drupalGetTestFiles('image');
56     $this->image = File::create((array) current($image_files));
57
58     list(, $this->imageExtension) = explode('.', $this->image->getFilename());
59     $this->assertTrue(is_file($this->image->getFileUri()), "The image file we're going to upload exists.");
60
61     $this->phpfile = current($this->drupalGetTestFiles('php'));
62     $this->assertTrue(is_file($this->phpfile->uri), 'The PHP file we are going to upload exists.');
63
64     $this->maxFidBefore = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
65
66     // Upload with replace to guarantee there's something there.
67     $edit = [
68       'file_test_replace' => FILE_EXISTS_REPLACE,
69       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
70     ];
71     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
72     $this->assertResponse(200, 'Received a 200 response for posted test file.');
73     $this->assertRaw(t('You WIN!'), 'Found the success message.');
74
75     // Check that the correct hooks were called then clean out the hook
76     // counters.
77     $this->assertFileHooksCalled(['validate', 'insert']);
78     file_test_reset();
79   }
80
81   /**
82    * Test the file_save_upload() function.
83    */
84   public function testNormal() {
85     $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
86     $this->assertTrue($max_fid_after > $this->maxFidBefore, 'A new file was created.');
87     $file1 = File::load($max_fid_after);
88     $this->assertTrue($file1, 'Loaded the file.');
89     // MIME type of the uploaded image may be either image/jpeg or image/png.
90     $this->assertEqual(substr($file1->getMimeType(), 0, 5), 'image', 'A MIME type was set.');
91
92     // Reset the hook counters to get rid of the 'load' we just called.
93     file_test_reset();
94
95     // Upload a second file.
96     $image2 = current($this->drupalGetTestFiles('image'));
97     $edit = ['files[file_test_upload]' => \Drupal::service('file_system')->realpath($image2->uri)];
98     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
99     $this->assertResponse(200, 'Received a 200 response for posted test file.');
100     $this->assertRaw(t('You WIN!'));
101     $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
102
103     // Check that the correct hooks were called.
104     $this->assertFileHooksCalled(['validate', 'insert']);
105
106     $file2 = File::load($max_fid_after);
107     $this->assertTrue($file2, 'Loaded the file');
108     // MIME type of the uploaded image may be either image/jpeg or image/png.
109     $this->assertEqual(substr($file2->getMimeType(), 0, 5), 'image', 'A MIME type was set.');
110
111     // Load both files using File::loadMultiple().
112     $files = File::loadMultiple([$file1->id(), $file2->id()]);
113     $this->assertTrue(isset($files[$file1->id()]), 'File was loaded successfully');
114     $this->assertTrue(isset($files[$file2->id()]), 'File was loaded successfully');
115
116     // Upload a third file to a subdirectory.
117     $image3 = current($this->drupalGetTestFiles('image'));
118     $image3_realpath = \Drupal::service('file_system')->realpath($image3->uri);
119     $dir = $this->randomMachineName();
120     $edit = [
121       'files[file_test_upload]' => $image3_realpath,
122       'file_subdir' => $dir,
123     ];
124     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
125     $this->assertResponse(200, 'Received a 200 response for posted test file.');
126     $this->assertRaw(t('You WIN!'));
127     $this->assertTrue(is_file('temporary://' . $dir . '/' . trim(drupal_basename($image3_realpath))));
128   }
129
130   /**
131    * Test extension handling.
132    */
133   public function testHandleExtension() {
134     // The file being tested is a .gif which is in the default safe list
135     // of extensions to allow when the extension validator isn't used. This is
136     // implicitly tested at the testNormal() test. Here we tell
137     // file_save_upload() to only allow ".foo".
138     $extensions = 'foo';
139     $edit = [
140       'file_test_replace' => FILE_EXISTS_REPLACE,
141       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
142       'extensions' => $extensions,
143     ];
144
145     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
146     $this->assertResponse(200, 'Received a 200 response for posted test file.');
147     $message = t('Only files with the following extensions are allowed:') . ' <em class="placeholder">' . $extensions . '</em>';
148     $this->assertRaw($message, 'Cannot upload a disallowed extension');
149     $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
150
151     // Check that the correct hooks were called.
152     $this->assertFileHooksCalled(['validate']);
153
154     // Reset the hook counters.
155     file_test_reset();
156
157     $extensions = 'foo ' . $this->imageExtension;
158     // Now tell file_save_upload() to allow the extension of our test image.
159     $edit = [
160       'file_test_replace' => FILE_EXISTS_REPLACE,
161       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
162       'extensions' => $extensions,
163     ];
164
165     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
166     $this->assertResponse(200, 'Received a 200 response for posted test file.');
167     $this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload an allowed extension.');
168     $this->assertRaw(t('You WIN!'), 'Found the success message.');
169
170     // Check that the correct hooks were called.
171     $this->assertFileHooksCalled(['validate', 'load', 'update']);
172
173     // Reset the hook counters.
174     file_test_reset();
175
176     // Now tell file_save_upload() to allow any extension.
177     $edit = [
178       'file_test_replace' => FILE_EXISTS_REPLACE,
179       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
180       'allow_all_extensions' => TRUE,
181     ];
182     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
183     $this->assertResponse(200, 'Received a 200 response for posted test file.');
184     $this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload any extension.');
185     $this->assertRaw(t('You WIN!'), 'Found the success message.');
186
187     // Check that the correct hooks were called.
188     $this->assertFileHooksCalled(['validate', 'load', 'update']);
189   }
190
191   /**
192    * Test dangerous file handling.
193    */
194   public function testHandleDangerousFile() {
195     $config = $this->config('system.file');
196     // Allow the .php extension and make sure it gets renamed to .txt for
197     // safety. Also check to make sure its MIME type was changed.
198     $edit = [
199       'file_test_replace' => FILE_EXISTS_REPLACE,
200       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->phpfile->uri),
201       'is_image_file' => FALSE,
202       'extensions' => 'php',
203     ];
204
205     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
206     $this->assertResponse(200, 'Received a 200 response for posted test file.');
207     $message = t('For security reasons, your upload has been renamed to') . ' <em class="placeholder">' . $this->phpfile->filename . '.txt' . '</em>';
208     $this->assertRaw($message, 'Dangerous file was renamed.');
209     $this->assertRaw(t('File MIME type is text/plain.'), "Dangerous file's MIME type was changed.");
210     $this->assertRaw(t('You WIN!'), 'Found the success message.');
211
212     // Check that the correct hooks were called.
213     $this->assertFileHooksCalled(['validate', 'insert']);
214
215     // Ensure dangerous files are not renamed when insecure uploads is TRUE.
216     // Turn on insecure uploads.
217     $config->set('allow_insecure_uploads', 1)->save();
218     // Reset the hook counters.
219     file_test_reset();
220
221     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
222     $this->assertResponse(200, 'Received a 200 response for posted test file.');
223     $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
224     $this->assertRaw(t('File name is @filename', ['@filename' => $this->phpfile->filename]), 'Dangerous file was not renamed when insecure uploads is TRUE.');
225     $this->assertRaw(t('You WIN!'), 'Found the success message.');
226
227     // Check that the correct hooks were called.
228     $this->assertFileHooksCalled(['validate', 'insert']);
229
230     // Turn off insecure uploads.
231     $config->set('allow_insecure_uploads', 0)->save();
232   }
233
234   /**
235    * Test file munge handling.
236    */
237   public function testHandleFileMunge() {
238     // Ensure insecure uploads are disabled for this test.
239     $this->config('system.file')->set('allow_insecure_uploads', 0)->save();
240     $this->image = file_move($this->image, $this->image->getFileUri() . '.foo.' . $this->imageExtension);
241
242     // Reset the hook counters to get rid of the 'move' we just called.
243     file_test_reset();
244
245     $extensions = $this->imageExtension;
246     $edit = [
247       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
248       'extensions' => $extensions,
249     ];
250
251     $munged_filename = $this->image->getFilename();
252     $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
253     $munged_filename .= '_.' . $this->imageExtension;
254
255     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
256     $this->assertResponse(200, 'Received a 200 response for posted test file.');
257     $this->assertRaw(t('For security reasons, your upload has been renamed'), 'Found security message.');
258     $this->assertRaw(t('File name is @filename', ['@filename' => $munged_filename]), 'File was successfully munged.');
259     $this->assertRaw(t('You WIN!'), 'Found the success message.');
260
261     // Check that the correct hooks were called.
262     $this->assertFileHooksCalled(['validate', 'insert']);
263
264     // Ensure we don't munge files if we're allowing any extension.
265     // Reset the hook counters.
266     file_test_reset();
267
268     $edit = [
269       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
270       'allow_all_extensions' => TRUE,
271     ];
272
273     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
274     $this->assertResponse(200, 'Received a 200 response for posted test file.');
275     $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
276     $this->assertRaw(t('File name is @filename', ['@filename' => $this->image->getFilename()]), 'File was not munged when allowing any extension.');
277     $this->assertRaw(t('You WIN!'), 'Found the success message.');
278
279     // Check that the correct hooks were called.
280     $this->assertFileHooksCalled(['validate', 'insert']);
281   }
282
283   /**
284    * Test renaming when uploading over a file that already exists.
285    */
286   public function testExistingRename() {
287     $edit = [
288       'file_test_replace' => FILE_EXISTS_RENAME,
289       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
290     ];
291     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
292     $this->assertResponse(200, 'Received a 200 response for posted test file.');
293     $this->assertRaw(t('You WIN!'), 'Found the success message.');
294
295     // Check that the correct hooks were called.
296     $this->assertFileHooksCalled(['validate', 'insert']);
297   }
298
299   /**
300    * Test replacement when uploading over a file that already exists.
301    */
302   public function testExistingReplace() {
303     $edit = [
304       'file_test_replace' => FILE_EXISTS_REPLACE,
305       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
306     ];
307     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
308     $this->assertResponse(200, 'Received a 200 response for posted test file.');
309     $this->assertRaw(t('You WIN!'), 'Found the success message.');
310
311     // Check that the correct hooks were called.
312     $this->assertFileHooksCalled(['validate', 'load', 'update']);
313   }
314
315   /**
316    * Test for failure when uploading over a file that already exists.
317    */
318   public function testExistingError() {
319     $edit = [
320       'file_test_replace' => FILE_EXISTS_ERROR,
321       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
322     ];
323     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
324     $this->assertResponse(200, 'Received a 200 response for posted test file.');
325     $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
326
327     // Check that the no hooks were called while failing.
328     $this->assertFileHooksCalled([]);
329   }
330
331   /**
332    * Test for no failures when not uploading a file.
333    */
334   public function testNoUpload() {
335     $this->drupalPostForm('file-test/upload', [], t('Submit'));
336     $this->assertNoRaw(t('Epic upload FAIL!'), 'Failure message not found.');
337   }
338
339   /**
340    * Tests for log entry on failing destination.
341    */
342   public function testDrupalMovingUploadedFileError() {
343     // Create a directory and make it not writable.
344     $test_directory = 'test_drupal_move_uploaded_file_fail';
345     drupal_mkdir('temporary://' . $test_directory, 0000);
346     $this->assertTrue(is_dir('temporary://' . $test_directory));
347
348     $edit = [
349       'file_subdir' => $test_directory,
350       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
351     ];
352
353     \Drupal::state()->set('file_test.disable_error_collection', TRUE);
354     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
355     $this->assertResponse(200, 'Received a 200 response for posted test file.');
356     $this->assertRaw(t('File upload error. Could not move uploaded file.'), 'Found the failure message.');
357     $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
358
359     // Uploading failed. Now check the log.
360     $this->drupalGet('admin/reports/dblog');
361     $this->assertResponse(200);
362     $this->assertRaw(t('Upload error. Could not move uploaded file @file to destination @destination.', [
363       '@file' => $this->image->getFilename(),
364       '@destination' => 'temporary://' . $test_directory . '/' . $this->image->getFilename(),
365     ]), 'Found upload error log entry.');
366   }
367
368 }