file.test 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  1. <?php
  2. /**
  3. * @file
  4. * Tests for file.module.
  5. */
  6. /**
  7. * Provides methods specifically for testing File module's field handling.
  8. */
  9. class FileFieldTestCase extends DrupalWebTestCase {
  10. protected $admin_user;
  11. function setUp() {
  12. // Since this is a base class for many test cases, support the same
  13. // flexibility that DrupalWebTestCase::setUp() has for the modules to be
  14. // passed in as either an array or a variable number of string arguments.
  15. $modules = func_get_args();
  16. if (isset($modules[0]) && is_array($modules[0])) {
  17. $modules = $modules[0];
  18. }
  19. $modules[] = 'file';
  20. $modules[] = 'file_module_test';
  21. parent::setUp($modules);
  22. $this->admin_user = $this->drupalCreateUser(array('access content', 'access administration pages', 'administer site configuration', 'administer users', 'administer permissions', 'administer content types', 'administer nodes', 'bypass node access'));
  23. $this->drupalLogin($this->admin_user);
  24. }
  25. /**
  26. * Retrieves a sample file of the specified type.
  27. */
  28. function getTestFile($type_name, $size = NULL) {
  29. // Get a file to upload.
  30. $file = current($this->drupalGetTestFiles($type_name, $size));
  31. // Add a filesize property to files as would be read by file_load().
  32. $file->filesize = filesize($file->uri);
  33. return $file;
  34. }
  35. /**
  36. * Retrieves the fid of the last inserted file.
  37. */
  38. function getLastFileId() {
  39. return (int) db_query('SELECT MAX(fid) FROM {file_managed}')->fetchField();
  40. }
  41. /**
  42. * Creates a new file field.
  43. *
  44. * @param $name
  45. * The name of the new field (all lowercase), exclude the "field_" prefix.
  46. * @param $type_name
  47. * The node type that this field will be added to.
  48. * @param $field_settings
  49. * A list of field settings that will be added to the defaults.
  50. * @param $instance_settings
  51. * A list of instance settings that will be added to the instance defaults.
  52. * @param $widget_settings
  53. * A list of widget settings that will be added to the widget defaults.
  54. */
  55. function createFileField($name, $type_name, $field_settings = array(), $instance_settings = array(), $widget_settings = array()) {
  56. $field = array(
  57. 'field_name' => $name,
  58. 'type' => 'file',
  59. 'settings' => array(),
  60. 'cardinality' => !empty($field_settings['cardinality']) ? $field_settings['cardinality'] : 1,
  61. );
  62. $field['settings'] = array_merge($field['settings'], $field_settings);
  63. field_create_field($field);
  64. $this->attachFileField($name, 'node', $type_name, $instance_settings, $widget_settings);
  65. }
  66. /**
  67. * Attaches a file field to an entity.
  68. *
  69. * @param $name
  70. * The name of the new field (all lowercase), exclude the "field_" prefix.
  71. * @param $entity_type
  72. * The entity type this field will be added to.
  73. * @param $bundle
  74. * The bundle this field will be added to.
  75. * @param $field_settings
  76. * A list of field settings that will be added to the defaults.
  77. * @param $instance_settings
  78. * A list of instance settings that will be added to the instance defaults.
  79. * @param $widget_settings
  80. * A list of widget settings that will be added to the widget defaults.
  81. */
  82. function attachFileField($name, $entity_type, $bundle, $instance_settings = array(), $widget_settings = array()) {
  83. $instance = array(
  84. 'field_name' => $name,
  85. 'label' => $name,
  86. 'entity_type' => $entity_type,
  87. 'bundle' => $bundle,
  88. 'required' => !empty($instance_settings['required']),
  89. 'settings' => array(),
  90. 'widget' => array(
  91. 'type' => 'file_generic',
  92. 'settings' => array(),
  93. ),
  94. );
  95. $instance['settings'] = array_merge($instance['settings'], $instance_settings);
  96. $instance['widget']['settings'] = array_merge($instance['widget']['settings'], $widget_settings);
  97. field_create_instance($instance);
  98. }
  99. /**
  100. * Updates an existing file field with new settings.
  101. */
  102. function updateFileField($name, $type_name, $instance_settings = array(), $widget_settings = array()) {
  103. $instance = field_info_instance('node', $name, $type_name);
  104. $instance['settings'] = array_merge($instance['settings'], $instance_settings);
  105. $instance['widget']['settings'] = array_merge($instance['widget']['settings'], $widget_settings);
  106. field_update_instance($instance);
  107. }
  108. /**
  109. * Uploads a file to a node.
  110. */
  111. function uploadNodeFile($file, $field_name, $nid_or_type, $new_revision = TRUE, $extras = array()) {
  112. $langcode = LANGUAGE_NONE;
  113. $edit = array(
  114. "title" => $this->randomName(),
  115. 'revision' => (string) (int) $new_revision,
  116. );
  117. if (is_numeric($nid_or_type)) {
  118. $nid = $nid_or_type;
  119. }
  120. else {
  121. // Add a new node.
  122. $extras['type'] = $nid_or_type;
  123. $node = $this->drupalCreateNode($extras);
  124. $nid = $node->nid;
  125. // Save at least one revision to better simulate a real site.
  126. $this->drupalCreateNode(get_object_vars($node));
  127. $node = node_load($nid, NULL, TRUE);
  128. $this->assertNotEqual($nid, $node->vid, 'Node revision exists.');
  129. }
  130. // Attach a file to the node.
  131. $edit['files[' . $field_name . '_' . $langcode . '_0]'] = drupal_realpath($file->uri);
  132. $this->drupalPost("node/$nid/edit", $edit, t('Save'));
  133. return $nid;
  134. }
  135. /**
  136. * Removes a file from a node.
  137. *
  138. * Note that if replacing a file, it must first be removed then added again.
  139. */
  140. function removeNodeFile($nid, $new_revision = TRUE) {
  141. $edit = array(
  142. 'revision' => (string) (int) $new_revision,
  143. );
  144. $this->drupalPost('node/' . $nid . '/edit', array(), t('Remove'));
  145. $this->drupalPost(NULL, $edit, t('Save'));
  146. }
  147. /**
  148. * Replaces a file within a node.
  149. */
  150. function replaceNodeFile($file, $field_name, $nid, $new_revision = TRUE) {
  151. $edit = array(
  152. 'files[' . $field_name . '_' . LANGUAGE_NONE . '_0]' => drupal_realpath($file->uri),
  153. 'revision' => (string) (int) $new_revision,
  154. );
  155. $this->drupalPost('node/' . $nid . '/edit', array(), t('Remove'));
  156. $this->drupalPost(NULL, $edit, t('Save'));
  157. }
  158. /**
  159. * Asserts that a file exists physically on disk.
  160. */
  161. function assertFileExists($file, $message = NULL) {
  162. $message = isset($message) ? $message : format_string('File %file exists on the disk.', array('%file' => $file->uri));
  163. $this->assertTrue(is_file($file->uri), $message);
  164. }
  165. /**
  166. * Asserts that a file exists in the database.
  167. */
  168. function assertFileEntryExists($file, $message = NULL) {
  169. entity_get_controller('file')->resetCache();
  170. $db_file = file_load($file->fid);
  171. $message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', array('%file' => $file->uri));
  172. $this->assertEqual($db_file->uri, $file->uri, $message);
  173. }
  174. /**
  175. * Asserts that a file does not exist on disk.
  176. */
  177. function assertFileNotExists($file, $message = NULL) {
  178. $message = isset($message) ? $message : format_string('File %file exists on the disk.', array('%file' => $file->uri));
  179. $this->assertFalse(is_file($file->uri), $message);
  180. }
  181. /**
  182. * Asserts that a file does not exist in the database.
  183. */
  184. function assertFileEntryNotExists($file, $message) {
  185. entity_get_controller('file')->resetCache();
  186. $message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', array('%file' => $file->uri));
  187. $this->assertFalse(file_load($file->fid), $message);
  188. }
  189. /**
  190. * Asserts that a file's status is set to permanent in the database.
  191. */
  192. function assertFileIsPermanent($file, $message = NULL) {
  193. $message = isset($message) ? $message : format_string('File %file is permanent.', array('%file' => $file->uri));
  194. $this->assertTrue($file->status == FILE_STATUS_PERMANENT, $message);
  195. }
  196. }
  197. /**
  198. * Tests the 'managed_file' element type.
  199. *
  200. * @todo Create a FileTestCase base class and move FileFieldTestCase methods
  201. * that aren't related to fields into it.
  202. */
  203. class FileManagedFileElementTestCase extends FileFieldTestCase {
  204. public static function getInfo() {
  205. return array(
  206. 'name' => 'Managed file element test',
  207. 'description' => 'Tests the managed_file element type.',
  208. 'group' => 'File',
  209. );
  210. }
  211. /**
  212. * Tests the managed_file element type.
  213. */
  214. function testManagedFile() {
  215. // Check that $element['#size'] is passed to the child upload element.
  216. $this->drupalGet('file/test');
  217. $this->assertFieldByXpath('//input[@name="files[nested_file]" and @size="13"]', NULL, 'The custom #size attribute is passed to the child upload element.');
  218. // Perform the tests with all permutations of $form['#tree'] and
  219. // $element['#extended'].
  220. foreach (array(0, 1) as $tree) {
  221. foreach (array(0, 1) as $extended) {
  222. $test_file = $this->getTestFile('text');
  223. $path = 'file/test/' . $tree . '/' . $extended;
  224. $input_base_name = $tree ? 'nested_file' : 'file';
  225. // Submit without a file.
  226. $this->drupalPost($path, array(), t('Save'));
  227. $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), 'Submitted without a file.');
  228. // Submit a new file, without using the Upload button.
  229. $last_fid_prior = $this->getLastFileId();
  230. $edit = array('files[' . $input_base_name . ']' => drupal_realpath($test_file->uri));
  231. $this->drupalPost($path, $edit, t('Save'));
  232. $last_fid = $this->getLastFileId();
  233. $this->assertTrue($last_fid > $last_fid_prior, 'New file got saved.');
  234. $this->assertRaw(t('The file id is %fid.', array('%fid' => $last_fid)), 'Submit handler has correct file info.');
  235. // Submit no new input, but with a default file.
  236. $this->drupalPost($path . '/' . $last_fid, array(), t('Save'));
  237. $this->assertRaw(t('The file id is %fid.', array('%fid' => $last_fid)), 'Empty submission did not change an existing file.');
  238. // Now, test the Upload and Remove buttons, with and without Ajax.
  239. foreach (array(FALSE, TRUE) as $ajax) {
  240. // Upload, then Submit.
  241. $last_fid_prior = $this->getLastFileId();
  242. $this->drupalGet($path);
  243. $edit = array('files[' . $input_base_name . ']' => drupal_realpath($test_file->uri));
  244. if ($ajax) {
  245. $this->drupalPostAJAX(NULL, $edit, $input_base_name . '_upload_button');
  246. }
  247. else {
  248. $this->drupalPost(NULL, $edit, t('Upload'));
  249. }
  250. $last_fid = $this->getLastFileId();
  251. $this->assertTrue($last_fid > $last_fid_prior, 'New file got uploaded.');
  252. $this->drupalPost(NULL, array(), t('Save'));
  253. $this->assertRaw(t('The file id is %fid.', array('%fid' => $last_fid)), 'Submit handler has correct file info.');
  254. // Remove, then Submit.
  255. $this->drupalGet($path . '/' . $last_fid);
  256. if ($ajax) {
  257. $this->drupalPostAJAX(NULL, array(), $input_base_name . '_remove_button');
  258. }
  259. else {
  260. $this->drupalPost(NULL, array(), t('Remove'));
  261. }
  262. $this->drupalPost(NULL, array(), t('Save'));
  263. $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), 'Submission after file removal was successful.');
  264. // Upload, then Remove, then Submit.
  265. $this->drupalGet($path);
  266. $edit = array('files[' . $input_base_name . ']' => drupal_realpath($test_file->uri));
  267. if ($ajax) {
  268. $this->drupalPostAJAX(NULL, $edit, $input_base_name . '_upload_button');
  269. $this->drupalPostAJAX(NULL, array(), $input_base_name . '_remove_button');
  270. }
  271. else {
  272. $this->drupalPost(NULL, $edit, t('Upload'));
  273. $this->drupalPost(NULL, array(), t('Remove'));
  274. }
  275. $this->drupalPost(NULL, array(), t('Save'));
  276. $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), 'Submission after file upload and removal was successful.');
  277. }
  278. }
  279. }
  280. }
  281. }
  282. /**
  283. * Tests file field widget.
  284. */
  285. class FileFieldWidgetTestCase extends FileFieldTestCase {
  286. public static function getInfo() {
  287. return array(
  288. 'name' => 'File field widget test',
  289. 'description' => 'Tests the file field widget, single and multi-valued, with and without AJAX, with public and private files.',
  290. 'group' => 'File',
  291. );
  292. }
  293. /**
  294. * Tests upload and remove buttons for a single-valued File field.
  295. */
  296. function testSingleValuedWidget() {
  297. // Use 'page' instead of 'article', so that the 'article' image field does
  298. // not conflict with this test. If in the future the 'page' type gets its
  299. // own default file or image field, this test can be made more robust by
  300. // using a custom node type.
  301. $type_name = 'page';
  302. $field_name = strtolower($this->randomName());
  303. $this->createFileField($field_name, $type_name);
  304. $field = field_info_field($field_name);
  305. $instance = field_info_instance('node', $field_name, $type_name);
  306. $test_file = $this->getTestFile('text');
  307. foreach (array('nojs', 'js') as $type) {
  308. // Create a new node with the uploaded file and ensure it got uploaded
  309. // successfully.
  310. // @todo This only tests a 'nojs' submission, because drupalPostAJAX()
  311. // does not yet support file uploads.
  312. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  313. $node = node_load($nid, NULL, TRUE);
  314. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  315. $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
  316. // Ensure the file can be downloaded.
  317. $this->drupalGet(file_create_url($node_file->uri));
  318. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
  319. // Ensure the edit page has a remove button instead of an upload button.
  320. $this->drupalGet("node/$nid/edit");
  321. $this->assertNoFieldByXPath('//input[@type="submit"]', t('Upload'), 'Node with file does not display the "Upload" button.');
  322. $this->assertFieldByXpath('//input[@type="submit"]', t('Remove'), 'Node with file displays the "Remove" button.');
  323. // "Click" the remove button (emulating either a nojs or js submission).
  324. switch ($type) {
  325. case 'nojs':
  326. $this->drupalPost(NULL, array(), t('Remove'));
  327. break;
  328. case 'js':
  329. $button = $this->xpath('//input[@type="submit" and @value="' . t('Remove') . '"]');
  330. $this->drupalPostAJAX(NULL, array(), array((string) $button[0]['name'] => (string) $button[0]['value']));
  331. break;
  332. }
  333. // Ensure the page now has an upload button instead of a remove button.
  334. $this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), 'After clicking the "Remove" button, it is no longer displayed.');
  335. $this->assertFieldByXpath('//input[@type="submit"]', t('Upload'), 'After clicking the "Remove" button, the "Upload" button is displayed.');
  336. // Save the node and ensure it does not have the file.
  337. $this->drupalPost(NULL, array(), t('Save'));
  338. $node = node_load($nid, NULL, TRUE);
  339. $this->assertTrue(empty($node->{$field_name}[LANGUAGE_NONE][0]['fid']), 'File was successfully removed from the node.');
  340. }
  341. }
  342. /**
  343. * Tests upload and remove buttons for multiple multi-valued File fields.
  344. */
  345. function testMultiValuedWidget() {
  346. // Use 'page' instead of 'article', so that the 'article' image field does
  347. // not conflict with this test. If in the future the 'page' type gets its
  348. // own default file or image field, this test can be made more robust by
  349. // using a custom node type.
  350. $type_name = 'page';
  351. $field_name = strtolower($this->randomName());
  352. $field_name2 = strtolower($this->randomName());
  353. $this->createFileField($field_name, $type_name, array('cardinality' => 3));
  354. $this->createFileField($field_name2, $type_name, array('cardinality' => 3));
  355. $field = field_info_field($field_name);
  356. $instance = field_info_instance('node', $field_name, $type_name);
  357. $field2 = field_info_field($field_name2);
  358. $instance2 = field_info_instance('node', $field_name2, $type_name);
  359. $test_file = $this->getTestFile('text');
  360. foreach (array('nojs', 'js') as $type) {
  361. // Visit the node creation form, and upload 3 files for each field. Since
  362. // the field has cardinality of 3, ensure the "Upload" button is displayed
  363. // until after the 3rd file, and after that, isn't displayed. Because
  364. // SimpleTest triggers the last button with a given name, so upload to the
  365. // second field first.
  366. // @todo This is only testing a non-Ajax upload, because drupalPostAJAX()
  367. // does not yet emulate jQuery's file upload.
  368. //
  369. $this->drupalGet("node/add/$type_name");
  370. foreach (array($field_name2, $field_name) as $each_field_name) {
  371. for ($delta = 0; $delta < 3; $delta++) {
  372. $edit = array('files[' . $each_field_name . '_' . LANGUAGE_NONE . '_' . $delta . ']' => drupal_realpath($test_file->uri));
  373. // If the Upload button doesn't exist, drupalPost() will automatically
  374. // fail with an assertion message.
  375. $this->drupalPost(NULL, $edit, t('Upload'));
  376. }
  377. }
  378. $this->assertNoFieldByXpath('//input[@type="submit"]', t('Upload'), 'After uploading 3 files for each field, the "Upload" button is no longer displayed.');
  379. $num_expected_remove_buttons = 6;
  380. foreach (array($field_name, $field_name2) as $current_field_name) {
  381. // How many uploaded files for the current field are remaining.
  382. $remaining = 3;
  383. // Test clicking each "Remove" button. For extra robustness, test them out
  384. // of sequential order. They are 0-indexed, and get renumbered after each
  385. // iteration, so array(1, 1, 0) means:
  386. // - First remove the 2nd file.
  387. // - Then remove what is then the 2nd file (was originally the 3rd file).
  388. // - Then remove the first file.
  389. foreach (array(1,1,0) as $delta) {
  390. // Ensure we have the expected number of Remove buttons, and that they
  391. // are numbered sequentially.
  392. $buttons = $this->xpath('//input[@type="submit" and @value="Remove"]');
  393. $this->assertTrue(is_array($buttons) && count($buttons) === $num_expected_remove_buttons, format_string('There are %n "Remove" buttons displayed (JSMode=%type).', array('%n' => $num_expected_remove_buttons, '%type' => $type)));
  394. foreach ($buttons as $i => $button) {
  395. $key = $i >= $remaining ? $i - $remaining : $i;
  396. $check_field_name = $field_name2;
  397. if ($current_field_name == $field_name && $i < $remaining) {
  398. $check_field_name = $field_name;
  399. }
  400. $this->assertIdentical((string) $button['name'], $check_field_name . '_' . LANGUAGE_NONE . '_' . $key. '_remove_button');
  401. }
  402. // "Click" the remove button (emulating either a nojs or js submission).
  403. $button_name = $current_field_name . '_' . LANGUAGE_NONE . '_' . $delta . '_remove_button';
  404. switch ($type) {
  405. case 'nojs':
  406. // drupalPost() takes a $submit parameter that is the value of the
  407. // button whose click we want to emulate. Since we have multiple
  408. // buttons with the value "Remove", and want to control which one we
  409. // use, we change the value of the other ones to something else.
  410. // Since non-clicked buttons aren't included in the submitted POST
  411. // data, and since drupalPost() will result in $this being updated
  412. // with a newly rebuilt form, this doesn't cause problems.
  413. foreach ($buttons as $button) {
  414. if ($button['name'] != $button_name) {
  415. $button['value'] = 'DUMMY';
  416. }
  417. }
  418. $this->drupalPost(NULL, array(), t('Remove'));
  419. break;
  420. case 'js':
  421. // drupalPostAJAX() lets us target the button precisely, so we don't
  422. // require the workaround used above for nojs.
  423. $this->drupalPostAJAX(NULL, array(), array($button_name => t('Remove')));
  424. break;
  425. }
  426. $num_expected_remove_buttons--;
  427. $remaining--;
  428. // Ensure an "Upload" button for the current field is displayed with the
  429. // correct name.
  430. $upload_button_name = $current_field_name . '_' . LANGUAGE_NONE . '_' . $remaining . '_upload_button';
  431. $buttons = $this->xpath('//input[@type="submit" and @value="Upload" and @name=:name]', array(':name' => $upload_button_name));
  432. $this->assertTrue(is_array($buttons) && count($buttons) == 1, format_string('The upload button is displayed with the correct name (JSMode=%type).', array('%type' => $type)));
  433. // Ensure only at most one button per field is displayed.
  434. $buttons = $this->xpath('//input[@type="submit" and @value="Upload"]');
  435. $expected = $current_field_name == $field_name ? 1 : 2;
  436. $this->assertTrue(is_array($buttons) && count($buttons) == $expected, format_string('After removing a file, only one "Upload" button for each possible field is displayed (JSMode=%type).', array('%type' => $type)));
  437. }
  438. }
  439. // Ensure the page now has no Remove buttons.
  440. $this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), format_string('After removing all files, there is no "Remove" button displayed (JSMode=%type).', array('%type' => $type)));
  441. // Save the node and ensure it does not have any files.
  442. $this->drupalPost(NULL, array('title' => $this->randomName()), t('Save'));
  443. $matches = array();
  444. preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
  445. $nid = $matches[1];
  446. $node = node_load($nid, NULL, TRUE);
  447. $this->assertTrue(empty($node->{$field_name}[LANGUAGE_NONE][0]['fid']), 'Node was successfully saved without any files.');
  448. }
  449. }
  450. /**
  451. * Tests a file field with a "Private files" upload destination setting.
  452. */
  453. function testPrivateFileSetting() {
  454. // Use 'page' instead of 'article', so that the 'article' image field does
  455. // not conflict with this test. If in the future the 'page' type gets its
  456. // own default file or image field, this test can be made more robust by
  457. // using a custom node type.
  458. $type_name = 'page';
  459. $field_name = strtolower($this->randomName());
  460. $this->createFileField($field_name, $type_name);
  461. $field = field_info_field($field_name);
  462. $instance = field_info_instance('node', $field_name, $type_name);
  463. $test_file = $this->getTestFile('text');
  464. // Change the field setting to make its files private, and upload a file.
  465. $edit = array('field[settings][uri_scheme]' => 'private');
  466. $this->drupalPost("admin/structure/types/manage/$type_name/fields/$field_name", $edit, t('Save settings'));
  467. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  468. $node = node_load($nid, NULL, TRUE);
  469. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  470. $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
  471. // Ensure the private file is available to the user who uploaded it.
  472. $this->drupalGet(file_create_url($node_file->uri));
  473. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
  474. // Ensure we can't change 'uri_scheme' field settings while there are some
  475. // entities with uploaded files.
  476. $this->drupalGet("admin/structure/types/manage/$type_name/fields/$field_name");
  477. $this->assertFieldByXpath('//input[@id="edit-field-settings-uri-scheme-public" and @disabled="disabled"]', 'public', 'Upload destination setting disabled.');
  478. // Delete node and confirm that setting could be changed.
  479. node_delete($nid);
  480. $this->drupalGet("admin/structure/types/manage/$type_name/fields/$field_name");
  481. $this->assertFieldByXpath('//input[@id="edit-field-settings-uri-scheme-public" and not(@disabled)]', 'public', 'Upload destination setting enabled.');
  482. }
  483. /**
  484. * Tests that download restrictions on private files work on comments.
  485. */
  486. function testPrivateFileComment() {
  487. $user = $this->drupalCreateUser(array('access comments'));
  488. // Remove access comments permission from anon user.
  489. $edit = array(
  490. DRUPAL_ANONYMOUS_RID . '[access comments]' => FALSE,
  491. );
  492. $this->drupalPost('admin/people/permissions', $edit, t('Save permissions'));
  493. // Create a new field.
  494. $edit = array(
  495. 'fields[_add_new_field][label]' => $label = $this->randomName(),
  496. 'fields[_add_new_field][field_name]' => $name = strtolower($this->randomName()),
  497. 'fields[_add_new_field][type]' => 'file',
  498. 'fields[_add_new_field][widget_type]' => 'file_generic',
  499. );
  500. $this->drupalPost('admin/structure/types/manage/article/comment/fields', $edit, t('Save'));
  501. $edit = array('field[settings][uri_scheme]' => 'private');
  502. $this->drupalPost(NULL, $edit, t('Save field settings'));
  503. $this->drupalPost(NULL, array(), t('Save settings'));
  504. // Create node.
  505. $text_file = $this->getTestFile('text');
  506. $edit = array(
  507. 'title' => $this->randomName(),
  508. );
  509. $this->drupalPost('node/add/article', $edit, t('Save'));
  510. $node = $this->drupalGetNodeByTitle($edit['title']);
  511. // Add a comment with a file.
  512. $text_file = $this->getTestFile('text');
  513. $edit = array(
  514. 'files[field_' . $name . '_' . LANGUAGE_NONE . '_' . 0 . ']' => drupal_realpath($text_file->uri),
  515. 'comment_body[' . LANGUAGE_NONE . '][0][value]' => $comment_body = $this->randomName(),
  516. );
  517. $this->drupalPost(NULL, $edit, t('Save'));
  518. // Get the comment ID.
  519. preg_match('/comment-([0-9]+)/', $this->getUrl(), $matches);
  520. $cid = $matches[1];
  521. // Log in as normal user.
  522. $this->drupalLogin($user);
  523. $comment = comment_load($cid);
  524. $comment_file = (object) $comment->{'field_' . $name}[LANGUAGE_NONE][0];
  525. $this->assertFileExists($comment_file, 'New file saved to disk on node creation.');
  526. // Test authenticated file download.
  527. $url = file_create_url($comment_file->uri);
  528. $this->assertNotEqual($url, NULL, 'Confirmed that the URL is valid');
  529. $this->drupalGet(file_create_url($comment_file->uri));
  530. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
  531. // Test anonymous file download.
  532. $this->drupalLogout();
  533. $this->drupalGet(file_create_url($comment_file->uri));
  534. $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
  535. // Unpublishes node.
  536. $this->drupalLogin($this->admin_user);
  537. $edit = array(
  538. 'status' => FALSE,
  539. );
  540. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  541. // Ensures normal user can no longer download the file.
  542. $this->drupalLogin($user);
  543. $this->drupalGet(file_create_url($comment_file->uri));
  544. $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
  545. }
  546. }
  547. /**
  548. * Tests file handling with node revisions.
  549. */
  550. class FileFieldRevisionTestCase extends FileFieldTestCase {
  551. public static function getInfo() {
  552. return array(
  553. 'name' => 'File field revision test',
  554. 'description' => 'Test creating and deleting revisions with files attached.',
  555. 'group' => 'File',
  556. );
  557. }
  558. /**
  559. * Tests creating multiple revisions of a node and managing attached files.
  560. *
  561. * Expected behaviors:
  562. * - Adding a new revision will make another entry in the field table, but
  563. * the original file will not be duplicated.
  564. * - Deleting a revision should not delete the original file if the file
  565. * is in use by another revision.
  566. * - When the last revision that uses a file is deleted, the original file
  567. * should be deleted also.
  568. */
  569. function testRevisions() {
  570. $type_name = 'article';
  571. $field_name = strtolower($this->randomName());
  572. $this->createFileField($field_name, $type_name);
  573. $field = field_info_field($field_name);
  574. $instance = field_info_instance('node', $field_name, $type_name);
  575. // Attach the same fields to users.
  576. $this->attachFileField($field_name, 'user', 'user');
  577. $test_file = $this->getTestFile('text');
  578. // Create a new node with the uploaded file.
  579. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  580. // Check that the file exists on disk and in the database.
  581. $node = node_load($nid, NULL, TRUE);
  582. $node_file_r1 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  583. $node_vid_r1 = $node->vid;
  584. $this->assertFileExists($node_file_r1, 'New file saved to disk on node creation.');
  585. $this->assertFileEntryExists($node_file_r1, 'File entry exists in database on node creation.');
  586. $this->assertFileIsPermanent($node_file_r1, 'File is permanent.');
  587. // Upload another file to the same node in a new revision.
  588. $this->replaceNodeFile($test_file, $field_name, $nid);
  589. $node = node_load($nid, NULL, TRUE);
  590. $node_file_r2 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  591. $node_vid_r2 = $node->vid;
  592. $this->assertFileExists($node_file_r2, 'Replacement file exists on disk after creating new revision.');
  593. $this->assertFileEntryExists($node_file_r2, 'Replacement file entry exists in database after creating new revision.');
  594. $this->assertFileIsPermanent($node_file_r2, 'Replacement file is permanent.');
  595. // Check that the original file is still in place on the first revision.
  596. $node = node_load($nid, $node_vid_r1, TRUE);
  597. $this->assertEqual($node_file_r1, (object) $node->{$field_name}[LANGUAGE_NONE][0], 'Original file still in place after replacing file in new revision.');
  598. $this->assertFileExists($node_file_r1, 'Original file still in place after replacing file in new revision.');
  599. $this->assertFileEntryExists($node_file_r1, 'Original file entry still in place after replacing file in new revision');
  600. $this->assertFileIsPermanent($node_file_r1, 'Original file is still permanent.');
  601. // Save a new version of the node without any changes.
  602. // Check that the file is still the same as the previous revision.
  603. $this->drupalPost('node/' . $nid . '/edit', array('revision' => '1'), t('Save'));
  604. $node = node_load($nid, NULL, TRUE);
  605. $node_file_r3 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  606. $node_vid_r3 = $node->vid;
  607. $this->assertEqual($node_file_r2, $node_file_r3, 'Previous revision file still in place after creating a new revision without a new file.');
  608. $this->assertFileIsPermanent($node_file_r3, 'New revision file is permanent.');
  609. // Revert to the first revision and check that the original file is active.
  610. $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r1 . '/revert', array(), t('Revert'));
  611. $node = node_load($nid, NULL, TRUE);
  612. $node_file_r4 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  613. $node_vid_r4 = $node->vid;
  614. $this->assertEqual($node_file_r1, $node_file_r4, 'Original revision file still in place after reverting to the original revision.');
  615. $this->assertFileIsPermanent($node_file_r4, 'Original revision file still permanent after reverting to the original revision.');
  616. // Delete the second revision and check that the file is kept (since it is
  617. // still being used by the third revision).
  618. $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r2 . '/delete', array(), t('Delete'));
  619. $this->assertFileExists($node_file_r3, 'Second file is still available after deleting second revision, since it is being used by the third revision.');
  620. $this->assertFileEntryExists($node_file_r3, 'Second file entry is still available after deleting second revision, since it is being used by the third revision.');
  621. $this->assertFileIsPermanent($node_file_r3, 'Second file entry is still permanent after deleting second revision, since it is being used by the third revision.');
  622. // Attach the second file to a user.
  623. $user = $this->drupalCreateUser();
  624. $edit = (array) $user;
  625. $edit[$field_name][LANGUAGE_NONE][0] = (array) $node_file_r3;
  626. user_save($user, $edit);
  627. $this->drupalGet('user/' . $user->uid . '/edit');
  628. // Delete the third revision and check that the file is not deleted yet.
  629. $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r3 . '/delete', array(), t('Delete'));
  630. $this->assertFileExists($node_file_r3, 'Second file is still available after deleting third revision, since it is being used by the user.');
  631. $this->assertFileEntryExists($node_file_r3, 'Second file entry is still available after deleting third revision, since it is being used by the user.');
  632. $this->assertFileIsPermanent($node_file_r3, 'Second file entry is still permanent after deleting third revision, since it is being used by the user.');
  633. // Delete the user and check that the file is also deleted.
  634. user_delete($user->uid);
  635. // TODO: This seems like a bug in File API. Clearing the stat cache should
  636. // not be necessary here. The file really is deleted, but stream wrappers
  637. // doesn't seem to think so unless we clear the PHP file stat() cache.
  638. clearstatcache();
  639. $this->assertFileNotExists($node_file_r3, 'Second file is now deleted after deleting third revision, since it is no longer being used by any other nodes.');
  640. $this->assertFileEntryNotExists($node_file_r3, 'Second file entry is now deleted after deleting third revision, since it is no longer being used by any other nodes.');
  641. // Delete the entire node and check that the original file is deleted.
  642. $this->drupalPost('node/' . $nid . '/delete', array(), t('Delete'));
  643. $this->assertFileNotExists($node_file_r1, 'Original file is deleted after deleting the entire node with two revisions remaining.');
  644. $this->assertFileEntryNotExists($node_file_r1, 'Original file entry is deleted after deleting the entire node with two revisions remaining.');
  645. }
  646. }
  647. /**
  648. * Tests that formatters are working properly.
  649. */
  650. class FileFieldDisplayTestCase extends FileFieldTestCase {
  651. public static function getInfo() {
  652. return array(
  653. 'name' => 'File field display tests',
  654. 'description' => 'Test the display of file fields in node and views.',
  655. 'group' => 'File',
  656. );
  657. }
  658. /**
  659. * Tests normal formatter display on node display.
  660. */
  661. function testNodeDisplay() {
  662. $field_name = strtolower($this->randomName());
  663. $type_name = 'article';
  664. $field_settings = array(
  665. 'display_field' => '1',
  666. 'display_default' => '1',
  667. );
  668. $instance_settings = array(
  669. 'description_field' => '1',
  670. );
  671. $widget_settings = array();
  672. $this->createFileField($field_name, $type_name, $field_settings, $instance_settings, $widget_settings);
  673. $field = field_info_field($field_name);
  674. $instance = field_info_instance('node', $field_name, $type_name);
  675. // Create a new node *without* the file field set, and check that the field
  676. // is not shown for each node display.
  677. $node = $this->drupalCreateNode(array('type' => $type_name));
  678. $file_formatters = array('file_default', 'file_table', 'file_url_plain', 'hidden');
  679. foreach ($file_formatters as $formatter) {
  680. $edit = array(
  681. "fields[$field_name][type]" => $formatter,
  682. );
  683. $this->drupalPost("admin/structure/types/manage/$type_name/display", $edit, t('Save'));
  684. $this->drupalGet('node/' . $node->nid);
  685. $this->assertNoText($field_name, format_string('Field label is hidden when no file attached for formatter %formatter', array('%formatter' => $formatter)));
  686. }
  687. $test_file = $this->getTestFile('text');
  688. // Create a new node with the uploaded file.
  689. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  690. $this->drupalGet('node/' . $nid . '/edit');
  691. // Check that the default formatter is displaying with the file name.
  692. $node = node_load($nid, NULL, TRUE);
  693. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  694. $default_output = theme('file_link', array('file' => $node_file));
  695. $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
  696. // Turn the "display" option off and check that the file is no longer displayed.
  697. $edit = array($field_name . '[' . LANGUAGE_NONE . '][0][display]' => FALSE);
  698. $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
  699. $this->assertNoRaw($default_output, 'Field is hidden when "display" option is unchecked.');
  700. }
  701. }
  702. /**
  703. * Tests various validations.
  704. */
  705. class FileFieldValidateTestCase extends FileFieldTestCase {
  706. protected $field;
  707. protected $node_type;
  708. public static function getInfo() {
  709. return array(
  710. 'name' => 'File field validation tests',
  711. 'description' => 'Tests validation functions such as file type, max file size, max size per node, and required.',
  712. 'group' => 'File',
  713. );
  714. }
  715. /**
  716. * Tests the required property on file fields.
  717. */
  718. function testRequired() {
  719. $type_name = 'article';
  720. $field_name = strtolower($this->randomName());
  721. $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
  722. $field = field_info_field($field_name);
  723. $instance = field_info_instance('node', $field_name, $type_name);
  724. $test_file = $this->getTestFile('text');
  725. // Try to post a new node without uploading a file.
  726. $langcode = LANGUAGE_NONE;
  727. $edit = array("title" => $this->randomName());
  728. $this->drupalPost('node/add/' . $type_name, $edit, t('Save'));
  729. $this->assertRaw(t('!title field is required.', array('!title' => $instance['label'])), 'Node save failed when required file field was empty.');
  730. // Create a new node with the uploaded file.
  731. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  732. $this->assertTrue($nid !== FALSE, format_string('uploadNodeFile(@test_file, @field_name, @type_name) succeeded', array('@test_file' => $test_file->uri, '@field_name' => $field_name, '@type_name' => $type_name)));
  733. $node = node_load($nid, NULL, TRUE);
  734. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  735. $this->assertFileExists($node_file, 'File exists after uploading to the required field.');
  736. $this->assertFileEntryExists($node_file, 'File entry exists after uploading to the required field.');
  737. // Try again with a multiple value field.
  738. field_delete_field($field_name);
  739. $this->createFileField($field_name, $type_name, array('cardinality' => FIELD_CARDINALITY_UNLIMITED), array('required' => '1'));
  740. // Try to post a new node without uploading a file in the multivalue field.
  741. $edit = array('title' => $this->randomName());
  742. $this->drupalPost('node/add/' . $type_name, $edit, t('Save'));
  743. $this->assertRaw(t('!title field is required.', array('!title' => $instance['label'])), 'Node save failed when required multiple value file field was empty.');
  744. // Create a new node with the uploaded file into the multivalue field.
  745. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  746. $node = node_load($nid, NULL, TRUE);
  747. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  748. $this->assertFileExists($node_file, 'File exists after uploading to the required multiple value field.');
  749. $this->assertFileEntryExists($node_file, 'File entry exists after uploading to the required multipel value field.');
  750. // Remove our file field.
  751. field_delete_field($field_name);
  752. }
  753. /**
  754. * Tests the max file size validator.
  755. */
  756. function testFileMaxSize() {
  757. $type_name = 'article';
  758. $field_name = strtolower($this->randomName());
  759. $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
  760. $field = field_info_field($field_name);
  761. $instance = field_info_instance('node', $field_name, $type_name);
  762. $small_file = $this->getTestFile('text', 131072); // 128KB.
  763. $large_file = $this->getTestFile('text', 1310720); // 1.2MB
  764. // Test uploading both a large and small file with different increments.
  765. $sizes = array(
  766. '1M' => 1048576,
  767. '1024K' => 1048576,
  768. '1048576' => 1048576,
  769. );
  770. foreach ($sizes as $max_filesize => $file_limit) {
  771. // Set the max file upload size.
  772. $this->updateFileField($field_name, $type_name, array('max_filesize' => $max_filesize));
  773. $instance = field_info_instance('node', $field_name, $type_name);
  774. // Create a new node with the small file, which should pass.
  775. $nid = $this->uploadNodeFile($small_file, $field_name, $type_name);
  776. $node = node_load($nid, NULL, TRUE);
  777. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  778. $this->assertFileExists($node_file, format_string('File exists after uploading a file (%filesize) under the max limit (%maxsize).', array('%filesize' => format_size($small_file->filesize), '%maxsize' => $max_filesize)));
  779. $this->assertFileEntryExists($node_file, format_string('File entry exists after uploading a file (%filesize) under the max limit (%maxsize).', array('%filesize' => format_size($small_file->filesize), '%maxsize' => $max_filesize)));
  780. // Check that uploading the large file fails (1M limit).
  781. $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
  782. $error_message = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($large_file->filesize), '%maxsize' => format_size($file_limit)));
  783. $this->assertRaw($error_message, format_string('Node save failed when file (%filesize) exceeded the max upload size (%maxsize).', array('%filesize' => format_size($large_file->filesize), '%maxsize' => $max_filesize)));
  784. }
  785. // Turn off the max filesize.
  786. $this->updateFileField($field_name, $type_name, array('max_filesize' => ''));
  787. // Upload the big file successfully.
  788. $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
  789. $node = node_load($nid, NULL, TRUE);
  790. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  791. $this->assertFileExists($node_file, format_string('File exists after uploading a file (%filesize) with no max limit.', array('%filesize' => format_size($large_file->filesize))));
  792. $this->assertFileEntryExists($node_file, format_string('File entry exists after uploading a file (%filesize) with no max limit.', array('%filesize' => format_size($large_file->filesize))));
  793. // Remove our file field.
  794. field_delete_field($field_name);
  795. }
  796. /**
  797. * Tests file extension checking.
  798. */
  799. function testFileExtension() {
  800. $type_name = 'article';
  801. $field_name = strtolower($this->randomName());
  802. $this->createFileField($field_name, $type_name);
  803. $field = field_info_field($field_name);
  804. $instance = field_info_instance('node', $field_name, $type_name);
  805. $test_file = $this->getTestFile('image');
  806. list(, $test_file_extension) = explode('.', $test_file->filename);
  807. // Disable extension checking.
  808. $this->updateFileField($field_name, $type_name, array('file_extensions' => ''));
  809. // Check that the file can be uploaded with no extension checking.
  810. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  811. $node = node_load($nid, NULL, TRUE);
  812. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  813. $this->assertFileExists($node_file, 'File exists after uploading a file with no extension checking.');
  814. $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with no extension checking.');
  815. // Enable extension checking for text files.
  816. $this->updateFileField($field_name, $type_name, array('file_extensions' => 'txt'));
  817. // Check that the file with the wrong extension cannot be uploaded.
  818. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  819. $error_message = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => 'txt'));
  820. $this->assertRaw($error_message, 'Node save failed when file uploaded with the wrong extension.');
  821. // Enable extension checking for text and image files.
  822. $this->updateFileField($field_name, $type_name, array('file_extensions' => "txt $test_file_extension"));
  823. // Check that the file can be uploaded with extension checking.
  824. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  825. $node = node_load($nid, NULL, TRUE);
  826. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  827. $this->assertFileExists($node_file, 'File exists after uploading a file with extension checking.');
  828. $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with extension checking.');
  829. // Remove our file field.
  830. field_delete_field($field_name);
  831. }
  832. }
  833. /**
  834. * Tests that files are uploaded to proper locations.
  835. */
  836. class FileFieldPathTestCase extends FileFieldTestCase {
  837. public static function getInfo() {
  838. return array(
  839. 'name' => 'File field file path tests',
  840. 'description' => 'Test that files are uploaded to the proper location with token support.',
  841. 'group' => 'File',
  842. );
  843. }
  844. /**
  845. * Tests the normal formatter display on node display.
  846. */
  847. function testUploadPath() {
  848. $field_name = strtolower($this->randomName());
  849. $type_name = 'article';
  850. $field = $this->createFileField($field_name, $type_name);
  851. $test_file = $this->getTestFile('text');
  852. // Create a new node.
  853. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  854. // Check that the file was uploaded to the file root.
  855. $node = node_load($nid, NULL, TRUE);
  856. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  857. $this->assertPathMatch('public://' . $test_file->filename, $node_file->uri, format_string('The file %file was uploaded to the correct path.', array('%file' => $node_file->uri)));
  858. // Change the path to contain multiple subdirectories.
  859. $field = $this->updateFileField($field_name, $type_name, array('file_directory' => 'foo/bar/baz'));
  860. // Upload a new file into the subdirectories.
  861. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  862. // Check that the file was uploaded into the subdirectory.
  863. $node = node_load($nid, NULL, TRUE);
  864. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  865. $this->assertPathMatch('public://foo/bar/baz/' . $test_file->filename, $node_file->uri, format_string('The file %file was uploaded to the correct path.', array('%file' => $node_file->uri)));
  866. // Check the path when used with tokens.
  867. // Change the path to contain multiple token directories.
  868. $field = $this->updateFileField($field_name, $type_name, array('file_directory' => '[current-user:uid]/[current-user:name]'));
  869. // Upload a new file into the token subdirectories.
  870. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  871. // Check that the file was uploaded into the subdirectory.
  872. $node = node_load($nid, NULL, TRUE);
  873. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  874. // Do token replacement using the same user which uploaded the file, not
  875. // the user running the test case.
  876. $data = array('user' => $this->admin_user);
  877. $subdirectory = token_replace('[user:uid]/[user:name]', $data);
  878. $this->assertPathMatch('public://' . $subdirectory . '/' . $test_file->filename, $node_file->uri, format_string('The file %file was uploaded to the correct path with token replacements.', array('%file' => $node_file->uri)));
  879. }
  880. /**
  881. * Asserts that a file is uploaded to the right location.
  882. *
  883. * @param $expected_path
  884. * The location where the file is expected to be uploaded. Duplicate file
  885. * names to not need to be taken into account.
  886. * @param $actual_path
  887. * Where the file was actually uploaded.
  888. * @param $message
  889. * The message to display with this assertion.
  890. */
  891. function assertPathMatch($expected_path, $actual_path, $message) {
  892. // Strip off the extension of the expected path to allow for _0, _1, etc.
  893. // suffixes when the file hits a duplicate name.
  894. $pos = strrpos($expected_path, '.');
  895. $base_path = substr($expected_path, 0, $pos);
  896. $extension = substr($expected_path, $pos + 1);
  897. $result = preg_match('/' . preg_quote($base_path, '/') . '(_[0-9]+)?\.' . preg_quote($extension, '/') . '/', $actual_path);
  898. $this->assertTrue($result, $message);
  899. }
  900. }
  901. /**
  902. * Tests the file token replacement in strings.
  903. */
  904. class FileTokenReplaceTestCase extends FileFieldTestCase {
  905. public static function getInfo() {
  906. return array(
  907. 'name' => 'File token replacement',
  908. 'description' => 'Generates text using placeholders for dummy content to check file token replacement.',
  909. 'group' => 'File',
  910. );
  911. }
  912. /**
  913. * Creates a file, then tests the tokens generated from it.
  914. */
  915. function testFileTokenReplacement() {
  916. global $language;
  917. $url_options = array(
  918. 'absolute' => TRUE,
  919. 'language' => $language,
  920. );
  921. // Create file field.
  922. $type_name = 'article';
  923. $field_name = 'field_' . strtolower($this->randomName());
  924. $this->createFileField($field_name, $type_name);
  925. $field = field_info_field($field_name);
  926. $instance = field_info_instance('node', $field_name, $type_name);
  927. $test_file = $this->getTestFile('text');
  928. // Coping a file to test uploads with non-latin filenames.
  929. $filename = drupal_dirname($test_file->uri) . '/текстовый файл.txt';
  930. $test_file = file_copy($test_file, $filename);
  931. // Create a new node with the uploaded file.
  932. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  933. // Load the node and the file.
  934. $node = node_load($nid, NULL, TRUE);
  935. $file = file_load($node->{$field_name}[LANGUAGE_NONE][0]['fid']);
  936. // Generate and test sanitized tokens.
  937. $tests = array();
  938. $tests['[file:fid]'] = $file->fid;
  939. $tests['[file:name]'] = check_plain($file->filename);
  940. $tests['[file:path]'] = check_plain($file->uri);
  941. $tests['[file:mime]'] = check_plain($file->filemime);
  942. $tests['[file:size]'] = format_size($file->filesize);
  943. $tests['[file:url]'] = check_plain(file_create_url($file->uri));
  944. $tests['[file:timestamp]'] = format_date($file->timestamp, 'medium', '', NULL, $language->language);
  945. $tests['[file:timestamp:short]'] = format_date($file->timestamp, 'short', '', NULL, $language->language);
  946. $tests['[file:owner]'] = check_plain(format_username($this->admin_user));
  947. $tests['[file:owner:uid]'] = $file->uid;
  948. // Test to make sure that we generated something for each token.
  949. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
  950. foreach ($tests as $input => $expected) {
  951. $output = token_replace($input, array('file' => $file), array('language' => $language));
  952. $this->assertEqual($output, $expected, format_string('Sanitized file token %token replaced.', array('%token' => $input)));
  953. }
  954. // Generate and test unsanitized tokens.
  955. $tests['[file:name]'] = $file->filename;
  956. $tests['[file:path]'] = $file->uri;
  957. $tests['[file:mime]'] = $file->filemime;
  958. $tests['[file:size]'] = format_size($file->filesize);
  959. foreach ($tests as $input => $expected) {
  960. $output = token_replace($input, array('file' => $file), array('language' => $language, 'sanitize' => FALSE));
  961. $this->assertEqual($output, $expected, format_string('Unsanitized file token %token replaced.', array('%token' => $input)));
  962. }
  963. }
  964. }
  965. /**
  966. * Tests file access on private nodes.
  967. */
  968. class FilePrivateTestCase extends FileFieldTestCase {
  969. public static function getInfo() {
  970. return array(
  971. 'name' => 'Private file test',
  972. 'description' => 'Uploads a test to a private node and checks access.',
  973. 'group' => 'File',
  974. );
  975. }
  976. function setUp() {
  977. parent::setUp(array('node_access_test', 'field_test'));
  978. node_access_rebuild();
  979. variable_set('node_access_test_private', TRUE);
  980. }
  981. /**
  982. * Tests file access for file uploaded to a private node.
  983. */
  984. function testPrivateFile() {
  985. // Use 'page' instead of 'article', so that the 'article' image field does
  986. // not conflict with this test. If in the future the 'page' type gets its
  987. // own default file or image field, this test can be made more robust by
  988. // using a custom node type.
  989. $type_name = 'page';
  990. $field_name = strtolower($this->randomName());
  991. $this->createFileField($field_name, $type_name, array('uri_scheme' => 'private'));
  992. // Create a field with no view access - see field_test_field_access().
  993. $no_access_field_name = 'field_no_view_access';
  994. $this->createFileField($no_access_field_name, $type_name, array('uri_scheme' => 'private'));
  995. $test_file = $this->getTestFile('text');
  996. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name, TRUE, array('private' => TRUE));
  997. $node = node_load($nid, NULL, TRUE);
  998. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  999. // Ensure the file can be downloaded.
  1000. $this->drupalGet(file_create_url($node_file->uri));
  1001. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
  1002. $this->drupalLogOut();
  1003. $this->drupalGet(file_create_url($node_file->uri));
  1004. $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
  1005. // Test with the field that should deny access through field access.
  1006. $this->drupalLogin($this->admin_user);
  1007. $nid = $this->uploadNodeFile($test_file, $no_access_field_name, $type_name, TRUE, array('private' => TRUE));
  1008. $node = node_load($nid, NULL, TRUE);
  1009. $node_file = (object) $node->{$no_access_field_name}[LANGUAGE_NONE][0];
  1010. // Ensure the file cannot be downloaded.
  1011. $this->drupalGet(file_create_url($node_file->uri));
  1012. $this->assertResponse(403, 'Confirmed that access is denied for the file without view field access permission.');
  1013. }
  1014. }