3 namespace Drupal\Tests\file\Functional;
5 use Drupal\file\Entity\File;
6 use Drupal\Tests\TestFileCreationTrait;
9 * Tests the file_save_upload() function.
13 class SaveUploadTest extends FileManagedTestBase {
15 use TestFileCreationTrait {
16 getTestFiles as drupalGetTestFiles;
24 public static $modules = ['dblog'];
27 * An image file path for uploading.
29 * @var \Drupal\file\FileInterface
34 * A PHP file path for upload security testing.
39 * The largest file id when the test starts.
41 protected $maxFidBefore;
44 * Extension of the image filename.
48 protected $imageExtension;
50 protected function setUp() {
52 $account = $this->drupalCreateUser(['access site reports']);
53 $this->drupalLogin($account);
55 $image_files = $this->drupalGetTestFiles('image');
56 $this->image = File::create((array) current($image_files));
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.");
61 $this->phpfile = current($this->drupalGetTestFiles('php'));
62 $this->assertTrue(is_file($this->phpfile->uri), 'The PHP file we are going to upload exists.');
64 $this->maxFidBefore = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
66 // Upload with replace to guarantee there's something there.
68 'file_test_replace' => FILE_EXISTS_REPLACE,
69 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
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.');
75 // Check that the correct hooks were called then clean out the hook
77 $this->assertFileHooksCalled(['validate', 'insert']);
82 * Test the file_save_upload() function.
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.');
92 // Reset the hook counters to get rid of the 'load' we just called.
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();
103 // Check that the correct hooks were called.
104 $this->assertFileHooksCalled(['validate', 'insert']);
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.');
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');
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();
121 'files[file_test_upload]' => $image3_realpath,
122 'file_subdir' => $dir,
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))));
131 * Test extension handling.
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".
140 'file_test_replace' => FILE_EXISTS_REPLACE,
141 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
142 'extensions' => $extensions,
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.');
151 // Check that the correct hooks were called.
152 $this->assertFileHooksCalled(['validate']);
154 // Reset the hook counters.
157 $extensions = 'foo ' . $this->imageExtension;
158 // Now tell file_save_upload() to allow the extension of our test image.
160 'file_test_replace' => FILE_EXISTS_REPLACE,
161 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
162 'extensions' => $extensions,
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.');
170 // Check that the correct hooks were called.
171 $this->assertFileHooksCalled(['validate', 'load', 'update']);
173 // Reset the hook counters.
176 // Now tell file_save_upload() to allow any extension.
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,
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.');
187 // Check that the correct hooks were called.
188 $this->assertFileHooksCalled(['validate', 'load', 'update']);
192 * Test dangerous file handling.
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.
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',
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.');
212 // Check that the correct hooks were called.
213 $this->assertFileHooksCalled(['validate', 'insert']);
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.
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.');
227 // Check that the correct hooks were called.
228 $this->assertFileHooksCalled(['validate', 'insert']);
230 // Turn off insecure uploads.
231 $config->set('allow_insecure_uploads', 0)->save();
235 * Test file munge handling.
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);
242 // Reset the hook counters to get rid of the 'move' we just called.
245 $extensions = $this->imageExtension;
247 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
248 'extensions' => $extensions,
251 $munged_filename = $this->image->getFilename();
252 $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
253 $munged_filename .= '_.' . $this->imageExtension;
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.');
261 // Check that the correct hooks were called.
262 $this->assertFileHooksCalled(['validate', 'insert']);
264 // Ensure we don't munge files if we're allowing any extension.
265 // Reset the hook counters.
269 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
270 'allow_all_extensions' => TRUE,
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.');
279 // Check that the correct hooks were called.
280 $this->assertFileHooksCalled(['validate', 'insert']);
284 * Test renaming when uploading over a file that already exists.
286 public function testExistingRename() {
288 'file_test_replace' => FILE_EXISTS_RENAME,
289 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
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.');
295 // Check that the correct hooks were called.
296 $this->assertFileHooksCalled(['validate', 'insert']);
300 * Test replacement when uploading over a file that already exists.
302 public function testExistingReplace() {
304 'file_test_replace' => FILE_EXISTS_REPLACE,
305 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
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.');
311 // Check that the correct hooks were called.
312 $this->assertFileHooksCalled(['validate', 'load', 'update']);
316 * Test for failure when uploading over a file that already exists.
318 public function testExistingError() {
320 'file_test_replace' => FILE_EXISTS_ERROR,
321 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
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.');
327 // Check that the no hooks were called while failing.
328 $this->assertFileHooksCalled([]);
332 * Test for no failures when not uploading a file.
334 public function testNoUpload() {
335 $this->drupalPostForm('file-test/upload', [], t('Submit'));
336 $this->assertNoRaw(t('Epic upload FAIL!'), 'Failure message not found.');
340 * Tests for log entry on failing destination.
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));
349 'file_subdir' => $test_directory,
350 'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
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.');
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.');