file.test 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327
  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 adding a file to a non-node entity.
  199. */
  200. class FileTaxonomyTermTestCase extends DrupalWebTestCase {
  201. protected $admin_user;
  202. public static function getInfo() {
  203. return array(
  204. 'name' => 'Taxonomy term file test',
  205. 'description' => 'Tests adding a file to a non-node entity.',
  206. 'group' => 'File',
  207. );
  208. }
  209. public function setUp() {
  210. $modules[] = 'file';
  211. $modules[] = 'taxonomy';
  212. parent::setUp($modules);
  213. $this->admin_user = $this->drupalCreateUser(array('access content', 'access administration pages', 'administer site configuration', 'administer taxonomy'));
  214. $this->drupalLogin($this->admin_user);
  215. }
  216. /**
  217. * Creates a file field and attaches it to the "Tags" taxonomy vocabulary.
  218. *
  219. * @param $name
  220. * The field name of the file field to create.
  221. * @param $uri_scheme
  222. * The URI scheme to use for the file field (for example, "private" to
  223. * create a field that stores private files or "public" to create a field
  224. * that stores public files).
  225. */
  226. protected function createAttachFileField($name, $uri_scheme) {
  227. $field = array(
  228. 'field_name' => $name,
  229. 'type' => 'file',
  230. 'settings' => array(
  231. 'uri_scheme' => $uri_scheme,
  232. ),
  233. 'cardinality' => 1,
  234. );
  235. field_create_field($field);
  236. // Attach an instance of it.
  237. $instance = array(
  238. 'field_name' => $name,
  239. 'label' => 'File',
  240. 'entity_type' => 'taxonomy_term',
  241. 'bundle' => 'tags',
  242. 'required' => FALSE,
  243. 'settings' => array(),
  244. 'widget' => array(
  245. 'type' => 'file_generic',
  246. 'settings' => array(),
  247. ),
  248. );
  249. field_create_instance($instance);
  250. }
  251. /**
  252. * Tests that a public file can be attached to a taxonomy term.
  253. *
  254. * This is a regression test for https://www.drupal.org/node/2305017.
  255. */
  256. public function testTermFilePublic() {
  257. $this->_testTermFile('public');
  258. }
  259. /**
  260. * Tests that a private file can be attached to a taxonomy term.
  261. *
  262. * This is a regression test for https://www.drupal.org/node/2305017.
  263. */
  264. public function testTermFilePrivate() {
  265. $this->_testTermFile('private');
  266. }
  267. /**
  268. * Runs tests for attaching a file field to a taxonomy term.
  269. *
  270. * @param $uri_scheme
  271. * The URI scheme to use for the file field, either "public" or "private".
  272. */
  273. protected function _testTermFile($uri_scheme) {
  274. $field_name = strtolower($this->randomName());
  275. $this->createAttachFileField($field_name, $uri_scheme);
  276. // Get a file to upload.
  277. $file = current($this->drupalGetTestFiles('text'));
  278. // Add a filesize property to files as would be read by file_load().
  279. $file->filesize = filesize($file->uri);
  280. $langcode = LANGUAGE_NONE;
  281. $edit = array(
  282. "name" => $this->randomName(),
  283. );
  284. // Attach a file to the term.
  285. $edit['files[' . $field_name . '_' . $langcode . '_0]'] = drupal_realpath($file->uri);
  286. $this->drupalPost("admin/structure/taxonomy/tags/add", $edit, t('Save'));
  287. // Find the term ID we just created.
  288. $tid = db_query_range('SELECT tid FROM {taxonomy_term_data} ORDER BY tid DESC', 0, 1)->fetchField();
  289. $terms = entity_load('taxonomy_term', array($tid));
  290. $term = $terms[$tid];
  291. $fid = $term->{$field_name}[LANGUAGE_NONE][0]['fid'];
  292. // Check that the uploaded file is present on the edit form.
  293. $this->drupalGet("taxonomy/term/$tid/edit");
  294. $file_input_name = $field_name . '[' . LANGUAGE_NONE . '][0][fid]';
  295. $this->assertFieldByXpath('//input[@type="hidden" and @name="' . $file_input_name . '"]', $fid, 'File is attached on edit form.');
  296. // Edit the term and change name without changing the file.
  297. $edit = array(
  298. "name" => $this->randomName(),
  299. );
  300. $this->drupalPost("taxonomy/term/$tid/edit", $edit, t('Save'));
  301. // Check that the uploaded file is still present on the edit form.
  302. $this->drupalGet("taxonomy/term/$tid/edit");
  303. $file_input_name = $field_name . '[' . LANGUAGE_NONE . '][0][fid]';
  304. $this->assertFieldByXpath('//input[@type="hidden" and @name="' . $file_input_name . '"]', $fid, 'File is attached on edit form.');
  305. // Load term while resetting the cache.
  306. $terms = entity_load('taxonomy_term', array($tid), array(), TRUE);
  307. $term = $terms[$tid];
  308. $this->assertTrue(!empty($term->{$field_name}[LANGUAGE_NONE]), 'Term has attached files.');
  309. $this->assertEqual($term->{$field_name}[LANGUAGE_NONE][0]['fid'], $fid, 'Same File ID is attached to the term.');
  310. }
  311. }
  312. /**
  313. * Tests the 'managed_file' element type.
  314. *
  315. * @todo Create a FileTestCase base class and move FileFieldTestCase methods
  316. * that aren't related to fields into it.
  317. */
  318. class FileManagedFileElementTestCase extends FileFieldTestCase {
  319. public static function getInfo() {
  320. return array(
  321. 'name' => 'Managed file element test',
  322. 'description' => 'Tests the managed_file element type.',
  323. 'group' => 'File',
  324. );
  325. }
  326. /**
  327. * Tests the managed_file element type.
  328. */
  329. function testManagedFile() {
  330. // Check that $element['#size'] is passed to the child upload element.
  331. $this->drupalGet('file/test');
  332. $this->assertFieldByXpath('//input[@name="files[nested_file]" and @size="13"]', NULL, 'The custom #size attribute is passed to the child upload element.');
  333. // Perform the tests with all permutations of $form['#tree'] and
  334. // $element['#extended'].
  335. foreach (array(0, 1) as $tree) {
  336. foreach (array(0, 1) as $extended) {
  337. $test_file = $this->getTestFile('text');
  338. $path = 'file/test/' . $tree . '/' . $extended;
  339. $input_base_name = $tree ? 'nested_file' : 'file';
  340. // Submit without a file.
  341. $this->drupalPost($path, array(), t('Save'));
  342. $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), 'Submitted without a file.');
  343. // Submit a new file, without using the Upload button.
  344. $last_fid_prior = $this->getLastFileId();
  345. $edit = array('files[' . $input_base_name . ']' => drupal_realpath($test_file->uri));
  346. $this->drupalPost($path, $edit, t('Save'));
  347. $last_fid = $this->getLastFileId();
  348. $this->assertTrue($last_fid > $last_fid_prior, 'New file got saved.');
  349. $this->assertRaw(t('The file id is %fid.', array('%fid' => $last_fid)), 'Submit handler has correct file info.');
  350. // Submit no new input, but with a default file.
  351. $this->drupalPost($path . '/' . $last_fid, array(), t('Save'));
  352. $this->assertRaw(t('The file id is %fid.', array('%fid' => $last_fid)), 'Empty submission did not change an existing file.');
  353. // Now, test the Upload and Remove buttons, with and without Ajax.
  354. foreach (array(FALSE, TRUE) as $ajax) {
  355. // Upload, then Submit.
  356. $last_fid_prior = $this->getLastFileId();
  357. $this->drupalGet($path);
  358. $edit = array('files[' . $input_base_name . ']' => drupal_realpath($test_file->uri));
  359. if ($ajax) {
  360. $this->drupalPostAJAX(NULL, $edit, $input_base_name . '_upload_button');
  361. }
  362. else {
  363. $this->drupalPost(NULL, $edit, t('Upload'));
  364. }
  365. $last_fid = $this->getLastFileId();
  366. $this->assertTrue($last_fid > $last_fid_prior, 'New file got uploaded.');
  367. $this->drupalPost(NULL, array(), t('Save'));
  368. $this->assertRaw(t('The file id is %fid.', array('%fid' => $last_fid)), 'Submit handler has correct file info.');
  369. // Remove, then Submit.
  370. $this->drupalGet($path . '/' . $last_fid);
  371. if ($ajax) {
  372. $this->drupalPostAJAX(NULL, array(), $input_base_name . '_remove_button');
  373. }
  374. else {
  375. $this->drupalPost(NULL, array(), t('Remove'));
  376. }
  377. $this->drupalPost(NULL, array(), t('Save'));
  378. $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), 'Submission after file removal was successful.');
  379. // Upload, then Remove, then Submit.
  380. $this->drupalGet($path);
  381. $edit = array('files[' . $input_base_name . ']' => drupal_realpath($test_file->uri));
  382. if ($ajax) {
  383. $this->drupalPostAJAX(NULL, $edit, $input_base_name . '_upload_button');
  384. $this->drupalPostAJAX(NULL, array(), $input_base_name . '_remove_button');
  385. }
  386. else {
  387. $this->drupalPost(NULL, $edit, t('Upload'));
  388. $this->drupalPost(NULL, array(), t('Remove'));
  389. }
  390. $this->drupalPost(NULL, array(), t('Save'));
  391. $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), 'Submission after file upload and removal was successful.');
  392. }
  393. }
  394. }
  395. }
  396. }
  397. /**
  398. * Tests file field widget.
  399. */
  400. class FileFieldWidgetTestCase extends FileFieldTestCase {
  401. public static function getInfo() {
  402. return array(
  403. 'name' => 'File field widget test',
  404. 'description' => 'Tests the file field widget, single and multi-valued, with and without AJAX, with public and private files.',
  405. 'group' => 'File',
  406. );
  407. }
  408. /**
  409. * Tests upload and remove buttons for a single-valued File field.
  410. */
  411. function testSingleValuedWidget() {
  412. // Use 'page' instead of 'article', so that the 'article' image field does
  413. // not conflict with this test. If in the future the 'page' type gets its
  414. // own default file or image field, this test can be made more robust by
  415. // using a custom node type.
  416. $type_name = 'page';
  417. $field_name = strtolower($this->randomName());
  418. $this->createFileField($field_name, $type_name);
  419. $field = field_info_field($field_name);
  420. $instance = field_info_instance('node', $field_name, $type_name);
  421. $test_file = $this->getTestFile('text');
  422. foreach (array('nojs', 'js') as $type) {
  423. // Create a new node with the uploaded file and ensure it got uploaded
  424. // successfully.
  425. // @todo This only tests a 'nojs' submission, because drupalPostAJAX()
  426. // does not yet support file uploads.
  427. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  428. $node = node_load($nid, NULL, TRUE);
  429. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  430. $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
  431. // Test that running field_attach_update() leaves the file intact.
  432. $field = new stdClass();
  433. $field->type = $type_name;
  434. $field->nid = $nid;
  435. field_attach_update('node', $field);
  436. $node = node_load($nid);
  437. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  438. $this->assertFileExists($node_file, 'New file still saved to disk on field update.');
  439. // Ensure the file can be downloaded.
  440. $this->drupalGet(file_create_url($node_file->uri));
  441. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
  442. // Ensure the edit page has a remove button instead of an upload button.
  443. $this->drupalGet("node/$nid/edit");
  444. $this->assertNoFieldByXPath('//input[@type="submit"]', t('Upload'), 'Node with file does not display the "Upload" button.');
  445. $this->assertFieldByXpath('//input[@type="submit"]', t('Remove'), 'Node with file displays the "Remove" button.');
  446. // "Click" the remove button (emulating either a nojs or js submission).
  447. switch ($type) {
  448. case 'nojs':
  449. $this->drupalPost(NULL, array(), t('Remove'));
  450. break;
  451. case 'js':
  452. $button = $this->xpath('//input[@type="submit" and @value="' . t('Remove') . '"]');
  453. $this->drupalPostAJAX(NULL, array(), array((string) $button[0]['name'] => (string) $button[0]['value']));
  454. break;
  455. }
  456. // Ensure the page now has an upload button instead of a remove button.
  457. $this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), 'After clicking the "Remove" button, it is no longer displayed.');
  458. $this->assertFieldByXpath('//input[@type="submit"]', t('Upload'), 'After clicking the "Remove" button, the "Upload" button is displayed.');
  459. // Save the node and ensure it does not have the file.
  460. $this->drupalPost(NULL, array(), t('Save'));
  461. $node = node_load($nid, NULL, TRUE);
  462. $this->assertTrue(empty($node->{$field_name}[LANGUAGE_NONE][0]['fid']), 'File was successfully removed from the node.');
  463. }
  464. }
  465. /**
  466. * Tests upload and remove buttons for multiple multi-valued File fields.
  467. */
  468. function testMultiValuedWidget() {
  469. // Use 'page' instead of 'article', so that the 'article' image field does
  470. // not conflict with this test. If in the future the 'page' type gets its
  471. // own default file or image field, this test can be made more robust by
  472. // using a custom node type.
  473. $type_name = 'page';
  474. $field_name = strtolower($this->randomName());
  475. $field_name2 = strtolower($this->randomName());
  476. $this->createFileField($field_name, $type_name, array('cardinality' => 3));
  477. $this->createFileField($field_name2, $type_name, array('cardinality' => 3));
  478. $field = field_info_field($field_name);
  479. $instance = field_info_instance('node', $field_name, $type_name);
  480. $field2 = field_info_field($field_name2);
  481. $instance2 = field_info_instance('node', $field_name2, $type_name);
  482. $test_file = $this->getTestFile('text');
  483. foreach (array('nojs', 'js') as $type) {
  484. // Visit the node creation form, and upload 3 files for each field. Since
  485. // the field has cardinality of 3, ensure the "Upload" button is displayed
  486. // until after the 3rd file, and after that, isn't displayed. Because
  487. // SimpleTest triggers the last button with a given name, so upload to the
  488. // second field first.
  489. // @todo This is only testing a non-Ajax upload, because drupalPostAJAX()
  490. // does not yet emulate jQuery's file upload.
  491. //
  492. $this->drupalGet("node/add/$type_name");
  493. foreach (array($field_name2, $field_name) as $each_field_name) {
  494. for ($delta = 0; $delta < 3; $delta++) {
  495. $edit = array('files[' . $each_field_name . '_' . LANGUAGE_NONE . '_' . $delta . ']' => drupal_realpath($test_file->uri));
  496. // If the Upload button doesn't exist, drupalPost() will automatically
  497. // fail with an assertion message.
  498. $this->drupalPost(NULL, $edit, t('Upload'));
  499. }
  500. }
  501. $this->assertNoFieldByXpath('//input[@type="submit"]', t('Upload'), 'After uploading 3 files for each field, the "Upload" button is no longer displayed.');
  502. $num_expected_remove_buttons = 6;
  503. foreach (array($field_name, $field_name2) as $current_field_name) {
  504. // How many uploaded files for the current field are remaining.
  505. $remaining = 3;
  506. // Test clicking each "Remove" button. For extra robustness, test them out
  507. // of sequential order. They are 0-indexed, and get renumbered after each
  508. // iteration, so array(1, 1, 0) means:
  509. // - First remove the 2nd file.
  510. // - Then remove what is then the 2nd file (was originally the 3rd file).
  511. // - Then remove the first file.
  512. foreach (array(1,1,0) as $delta) {
  513. // Ensure we have the expected number of Remove buttons, and that they
  514. // are numbered sequentially.
  515. $buttons = $this->xpath('//input[@type="submit" and @value="Remove"]');
  516. $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)));
  517. foreach ($buttons as $i => $button) {
  518. $key = $i >= $remaining ? $i - $remaining : $i;
  519. $check_field_name = $field_name2;
  520. if ($current_field_name == $field_name && $i < $remaining) {
  521. $check_field_name = $field_name;
  522. }
  523. $this->assertIdentical((string) $button['name'], $check_field_name . '_' . LANGUAGE_NONE . '_' . $key. '_remove_button');
  524. }
  525. // "Click" the remove button (emulating either a nojs or js submission).
  526. $button_name = $current_field_name . '_' . LANGUAGE_NONE . '_' . $delta . '_remove_button';
  527. switch ($type) {
  528. case 'nojs':
  529. // drupalPost() takes a $submit parameter that is the value of the
  530. // button whose click we want to emulate. Since we have multiple
  531. // buttons with the value "Remove", and want to control which one we
  532. // use, we change the value of the other ones to something else.
  533. // Since non-clicked buttons aren't included in the submitted POST
  534. // data, and since drupalPost() will result in $this being updated
  535. // with a newly rebuilt form, this doesn't cause problems.
  536. foreach ($buttons as $button) {
  537. if ($button['name'] != $button_name) {
  538. $button['value'] = 'DUMMY';
  539. }
  540. }
  541. $this->drupalPost(NULL, array(), t('Remove'));
  542. break;
  543. case 'js':
  544. // drupalPostAJAX() lets us target the button precisely, so we don't
  545. // require the workaround used above for nojs.
  546. $this->drupalPostAJAX(NULL, array(), array($button_name => t('Remove')));
  547. break;
  548. }
  549. $num_expected_remove_buttons--;
  550. $remaining--;
  551. // Ensure an "Upload" button for the current field is displayed with the
  552. // correct name.
  553. $upload_button_name = $current_field_name . '_' . LANGUAGE_NONE . '_' . $remaining . '_upload_button';
  554. $buttons = $this->xpath('//input[@type="submit" and @value="Upload" and @name=:name]', array(':name' => $upload_button_name));
  555. $this->assertTrue(is_array($buttons) && count($buttons) == 1, format_string('The upload button is displayed with the correct name (JSMode=%type).', array('%type' => $type)));
  556. // Ensure only at most one button per field is displayed.
  557. $buttons = $this->xpath('//input[@type="submit" and @value="Upload"]');
  558. $expected = $current_field_name == $field_name ? 1 : 2;
  559. $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)));
  560. }
  561. }
  562. // Ensure the page now has no Remove buttons.
  563. $this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), format_string('After removing all files, there is no "Remove" button displayed (JSMode=%type).', array('%type' => $type)));
  564. // Save the node and ensure it does not have any files.
  565. $this->drupalPost(NULL, array('title' => $this->randomName()), t('Save'));
  566. $matches = array();
  567. preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
  568. $nid = $matches[1];
  569. $node = node_load($nid, NULL, TRUE);
  570. $this->assertTrue(empty($node->{$field_name}[LANGUAGE_NONE][0]['fid']), 'Node was successfully saved without any files.');
  571. }
  572. }
  573. /**
  574. * Tests a file field with a "Private files" upload destination setting.
  575. */
  576. function testPrivateFileSetting() {
  577. // Use 'page' instead of 'article', so that the 'article' image field does
  578. // not conflict with this test. If in the future the 'page' type gets its
  579. // own default file or image field, this test can be made more robust by
  580. // using a custom node type.
  581. $type_name = 'page';
  582. $field_name = strtolower($this->randomName());
  583. $this->createFileField($field_name, $type_name);
  584. $field = field_info_field($field_name);
  585. $instance = field_info_instance('node', $field_name, $type_name);
  586. $test_file = $this->getTestFile('text');
  587. // Change the field setting to make its files private, and upload a file.
  588. $edit = array('field[settings][uri_scheme]' => 'private');
  589. $this->drupalPost("admin/structure/types/manage/$type_name/fields/$field_name", $edit, t('Save settings'));
  590. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  591. $node = node_load($nid, NULL, TRUE);
  592. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  593. $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
  594. // Ensure the private file is available to the user who uploaded it.
  595. $this->drupalGet(file_create_url($node_file->uri));
  596. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
  597. // Ensure we can't change 'uri_scheme' field settings while there are some
  598. // entities with uploaded files.
  599. $this->drupalGet("admin/structure/types/manage/$type_name/fields/$field_name");
  600. $this->assertFieldByXpath('//input[@id="edit-field-settings-uri-scheme-public" and @disabled="disabled"]', 'public', 'Upload destination setting disabled.');
  601. // Delete node and confirm that setting could be changed.
  602. node_delete($nid);
  603. $this->drupalGet("admin/structure/types/manage/$type_name/fields/$field_name");
  604. $this->assertFieldByXpath('//input[@id="edit-field-settings-uri-scheme-public" and not(@disabled)]', 'public', 'Upload destination setting enabled.');
  605. }
  606. /**
  607. * Tests that download restrictions on private files work on comments.
  608. */
  609. function testPrivateFileComment() {
  610. $user = $this->drupalCreateUser(array('access comments'));
  611. // Remove access comments permission from anon user.
  612. $edit = array(
  613. DRUPAL_ANONYMOUS_RID . '[access comments]' => FALSE,
  614. );
  615. $this->drupalPost('admin/people/permissions', $edit, t('Save permissions'));
  616. // Create a new field.
  617. $edit = array(
  618. 'fields[_add_new_field][label]' => $label = $this->randomName(),
  619. 'fields[_add_new_field][field_name]' => $name = strtolower($this->randomName()),
  620. 'fields[_add_new_field][type]' => 'file',
  621. 'fields[_add_new_field][widget_type]' => 'file_generic',
  622. );
  623. $this->drupalPost('admin/structure/types/manage/article/comment/fields', $edit, t('Save'));
  624. $edit = array('field[settings][uri_scheme]' => 'private');
  625. $this->drupalPost(NULL, $edit, t('Save field settings'));
  626. $this->drupalPost(NULL, array(), t('Save settings'));
  627. // Create node.
  628. $text_file = $this->getTestFile('text');
  629. $edit = array(
  630. 'title' => $this->randomName(),
  631. );
  632. $this->drupalPost('node/add/article', $edit, t('Save'));
  633. $node = $this->drupalGetNodeByTitle($edit['title']);
  634. // Add a comment with a file.
  635. $text_file = $this->getTestFile('text');
  636. $edit = array(
  637. 'files[field_' . $name . '_' . LANGUAGE_NONE . '_' . 0 . ']' => drupal_realpath($text_file->uri),
  638. 'comment_body[' . LANGUAGE_NONE . '][0][value]' => $comment_body = $this->randomName(),
  639. );
  640. $this->drupalPost(NULL, $edit, t('Save'));
  641. // Get the comment ID.
  642. preg_match('/comment-([0-9]+)/', $this->getUrl(), $matches);
  643. $cid = $matches[1];
  644. // Log in as normal user.
  645. $this->drupalLogin($user);
  646. $comment = comment_load($cid);
  647. $comment_file = (object) $comment->{'field_' . $name}[LANGUAGE_NONE][0];
  648. $this->assertFileExists($comment_file, 'New file saved to disk on node creation.');
  649. // Test authenticated file download.
  650. $url = file_create_url($comment_file->uri);
  651. $this->assertNotEqual($url, NULL, 'Confirmed that the URL is valid');
  652. $this->drupalGet(file_create_url($comment_file->uri));
  653. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
  654. // Test anonymous file download.
  655. $this->drupalLogout();
  656. $this->drupalGet(file_create_url($comment_file->uri));
  657. $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
  658. // Unpublishes node.
  659. $this->drupalLogin($this->admin_user);
  660. $edit = array(
  661. 'status' => FALSE,
  662. );
  663. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  664. // Ensures normal user can no longer download the file.
  665. $this->drupalLogin($user);
  666. $this->drupalGet(file_create_url($comment_file->uri));
  667. $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
  668. }
  669. }
  670. /**
  671. * Tests file handling with node revisions.
  672. */
  673. class FileFieldRevisionTestCase extends FileFieldTestCase {
  674. public static function getInfo() {
  675. return array(
  676. 'name' => 'File field revision test',
  677. 'description' => 'Test creating and deleting revisions with files attached.',
  678. 'group' => 'File',
  679. );
  680. }
  681. /**
  682. * Tests creating multiple revisions of a node and managing attached files.
  683. *
  684. * Expected behaviors:
  685. * - Adding a new revision will make another entry in the field table, but
  686. * the original file will not be duplicated.
  687. * - Deleting a revision should not delete the original file if the file
  688. * is in use by another revision.
  689. * - When the last revision that uses a file is deleted, the original file
  690. * should be deleted also.
  691. */
  692. function testRevisions() {
  693. $type_name = 'article';
  694. $field_name = strtolower($this->randomName());
  695. $this->createFileField($field_name, $type_name);
  696. $field = field_info_field($field_name);
  697. $instance = field_info_instance('node', $field_name, $type_name);
  698. // Attach the same fields to users.
  699. $this->attachFileField($field_name, 'user', 'user');
  700. $test_file = $this->getTestFile('text');
  701. // Create a new node with the uploaded file.
  702. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  703. // Check that the file exists on disk and in the database.
  704. $node = node_load($nid, NULL, TRUE);
  705. $node_file_r1 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  706. $node_vid_r1 = $node->vid;
  707. $this->assertFileExists($node_file_r1, 'New file saved to disk on node creation.');
  708. $this->assertFileEntryExists($node_file_r1, 'File entry exists in database on node creation.');
  709. $this->assertFileIsPermanent($node_file_r1, 'File is permanent.');
  710. // Upload another file to the same node in a new revision.
  711. $this->replaceNodeFile($test_file, $field_name, $nid);
  712. $node = node_load($nid, NULL, TRUE);
  713. $node_file_r2 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  714. $node_vid_r2 = $node->vid;
  715. $this->assertFileExists($node_file_r2, 'Replacement file exists on disk after creating new revision.');
  716. $this->assertFileEntryExists($node_file_r2, 'Replacement file entry exists in database after creating new revision.');
  717. $this->assertFileIsPermanent($node_file_r2, 'Replacement file is permanent.');
  718. // Check that the original file is still in place on the first revision.
  719. $node = node_load($nid, $node_vid_r1, TRUE);
  720. $this->assertEqual($node_file_r1, (object) $node->{$field_name}[LANGUAGE_NONE][0], 'Original file still in place after replacing file in new revision.');
  721. $this->assertFileExists($node_file_r1, 'Original file still in place after replacing file in new revision.');
  722. $this->assertFileEntryExists($node_file_r1, 'Original file entry still in place after replacing file in new revision');
  723. $this->assertFileIsPermanent($node_file_r1, 'Original file is still permanent.');
  724. // Save a new version of the node without any changes.
  725. // Check that the file is still the same as the previous revision.
  726. $this->drupalPost('node/' . $nid . '/edit', array('revision' => '1'), t('Save'));
  727. $node = node_load($nid, NULL, TRUE);
  728. $node_file_r3 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  729. $node_vid_r3 = $node->vid;
  730. $this->assertEqual($node_file_r2, $node_file_r3, 'Previous revision file still in place after creating a new revision without a new file.');
  731. $this->assertFileIsPermanent($node_file_r3, 'New revision file is permanent.');
  732. // Revert to the first revision and check that the original file is active.
  733. $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r1 . '/revert', array(), t('Revert'));
  734. $node = node_load($nid, NULL, TRUE);
  735. $node_file_r4 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  736. $node_vid_r4 = $node->vid;
  737. $this->assertEqual($node_file_r1, $node_file_r4, 'Original revision file still in place after reverting to the original revision.');
  738. $this->assertFileIsPermanent($node_file_r4, 'Original revision file still permanent after reverting to the original revision.');
  739. // Delete the second revision and check that the file is kept (since it is
  740. // still being used by the third revision).
  741. $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r2 . '/delete', array(), t('Delete'));
  742. $this->assertFileExists($node_file_r3, 'Second file is still available after deleting second revision, since it is being used by the third revision.');
  743. $this->assertFileEntryExists($node_file_r3, 'Second file entry is still available after deleting second revision, since it is being used by the third revision.');
  744. $this->assertFileIsPermanent($node_file_r3, 'Second file entry is still permanent after deleting second revision, since it is being used by the third revision.');
  745. // Attach the second file to a user.
  746. $user = $this->drupalCreateUser();
  747. $edit = (array) $user;
  748. $edit[$field_name][LANGUAGE_NONE][0] = (array) $node_file_r3;
  749. user_save($user, $edit);
  750. $this->drupalGet('user/' . $user->uid . '/edit');
  751. // Delete the third revision and check that the file is not deleted yet.
  752. $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r3 . '/delete', array(), t('Delete'));
  753. $this->assertFileExists($node_file_r3, 'Second file is still available after deleting third revision, since it is being used by the user.');
  754. $this->assertFileEntryExists($node_file_r3, 'Second file entry is still available after deleting third revision, since it is being used by the user.');
  755. $this->assertFileIsPermanent($node_file_r3, 'Second file entry is still permanent after deleting third revision, since it is being used by the user.');
  756. // Delete the user and check that the file is also deleted.
  757. user_delete($user->uid);
  758. // TODO: This seems like a bug in File API. Clearing the stat cache should
  759. // not be necessary here. The file really is deleted, but stream wrappers
  760. // doesn't seem to think so unless we clear the PHP file stat() cache.
  761. clearstatcache();
  762. $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.');
  763. $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.');
  764. // Delete the entire node and check that the original file is deleted.
  765. $this->drupalPost('node/' . $nid . '/delete', array(), t('Delete'));
  766. $this->assertFileNotExists($node_file_r1, 'Original file is deleted after deleting the entire node with two revisions remaining.');
  767. $this->assertFileEntryNotExists($node_file_r1, 'Original file entry is deleted after deleting the entire node with two revisions remaining.');
  768. }
  769. }
  770. /**
  771. * Tests that formatters are working properly.
  772. */
  773. class FileFieldDisplayTestCase extends FileFieldTestCase {
  774. public static function getInfo() {
  775. return array(
  776. 'name' => 'File field display tests',
  777. 'description' => 'Test the display of file fields in node and views.',
  778. 'group' => 'File',
  779. );
  780. }
  781. /**
  782. * Tests normal formatter display on node display.
  783. */
  784. function testNodeDisplay() {
  785. $field_name = strtolower($this->randomName());
  786. $type_name = 'article';
  787. $field_settings = array(
  788. 'display_field' => '1',
  789. 'display_default' => '1',
  790. 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  791. );
  792. $instance_settings = array(
  793. 'description_field' => '1',
  794. );
  795. $widget_settings = array();
  796. $this->createFileField($field_name, $type_name, $field_settings, $instance_settings, $widget_settings);
  797. $field = field_info_field($field_name);
  798. $instance = field_info_instance('node', $field_name, $type_name);
  799. // Create a new node *without* the file field set, and check that the field
  800. // is not shown for each node display.
  801. $node = $this->drupalCreateNode(array('type' => $type_name));
  802. $file_formatters = array('file_default', 'file_table', 'file_url_plain', 'hidden');
  803. foreach ($file_formatters as $formatter) {
  804. $edit = array(
  805. "fields[$field_name][type]" => $formatter,
  806. );
  807. $this->drupalPost("admin/structure/types/manage/$type_name/display", $edit, t('Save'));
  808. $this->drupalGet('node/' . $node->nid);
  809. $this->assertNoText($field_name, format_string('Field label is hidden when no file attached for formatter %formatter', array('%formatter' => $formatter)));
  810. }
  811. $test_file = $this->getTestFile('text');
  812. // Create a new node with the uploaded file.
  813. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  814. $this->drupalGet('node/' . $nid . '/edit');
  815. // Check that the default formatter is displaying with the file name.
  816. $node = node_load($nid, NULL, TRUE);
  817. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  818. $default_output = theme('file_link', array('file' => $node_file));
  819. $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
  820. // Turn the "display" option off and check that the file is no longer displayed.
  821. $edit = array($field_name . '[' . LANGUAGE_NONE . '][0][display]' => FALSE);
  822. $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
  823. $this->assertNoRaw($default_output, 'Field is hidden when "display" option is unchecked.');
  824. // Test that fields appear as expected during the preview.
  825. // Add a second file.
  826. $name = 'files[' . $field_name . '_' . LANGUAGE_NONE . '_1]';
  827. $edit[$name] = drupal_realpath($test_file->uri);
  828. // Uncheck the display checkboxes and go to the preview.
  829. $edit[$field_name . '[' . LANGUAGE_NONE . '][0][display]'] = FALSE;
  830. $edit[$field_name . '[' . LANGUAGE_NONE . '][1][display]'] = FALSE;
  831. $this->drupalPost('node/' . $nid . '/edit', $edit, t('Preview'));
  832. $this->assertRaw($field_name . '[' . LANGUAGE_NONE . '][0][display]', 'First file appears as expected.');
  833. $this->assertRaw($field_name . '[' . LANGUAGE_NONE . '][1][display]', 'Second file appears as expected.');
  834. }
  835. }
  836. /**
  837. * Tests various validations.
  838. */
  839. class FileFieldValidateTestCase extends FileFieldTestCase {
  840. protected $field;
  841. protected $node_type;
  842. public static function getInfo() {
  843. return array(
  844. 'name' => 'File field validation tests',
  845. 'description' => 'Tests validation functions such as file type, max file size, max size per node, and required.',
  846. 'group' => 'File',
  847. );
  848. }
  849. /**
  850. * Tests the required property on file fields.
  851. */
  852. function testRequired() {
  853. $type_name = 'article';
  854. $field_name = strtolower($this->randomName());
  855. $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
  856. $field = field_info_field($field_name);
  857. $instance = field_info_instance('node', $field_name, $type_name);
  858. $test_file = $this->getTestFile('text');
  859. // Try to post a new node without uploading a file.
  860. $langcode = LANGUAGE_NONE;
  861. $edit = array("title" => $this->randomName());
  862. $this->drupalPost('node/add/' . $type_name, $edit, t('Save'));
  863. $this->assertRaw(t('!title field is required.', array('!title' => $instance['label'])), 'Node save failed when required file field was empty.');
  864. // Create a new node with the uploaded file.
  865. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  866. $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)));
  867. $node = node_load($nid, NULL, TRUE);
  868. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  869. $this->assertFileExists($node_file, 'File exists after uploading to the required field.');
  870. $this->assertFileEntryExists($node_file, 'File entry exists after uploading to the required field.');
  871. // Try again with a multiple value field.
  872. field_delete_field($field_name);
  873. $this->createFileField($field_name, $type_name, array('cardinality' => FIELD_CARDINALITY_UNLIMITED), array('required' => '1'));
  874. // Try to post a new node without uploading a file in the multivalue field.
  875. $edit = array('title' => $this->randomName());
  876. $this->drupalPost('node/add/' . $type_name, $edit, t('Save'));
  877. $this->assertRaw(t('!title field is required.', array('!title' => $instance['label'])), 'Node save failed when required multiple value file field was empty.');
  878. // Create a new node with the uploaded file into the multivalue field.
  879. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  880. $node = node_load($nid, NULL, TRUE);
  881. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  882. $this->assertFileExists($node_file, 'File exists after uploading to the required multiple value field.');
  883. $this->assertFileEntryExists($node_file, 'File entry exists after uploading to the required multipel value field.');
  884. // Remove our file field.
  885. field_delete_field($field_name);
  886. }
  887. /**
  888. * Tests the max file size validator.
  889. */
  890. function testFileMaxSize() {
  891. $type_name = 'article';
  892. $field_name = strtolower($this->randomName());
  893. $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
  894. $field = field_info_field($field_name);
  895. $instance = field_info_instance('node', $field_name, $type_name);
  896. $small_file = $this->getTestFile('text', 131072); // 128KB.
  897. $large_file = $this->getTestFile('text', 1310720); // 1.2MB
  898. // Test uploading both a large and small file with different increments.
  899. $sizes = array(
  900. '1M' => 1048576,
  901. '1024K' => 1048576,
  902. '1048576' => 1048576,
  903. );
  904. foreach ($sizes as $max_filesize => $file_limit) {
  905. // Set the max file upload size.
  906. $this->updateFileField($field_name, $type_name, array('max_filesize' => $max_filesize));
  907. $instance = field_info_instance('node', $field_name, $type_name);
  908. // Create a new node with the small file, which should pass.
  909. $nid = $this->uploadNodeFile($small_file, $field_name, $type_name);
  910. $node = node_load($nid, NULL, TRUE);
  911. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  912. $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)));
  913. $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)));
  914. // Check that uploading the large file fails (1M limit).
  915. $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
  916. $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)));
  917. $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)));
  918. }
  919. // Turn off the max filesize.
  920. $this->updateFileField($field_name, $type_name, array('max_filesize' => ''));
  921. // Upload the big file successfully.
  922. $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
  923. $node = node_load($nid, NULL, TRUE);
  924. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  925. $this->assertFileExists($node_file, format_string('File exists after uploading a file (%filesize) with no max limit.', array('%filesize' => format_size($large_file->filesize))));
  926. $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))));
  927. // Remove our file field.
  928. field_delete_field($field_name);
  929. }
  930. /**
  931. * Tests file extension checking.
  932. */
  933. function testFileExtension() {
  934. $type_name = 'article';
  935. $field_name = strtolower($this->randomName());
  936. $this->createFileField($field_name, $type_name);
  937. $field = field_info_field($field_name);
  938. $instance = field_info_instance('node', $field_name, $type_name);
  939. $test_file = $this->getTestFile('image');
  940. list(, $test_file_extension) = explode('.', $test_file->filename);
  941. // Disable extension checking.
  942. $this->updateFileField($field_name, $type_name, array('file_extensions' => ''));
  943. // Check that the file can be uploaded with no extension checking.
  944. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  945. $node = node_load($nid, NULL, TRUE);
  946. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  947. $this->assertFileExists($node_file, 'File exists after uploading a file with no extension checking.');
  948. $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with no extension checking.');
  949. // Enable extension checking for text files.
  950. $this->updateFileField($field_name, $type_name, array('file_extensions' => 'txt'));
  951. // Check that the file with the wrong extension cannot be uploaded.
  952. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  953. $error_message = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => 'txt'));
  954. $this->assertRaw($error_message, 'Node save failed when file uploaded with the wrong extension.');
  955. // Enable extension checking for text and image files.
  956. $this->updateFileField($field_name, $type_name, array('file_extensions' => "txt $test_file_extension"));
  957. // Check that the file can be uploaded with extension checking.
  958. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  959. $node = node_load($nid, NULL, TRUE);
  960. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  961. $this->assertFileExists($node_file, 'File exists after uploading a file with extension checking.');
  962. $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with extension checking.');
  963. // Remove our file field.
  964. field_delete_field($field_name);
  965. }
  966. }
  967. /**
  968. * Tests that files are uploaded to proper locations.
  969. */
  970. class FileFieldPathTestCase extends FileFieldTestCase {
  971. public static function getInfo() {
  972. return array(
  973. 'name' => 'File field file path tests',
  974. 'description' => 'Test that files are uploaded to the proper location with token support.',
  975. 'group' => 'File',
  976. );
  977. }
  978. /**
  979. * Tests the normal formatter display on node display.
  980. */
  981. function testUploadPath() {
  982. $field_name = strtolower($this->randomName());
  983. $type_name = 'article';
  984. $field = $this->createFileField($field_name, $type_name);
  985. $test_file = $this->getTestFile('text');
  986. // Create a new node.
  987. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  988. // Check that the file was uploaded to the file root.
  989. $node = node_load($nid, NULL, TRUE);
  990. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  991. $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)));
  992. // Change the path to contain multiple subdirectories.
  993. $field = $this->updateFileField($field_name, $type_name, array('file_directory' => 'foo/bar/baz'));
  994. // Upload a new file into the subdirectories.
  995. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  996. // Check that the file was uploaded into the subdirectory.
  997. $node = node_load($nid, NULL, TRUE);
  998. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  999. $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)));
  1000. // Check the path when used with tokens.
  1001. // Change the path to contain multiple token directories.
  1002. $field = $this->updateFileField($field_name, $type_name, array('file_directory' => '[current-user:uid]/[current-user:name]'));
  1003. // Upload a new file into the token subdirectories.
  1004. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  1005. // Check that the file was uploaded into the subdirectory.
  1006. $node = node_load($nid, NULL, TRUE);
  1007. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  1008. // Do token replacement using the same user which uploaded the file, not
  1009. // the user running the test case.
  1010. $data = array('user' => $this->admin_user);
  1011. $subdirectory = token_replace('[user:uid]/[user:name]', $data);
  1012. $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)));
  1013. }
  1014. /**
  1015. * Asserts that a file is uploaded to the right location.
  1016. *
  1017. * @param $expected_path
  1018. * The location where the file is expected to be uploaded. Duplicate file
  1019. * names to not need to be taken into account.
  1020. * @param $actual_path
  1021. * Where the file was actually uploaded.
  1022. * @param $message
  1023. * The message to display with this assertion.
  1024. */
  1025. function assertPathMatch($expected_path, $actual_path, $message) {
  1026. // Strip off the extension of the expected path to allow for _0, _1, etc.
  1027. // suffixes when the file hits a duplicate name.
  1028. $pos = strrpos($expected_path, '.');
  1029. $base_path = substr($expected_path, 0, $pos);
  1030. $extension = substr($expected_path, $pos + 1);
  1031. $result = preg_match('/' . preg_quote($base_path, '/') . '(_[0-9]+)?\.' . preg_quote($extension, '/') . '/', $actual_path);
  1032. $this->assertTrue($result, $message);
  1033. }
  1034. }
  1035. /**
  1036. * Tests the file token replacement in strings.
  1037. */
  1038. class FileTokenReplaceTestCase extends FileFieldTestCase {
  1039. public static function getInfo() {
  1040. return array(
  1041. 'name' => 'File token replacement',
  1042. 'description' => 'Generates text using placeholders for dummy content to check file token replacement.',
  1043. 'group' => 'File',
  1044. );
  1045. }
  1046. /**
  1047. * Creates a file, then tests the tokens generated from it.
  1048. */
  1049. function testFileTokenReplacement() {
  1050. global $language;
  1051. $url_options = array(
  1052. 'absolute' => TRUE,
  1053. 'language' => $language,
  1054. );
  1055. // Create file field.
  1056. $type_name = 'article';
  1057. $field_name = 'field_' . strtolower($this->randomName());
  1058. $this->createFileField($field_name, $type_name);
  1059. $field = field_info_field($field_name);
  1060. $instance = field_info_instance('node', $field_name, $type_name);
  1061. $test_file = $this->getTestFile('text');
  1062. // Coping a file to test uploads with non-latin filenames.
  1063. $filename = drupal_dirname($test_file->uri) . '/текстовый файл.txt';
  1064. $test_file = file_copy($test_file, $filename);
  1065. // Create a new node with the uploaded file.
  1066. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  1067. // Load the node and the file.
  1068. $node = node_load($nid, NULL, TRUE);
  1069. $file = file_load($node->{$field_name}[LANGUAGE_NONE][0]['fid']);
  1070. // Generate and test sanitized tokens.
  1071. $tests = array();
  1072. $tests['[file:fid]'] = $file->fid;
  1073. $tests['[file:name]'] = check_plain($file->filename);
  1074. $tests['[file:path]'] = check_plain($file->uri);
  1075. $tests['[file:mime]'] = check_plain($file->filemime);
  1076. $tests['[file:size]'] = format_size($file->filesize);
  1077. $tests['[file:url]'] = check_plain(file_create_url($file->uri));
  1078. $tests['[file:timestamp]'] = format_date($file->timestamp, 'medium', '', NULL, $language->language);
  1079. $tests['[file:timestamp:short]'] = format_date($file->timestamp, 'short', '', NULL, $language->language);
  1080. $tests['[file:owner]'] = check_plain(format_username($this->admin_user));
  1081. $tests['[file:owner:uid]'] = $file->uid;
  1082. // Test to make sure that we generated something for each token.
  1083. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
  1084. foreach ($tests as $input => $expected) {
  1085. $output = token_replace($input, array('file' => $file), array('language' => $language));
  1086. $this->assertEqual($output, $expected, format_string('Sanitized file token %token replaced.', array('%token' => $input)));
  1087. }
  1088. // Generate and test unsanitized tokens.
  1089. $tests['[file:name]'] = $file->filename;
  1090. $tests['[file:path]'] = $file->uri;
  1091. $tests['[file:mime]'] = $file->filemime;
  1092. $tests['[file:size]'] = format_size($file->filesize);
  1093. foreach ($tests as $input => $expected) {
  1094. $output = token_replace($input, array('file' => $file), array('language' => $language, 'sanitize' => FALSE));
  1095. $this->assertEqual($output, $expected, format_string('Unsanitized file token %token replaced.', array('%token' => $input)));
  1096. }
  1097. }
  1098. }
  1099. /**
  1100. * Tests file access on private nodes.
  1101. */
  1102. class FilePrivateTestCase extends FileFieldTestCase {
  1103. public static function getInfo() {
  1104. return array(
  1105. 'name' => 'Private file test',
  1106. 'description' => 'Uploads a test to a private node and checks access.',
  1107. 'group' => 'File',
  1108. );
  1109. }
  1110. function setUp() {
  1111. parent::setUp(array('node_access_test', 'field_test'));
  1112. node_access_rebuild();
  1113. variable_set('node_access_test_private', TRUE);
  1114. }
  1115. /**
  1116. * Tests file access for file uploaded to a private node.
  1117. */
  1118. function testPrivateFile() {
  1119. // Use 'page' instead of 'article', so that the 'article' image field does
  1120. // not conflict with this test. If in the future the 'page' type gets its
  1121. // own default file or image field, this test can be made more robust by
  1122. // using a custom node type.
  1123. $type_name = 'page';
  1124. $field_name = strtolower($this->randomName());
  1125. $this->createFileField($field_name, $type_name, array('uri_scheme' => 'private'));
  1126. // Create a field with no view access - see field_test_field_access().
  1127. $no_access_field_name = 'field_no_view_access';
  1128. $this->createFileField($no_access_field_name, $type_name, array('uri_scheme' => 'private'));
  1129. $test_file = $this->getTestFile('text');
  1130. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name, TRUE, array('private' => TRUE));
  1131. $node = node_load($nid, NULL, TRUE);
  1132. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  1133. // Ensure the file can be downloaded.
  1134. $this->drupalGet(file_create_url($node_file->uri));
  1135. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
  1136. $this->drupalLogOut();
  1137. $this->drupalGet(file_create_url($node_file->uri));
  1138. $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
  1139. // Test with the field that should deny access through field access.
  1140. $this->drupalLogin($this->admin_user);
  1141. $nid = $this->uploadNodeFile($test_file, $no_access_field_name, $type_name, TRUE, array('private' => TRUE));
  1142. $node = node_load($nid, NULL, TRUE);
  1143. $node_file = (object) $node->{$no_access_field_name}[LANGUAGE_NONE][0];
  1144. // Ensure the file cannot be downloaded.
  1145. $this->drupalGet(file_create_url($node_file->uri));
  1146. $this->assertResponse(403, 'Confirmed that access is denied for the file without view field access permission.');
  1147. // Attempt to reuse the existing file when creating a new node, and confirm
  1148. // that access is still denied.
  1149. $edit = array();
  1150. $edit['title'] = $this->randomName(8);
  1151. $edit[$field_name . '[' . LANGUAGE_NONE . '][0][fid]'] = $node_file->fid;
  1152. $this->drupalPost('node/add/page', $edit, t('Save'));
  1153. $new_node = $this->drupalGetNodeByTitle($edit['title']);
  1154. $this->assertTrue(!empty($new_node), 'Node was created.');
  1155. $this->assertUrl('node/' . $new_node->nid);
  1156. $this->assertNoRaw($node_file->filename, 'File without view field access permission does not appear after attempting to attach it to a new node.');
  1157. $this->drupalGet(file_create_url($node_file->uri));
  1158. $this->assertResponse(403, 'Confirmed that access is denied for the file without view field access permission after attempting to attach it to a new node.');
  1159. }
  1160. }