a6e6f9a46a899343ea93bdebf8e94ba6d2e31e98
[yaffs-website] / web / core / modules / file / src / Tests / SaveUploadTest.php
1 <?php
2
3 namespace Drupal\file\Tests;
4
5 use Drupal\file\Entity\File;
6
7 /**
8  * Tests the file_save_upload() function.
9  *
10  * @group file
11  */
12 class SaveUploadTest extends FileManagedTestBase {
13   /**
14    * Modules to enable.
15    *
16    * @var array
17    */
18   public static $modules = ['dblog'];
19
20   /**
21    * An image file path for uploading.
22    *
23    * @var \Drupal\file\FileInterface
24    */
25   protected $image;
26
27   /**
28    * A PHP file path for upload security testing.
29    */
30   protected $phpfile;
31
32   /**
33    * The largest file id when the test starts.
34    */
35   protected $maxFidBefore;
36
37   /**
38    * Extension of the image filename.
39    *
40    * @var string
41    */
42   protected $imageExtension;
43
44   protected function setUp() {
45     parent::setUp();
46     $account = $this->drupalCreateUser(['access site reports']);
47     $this->drupalLogin($account);
48
49     $image_files = $this->drupalGetTestFiles('image');
50     $this->image = File::create((array) current($image_files));
51
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.");
54
55     $this->phpfile = current($this->drupalGetTestFiles('php'));
56     $this->assertTrue(is_file($this->phpfile->uri), 'The PHP file we are going to upload exists.');
57
58     $this->maxFidBefore = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
59
60     // Upload with replace to guarantee there's something there.
61     $edit = [
62       'file_test_replace' => FILE_EXISTS_REPLACE,
63       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
64     ];
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.');
68
69     // Check that the correct hooks were called then clean out the hook
70     // counters.
71     $this->assertFileHooksCalled(['validate', 'insert']);
72     file_test_reset();
73   }
74
75   /**
76    * Test the file_save_upload() function.
77    */
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.');
85
86     // Reset the hook counters to get rid of the 'load' we just called.
87     file_test_reset();
88
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();
96
97     // Check that the correct hooks were called.
98     $this->assertFileHooksCalled(['validate', 'insert']);
99
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.');
104
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');
109
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();
114     $edit = [
115       'files[file_test_upload]' => $image3_realpath,
116       'file_subdir' => $dir,
117     ];
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))));
122   }
123
124   /**
125    * Test extension handling.
126    */
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".
132     $extensions = 'foo';
133     $edit = [
134       'file_test_replace' => FILE_EXISTS_REPLACE,
135       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
136       'extensions' => $extensions,
137     ];
138
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.');
144
145     // Check that the correct hooks were called.
146     $this->assertFileHooksCalled(['validate']);
147
148     // Reset the hook counters.
149     file_test_reset();
150
151     $extensions = 'foo ' . $this->imageExtension;
152     // Now tell file_save_upload() to allow the extension of our test image.
153     $edit = [
154       'file_test_replace' => FILE_EXISTS_REPLACE,
155       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
156       'extensions' => $extensions,
157     ];
158
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.');
163
164     // Check that the correct hooks were called.
165     $this->assertFileHooksCalled(['validate', 'load', 'update']);
166
167     // Reset the hook counters.
168     file_test_reset();
169
170     // Now tell file_save_upload() to allow any extension.
171     $edit = [
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,
175     ];
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.');
180
181     // Check that the correct hooks were called.
182     $this->assertFileHooksCalled(['validate', 'load', 'update']);
183   }
184
185   /**
186    * Test dangerous file handling.
187    */
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.
192     $edit = [
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',
197     ];
198
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.');
205
206     // Check that the correct hooks were called.
207     $this->assertFileHooksCalled(['validate', 'insert']);
208
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.
213     file_test_reset();
214
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.');
220
221     // Check that the correct hooks were called.
222     $this->assertFileHooksCalled(['validate', 'insert']);
223
224     // Turn off insecure uploads.
225     $config->set('allow_insecure_uploads', 0)->save();
226   }
227
228   /**
229    * Test file munge handling.
230    */
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);
235
236     // Reset the hook counters to get rid of the 'move' we just called.
237     file_test_reset();
238
239     $extensions = $this->imageExtension;
240     $edit = [
241       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
242       'extensions' => $extensions,
243     ];
244
245     $munged_filename = $this->image->getFilename();
246     $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
247     $munged_filename .= '_.' . $this->imageExtension;
248
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.');
254
255     // Check that the correct hooks were called.
256     $this->assertFileHooksCalled(['validate', 'insert']);
257
258     // Ensure we don't munge files if we're allowing any extension.
259     // Reset the hook counters.
260     file_test_reset();
261
262     $edit = [
263       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
264       'allow_all_extensions' => TRUE,
265     ];
266
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.');
272
273     // Check that the correct hooks were called.
274     $this->assertFileHooksCalled(['validate', 'insert']);
275   }
276
277   /**
278    * Test renaming when uploading over a file that already exists.
279    */
280   public function testExistingRename() {
281     $edit = [
282       'file_test_replace' => FILE_EXISTS_RENAME,
283       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri())
284     ];
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.');
288
289     // Check that the correct hooks were called.
290     $this->assertFileHooksCalled(['validate', 'insert']);
291   }
292
293   /**
294    * Test replacement when uploading over a file that already exists.
295    */
296   public function testExistingReplace() {
297     $edit = [
298       'file_test_replace' => FILE_EXISTS_REPLACE,
299       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri())
300     ];
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.');
304
305     // Check that the correct hooks were called.
306     $this->assertFileHooksCalled(['validate', 'load', 'update']);
307   }
308
309   /**
310    * Test for failure when uploading over a file that already exists.
311    */
312   public function testExistingError() {
313     $edit = [
314       'file_test_replace' => FILE_EXISTS_ERROR,
315       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri())
316     ];
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.');
320
321     // Check that the no hooks were called while failing.
322     $this->assertFileHooksCalled([]);
323   }
324
325   /**
326    * Test for no failures when not uploading a file.
327    */
328   public function testNoUpload() {
329     $this->drupalPostForm('file-test/upload', [], t('Submit'));
330     $this->assertNoRaw(t('Epic upload FAIL!'), 'Failure message not found.');
331   }
332
333   /**
334    * Tests for log entry on failing destination.
335    */
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));
341
342     $edit = [
343       'file_subdir' => $test_directory,
344       'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri())
345     ];
346
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.');
352
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.');
360   }
361
362 }