PageRenderTime 26ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/core/modules/file/src/Tests/SaveUploadTest.php

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