file.test 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306
  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. // Ensure the file can be downloaded.
  432. $this->drupalGet(file_create_url($node_file->uri));
  433. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
  434. // Ensure the edit page has a remove button instead of an upload button.
  435. $this->drupalGet("node/$nid/edit");
  436. $this->assertNoFieldByXPath('//input[@type="submit"]', t('Upload'), 'Node with file does not display the "Upload" button.');
  437. $this->assertFieldByXpath('//input[@type="submit"]', t('Remove'), 'Node with file displays the "Remove" button.');
  438. // "Click" the remove button (emulating either a nojs or js submission).
  439. switch ($type) {
  440. case 'nojs':
  441. $this->drupalPost(NULL, array(), t('Remove'));
  442. break;
  443. case 'js':
  444. $button = $this->xpath('//input[@type="submit" and @value="' . t('Remove') . '"]');
  445. $this->drupalPostAJAX(NULL, array(), array((string) $button[0]['name'] => (string) $button[0]['value']));
  446. break;
  447. }
  448. // Ensure the page now has an upload button instead of a remove button.
  449. $this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), 'After clicking the "Remove" button, it is no longer displayed.');
  450. $this->assertFieldByXpath('//input[@type="submit"]', t('Upload'), 'After clicking the "Remove" button, the "Upload" button is displayed.');
  451. // Save the node and ensure it does not have the file.
  452. $this->drupalPost(NULL, array(), t('Save'));
  453. $node = node_load($nid, NULL, TRUE);
  454. $this->assertTrue(empty($node->{$field_name}[LANGUAGE_NONE][0]['fid']), 'File was successfully removed from the node.');
  455. }
  456. }
  457. /**
  458. * Tests upload and remove buttons for multiple multi-valued File fields.
  459. */
  460. function testMultiValuedWidget() {
  461. // Use 'page' instead of 'article', so that the 'article' image field does
  462. // not conflict with this test. If in the future the 'page' type gets its
  463. // own default file or image field, this test can be made more robust by
  464. // using a custom node type.
  465. $type_name = 'page';
  466. $field_name = strtolower($this->randomName());
  467. $field_name2 = strtolower($this->randomName());
  468. $this->createFileField($field_name, $type_name, array('cardinality' => 3));
  469. $this->createFileField($field_name2, $type_name, array('cardinality' => 3));
  470. $field = field_info_field($field_name);
  471. $instance = field_info_instance('node', $field_name, $type_name);
  472. $field2 = field_info_field($field_name2);
  473. $instance2 = field_info_instance('node', $field_name2, $type_name);
  474. $test_file = $this->getTestFile('text');
  475. foreach (array('nojs', 'js') as $type) {
  476. // Visit the node creation form, and upload 3 files for each field. Since
  477. // the field has cardinality of 3, ensure the "Upload" button is displayed
  478. // until after the 3rd file, and after that, isn't displayed. Because
  479. // SimpleTest triggers the last button with a given name, so upload to the
  480. // second field first.
  481. // @todo This is only testing a non-Ajax upload, because drupalPostAJAX()
  482. // does not yet emulate jQuery's file upload.
  483. //
  484. $this->drupalGet("node/add/$type_name");
  485. foreach (array($field_name2, $field_name) as $each_field_name) {
  486. for ($delta = 0; $delta < 3; $delta++) {
  487. $edit = array('files[' . $each_field_name . '_' . LANGUAGE_NONE . '_' . $delta . ']' => drupal_realpath($test_file->uri));
  488. // If the Upload button doesn't exist, drupalPost() will automatically
  489. // fail with an assertion message.
  490. $this->drupalPost(NULL, $edit, t('Upload'));
  491. }
  492. }
  493. $this->assertNoFieldByXpath('//input[@type="submit"]', t('Upload'), 'After uploading 3 files for each field, the "Upload" button is no longer displayed.');
  494. $num_expected_remove_buttons = 6;
  495. foreach (array($field_name, $field_name2) as $current_field_name) {
  496. // How many uploaded files for the current field are remaining.
  497. $remaining = 3;
  498. // Test clicking each "Remove" button. For extra robustness, test them out
  499. // of sequential order. They are 0-indexed, and get renumbered after each
  500. // iteration, so array(1, 1, 0) means:
  501. // - First remove the 2nd file.
  502. // - Then remove what is then the 2nd file (was originally the 3rd file).
  503. // - Then remove the first file.
  504. foreach (array(1,1,0) as $delta) {
  505. // Ensure we have the expected number of Remove buttons, and that they
  506. // are numbered sequentially.
  507. $buttons = $this->xpath('//input[@type="submit" and @value="Remove"]');
  508. $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)));
  509. foreach ($buttons as $i => $button) {
  510. $key = $i >= $remaining ? $i - $remaining : $i;
  511. $check_field_name = $field_name2;
  512. if ($current_field_name == $field_name && $i < $remaining) {
  513. $check_field_name = $field_name;
  514. }
  515. $this->assertIdentical((string) $button['name'], $check_field_name . '_' . LANGUAGE_NONE . '_' . $key. '_remove_button');
  516. }
  517. // "Click" the remove button (emulating either a nojs or js submission).
  518. $button_name = $current_field_name . '_' . LANGUAGE_NONE . '_' . $delta . '_remove_button';
  519. switch ($type) {
  520. case 'nojs':
  521. // drupalPost() takes a $submit parameter that is the value of the
  522. // button whose click we want to emulate. Since we have multiple
  523. // buttons with the value "Remove", and want to control which one we
  524. // use, we change the value of the other ones to something else.
  525. // Since non-clicked buttons aren't included in the submitted POST
  526. // data, and since drupalPost() will result in $this being updated
  527. // with a newly rebuilt form, this doesn't cause problems.
  528. foreach ($buttons as $button) {
  529. if ($button['name'] != $button_name) {
  530. $button['value'] = 'DUMMY';
  531. }
  532. }
  533. $this->drupalPost(NULL, array(), t('Remove'));
  534. break;
  535. case 'js':
  536. // drupalPostAJAX() lets us target the button precisely, so we don't
  537. // require the workaround used above for nojs.
  538. $this->drupalPostAJAX(NULL, array(), array($button_name => t('Remove')));
  539. break;
  540. }
  541. $num_expected_remove_buttons--;
  542. $remaining--;
  543. // Ensure an "Upload" button for the current field is displayed with the
  544. // correct name.
  545. $upload_button_name = $current_field_name . '_' . LANGUAGE_NONE . '_' . $remaining . '_upload_button';
  546. $buttons = $this->xpath('//input[@type="submit" and @value="Upload" and @name=:name]', array(':name' => $upload_button_name));
  547. $this->assertTrue(is_array($buttons) && count($buttons) == 1, format_string('The upload button is displayed with the correct name (JSMode=%type).', array('%type' => $type)));
  548. // Ensure only at most one button per field is displayed.
  549. $buttons = $this->xpath('//input[@type="submit" and @value="Upload"]');
  550. $expected = $current_field_name == $field_name ? 1 : 2;
  551. $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)));
  552. }
  553. }
  554. // Ensure the page now has no Remove buttons.
  555. $this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), format_string('After removing all files, there is no "Remove" button displayed (JSMode=%type).', array('%type' => $type)));
  556. // Save the node and ensure it does not have any files.
  557. $this->drupalPost(NULL, array('title' => $this->randomName()), t('Save'));
  558. $matches = array();
  559. preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
  560. $nid = $matches[1];
  561. $node = node_load($nid, NULL, TRUE);
  562. $this->assertTrue(empty($node->{$field_name}[LANGUAGE_NONE][0]['fid']), 'Node was successfully saved without any files.');
  563. }
  564. }
  565. /**
  566. * Tests a file field with a "Private files" upload destination setting.
  567. */
  568. function testPrivateFileSetting() {
  569. // Use 'page' instead of 'article', so that the 'article' image field does
  570. // not conflict with this test. If in the future the 'page' type gets its
  571. // own default file or image field, this test can be made more robust by
  572. // using a custom node type.
  573. $type_name = 'page';
  574. $field_name = strtolower($this->randomName());
  575. $this->createFileField($field_name, $type_name);
  576. $field = field_info_field($field_name);
  577. $instance = field_info_instance('node', $field_name, $type_name);
  578. $test_file = $this->getTestFile('text');
  579. // Change the field setting to make its files private, and upload a file.
  580. $edit = array('field[settings][uri_scheme]' => 'private');
  581. $this->drupalPost("admin/structure/types/manage/$type_name/fields/$field_name", $edit, t('Save settings'));
  582. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  583. $node = node_load($nid, NULL, TRUE);
  584. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  585. $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
  586. // Ensure the private file is available to the user who uploaded it.
  587. $this->drupalGet(file_create_url($node_file->uri));
  588. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
  589. // Ensure we can't change 'uri_scheme' field settings while there are some
  590. // entities with uploaded files.
  591. $this->drupalGet("admin/structure/types/manage/$type_name/fields/$field_name");
  592. $this->assertFieldByXpath('//input[@id="edit-field-settings-uri-scheme-public" and @disabled="disabled"]', 'public', 'Upload destination setting disabled.');
  593. // Delete node and confirm that setting could be changed.
  594. node_delete($nid);
  595. $this->drupalGet("admin/structure/types/manage/$type_name/fields/$field_name");
  596. $this->assertFieldByXpath('//input[@id="edit-field-settings-uri-scheme-public" and not(@disabled)]', 'public', 'Upload destination setting enabled.');
  597. }
  598. /**
  599. * Tests that download restrictions on private files work on comments.
  600. */
  601. function testPrivateFileComment() {
  602. $user = $this->drupalCreateUser(array('access comments'));
  603. // Remove access comments permission from anon user.
  604. $edit = array(
  605. DRUPAL_ANONYMOUS_RID . '[access comments]' => FALSE,
  606. );
  607. $this->drupalPost('admin/people/permissions', $edit, t('Save permissions'));
  608. // Create a new field.
  609. $edit = array(
  610. 'fields[_add_new_field][label]' => $label = $this->randomName(),
  611. 'fields[_add_new_field][field_name]' => $name = strtolower($this->randomName()),
  612. 'fields[_add_new_field][type]' => 'file',
  613. 'fields[_add_new_field][widget_type]' => 'file_generic',
  614. );
  615. $this->drupalPost('admin/structure/types/manage/article/comment/fields', $edit, t('Save'));
  616. $edit = array('field[settings][uri_scheme]' => 'private');
  617. $this->drupalPost(NULL, $edit, t('Save field settings'));
  618. $this->drupalPost(NULL, array(), t('Save settings'));
  619. // Create node.
  620. $text_file = $this->getTestFile('text');
  621. $edit = array(
  622. 'title' => $this->randomName(),
  623. );
  624. $this->drupalPost('node/add/article', $edit, t('Save'));
  625. $node = $this->drupalGetNodeByTitle($edit['title']);
  626. // Add a comment with a file.
  627. $text_file = $this->getTestFile('text');
  628. $edit = array(
  629. 'files[field_' . $name . '_' . LANGUAGE_NONE . '_' . 0 . ']' => drupal_realpath($text_file->uri),
  630. 'comment_body[' . LANGUAGE_NONE . '][0][value]' => $comment_body = $this->randomName(),
  631. );
  632. $this->drupalPost(NULL, $edit, t('Save'));
  633. // Get the comment ID.
  634. preg_match('/comment-([0-9]+)/', $this->getUrl(), $matches);
  635. $cid = $matches[1];
  636. // Log in as normal user.
  637. $this->drupalLogin($user);
  638. $comment = comment_load($cid);
  639. $comment_file = (object) $comment->{'field_' . $name}[LANGUAGE_NONE][0];
  640. $this->assertFileExists($comment_file, 'New file saved to disk on node creation.');
  641. // Test authenticated file download.
  642. $url = file_create_url($comment_file->uri);
  643. $this->assertNotEqual($url, NULL, 'Confirmed that the URL is valid');
  644. $this->drupalGet(file_create_url($comment_file->uri));
  645. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
  646. // Test anonymous file download.
  647. $this->drupalLogout();
  648. $this->drupalGet(file_create_url($comment_file->uri));
  649. $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
  650. // Unpublishes node.
  651. $this->drupalLogin($this->admin_user);
  652. $edit = array(
  653. 'status' => FALSE,
  654. );
  655. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  656. // Ensures normal user can no longer download the file.
  657. $this->drupalLogin($user);
  658. $this->drupalGet(file_create_url($comment_file->uri));
  659. $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
  660. }
  661. }
  662. /**
  663. * Tests file handling with node revisions.
  664. */
  665. class FileFieldRevisionTestCase extends FileFieldTestCase {
  666. public static function getInfo() {
  667. return array(
  668. 'name' => 'File field revision test',
  669. 'description' => 'Test creating and deleting revisions with files attached.',
  670. 'group' => 'File',
  671. );
  672. }
  673. /**
  674. * Tests creating multiple revisions of a node and managing attached files.
  675. *
  676. * Expected behaviors:
  677. * - Adding a new revision will make another entry in the field table, but
  678. * the original file will not be duplicated.
  679. * - Deleting a revision should not delete the original file if the file
  680. * is in use by another revision.
  681. * - When the last revision that uses a file is deleted, the original file
  682. * should be deleted also.
  683. */
  684. function testRevisions() {
  685. $type_name = 'article';
  686. $field_name = strtolower($this->randomName());
  687. $this->createFileField($field_name, $type_name);
  688. $field = field_info_field($field_name);
  689. $instance = field_info_instance('node', $field_name, $type_name);
  690. // Attach the same fields to users.
  691. $this->attachFileField($field_name, 'user', 'user');
  692. $test_file = $this->getTestFile('text');
  693. // Create a new node with the uploaded file.
  694. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  695. // Check that the file exists on disk and in the database.
  696. $node = node_load($nid, NULL, TRUE);
  697. $node_file_r1 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  698. $node_vid_r1 = $node->vid;
  699. $this->assertFileExists($node_file_r1, 'New file saved to disk on node creation.');
  700. $this->assertFileEntryExists($node_file_r1, 'File entry exists in database on node creation.');
  701. $this->assertFileIsPermanent($node_file_r1, 'File is permanent.');
  702. // Upload another file to the same node in a new revision.
  703. $this->replaceNodeFile($test_file, $field_name, $nid);
  704. $node = node_load($nid, NULL, TRUE);
  705. $node_file_r2 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  706. $node_vid_r2 = $node->vid;
  707. $this->assertFileExists($node_file_r2, 'Replacement file exists on disk after creating new revision.');
  708. $this->assertFileEntryExists($node_file_r2, 'Replacement file entry exists in database after creating new revision.');
  709. $this->assertFileIsPermanent($node_file_r2, 'Replacement file is permanent.');
  710. // Check that the original file is still in place on the first revision.
  711. $node = node_load($nid, $node_vid_r1, TRUE);
  712. $this->assertEqual($node_file_r1, (object) $node->{$field_name}[LANGUAGE_NONE][0], 'Original file still in place after replacing file in new revision.');
  713. $this->assertFileExists($node_file_r1, 'Original file still in place after replacing file in new revision.');
  714. $this->assertFileEntryExists($node_file_r1, 'Original file entry still in place after replacing file in new revision');
  715. $this->assertFileIsPermanent($node_file_r1, 'Original file is still permanent.');
  716. // Save a new version of the node without any changes.
  717. // Check that the file is still the same as the previous revision.
  718. $this->drupalPost('node/' . $nid . '/edit', array('revision' => '1'), t('Save'));
  719. $node = node_load($nid, NULL, TRUE);
  720. $node_file_r3 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  721. $node_vid_r3 = $node->vid;
  722. $this->assertEqual($node_file_r2, $node_file_r3, 'Previous revision file still in place after creating a new revision without a new file.');
  723. $this->assertFileIsPermanent($node_file_r3, 'New revision file is permanent.');
  724. // Revert to the first revision and check that the original file is active.
  725. $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r1 . '/revert', array(), t('Revert'));
  726. $node = node_load($nid, NULL, TRUE);
  727. $node_file_r4 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  728. $node_vid_r4 = $node->vid;
  729. $this->assertEqual($node_file_r1, $node_file_r4, 'Original revision file still in place after reverting to the original revision.');
  730. $this->assertFileIsPermanent($node_file_r4, 'Original revision file still permanent after reverting to the original revision.');
  731. // Delete the second revision and check that the file is kept (since it is
  732. // still being used by the third revision).
  733. $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r2 . '/delete', array(), t('Delete'));
  734. $this->assertFileExists($node_file_r3, 'Second file is still available after deleting second revision, since it is being used by the third revision.');
  735. $this->assertFileEntryExists($node_file_r3, 'Second file entry is still available after deleting second revision, since it is being used by the third revision.');
  736. $this->assertFileIsPermanent($node_file_r3, 'Second file entry is still permanent after deleting second revision, since it is being used by the third revision.');
  737. // Attach the second file to a user.
  738. $user = $this->drupalCreateUser();
  739. $edit = (array) $user;
  740. $edit[$field_name][LANGUAGE_NONE][0] = (array) $node_file_r3;
  741. user_save($user, $edit);
  742. $this->drupalGet('user/' . $user->uid . '/edit');
  743. // Delete the third revision and check that the file is not deleted yet.
  744. $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r3 . '/delete', array(), t('Delete'));
  745. $this->assertFileExists($node_file_r3, 'Second file is still available after deleting third revision, since it is being used by the user.');
  746. $this->assertFileEntryExists($node_file_r3, 'Second file entry is still available after deleting third revision, since it is being used by the user.');
  747. $this->assertFileIsPermanent($node_file_r3, 'Second file entry is still permanent after deleting third revision, since it is being used by the user.');
  748. // Delete the user and check that the file is also deleted.
  749. user_delete($user->uid);
  750. // TODO: This seems like a bug in File API. Clearing the stat cache should
  751. // not be necessary here. The file really is deleted, but stream wrappers
  752. // doesn't seem to think so unless we clear the PHP file stat() cache.
  753. clearstatcache();
  754. $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.');
  755. $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.');
  756. // Delete the entire node and check that the original file is deleted.
  757. $this->drupalPost('node/' . $nid . '/delete', array(), t('Delete'));
  758. $this->assertFileNotExists($node_file_r1, 'Original file is deleted after deleting the entire node with two revisions remaining.');
  759. $this->assertFileEntryNotExists($node_file_r1, 'Original file entry is deleted after deleting the entire node with two revisions remaining.');
  760. }
  761. }
  762. /**
  763. * Tests that formatters are working properly.
  764. */
  765. class FileFieldDisplayTestCase extends FileFieldTestCase {
  766. public static function getInfo() {
  767. return array(
  768. 'name' => 'File field display tests',
  769. 'description' => 'Test the display of file fields in node and views.',
  770. 'group' => 'File',
  771. );
  772. }
  773. /**
  774. * Tests normal formatter display on node display.
  775. */
  776. function testNodeDisplay() {
  777. $field_name = strtolower($this->randomName());
  778. $type_name = 'article';
  779. $field_settings = array(
  780. 'display_field' => '1',
  781. 'display_default' => '1',
  782. );
  783. $instance_settings = array(
  784. 'description_field' => '1',
  785. );
  786. $widget_settings = array();
  787. $this->createFileField($field_name, $type_name, $field_settings, $instance_settings, $widget_settings);
  788. $field = field_info_field($field_name);
  789. $instance = field_info_instance('node', $field_name, $type_name);
  790. // Create a new node *without* the file field set, and check that the field
  791. // is not shown for each node display.
  792. $node = $this->drupalCreateNode(array('type' => $type_name));
  793. $file_formatters = array('file_default', 'file_table', 'file_url_plain', 'hidden');
  794. foreach ($file_formatters as $formatter) {
  795. $edit = array(
  796. "fields[$field_name][type]" => $formatter,
  797. );
  798. $this->drupalPost("admin/structure/types/manage/$type_name/display", $edit, t('Save'));
  799. $this->drupalGet('node/' . $node->nid);
  800. $this->assertNoText($field_name, format_string('Field label is hidden when no file attached for formatter %formatter', array('%formatter' => $formatter)));
  801. }
  802. $test_file = $this->getTestFile('text');
  803. // Create a new node with the uploaded file.
  804. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  805. $this->drupalGet('node/' . $nid . '/edit');
  806. // Check that the default formatter is displaying with the file name.
  807. $node = node_load($nid, NULL, TRUE);
  808. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  809. $default_output = theme('file_link', array('file' => $node_file));
  810. $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
  811. // Turn the "display" option off and check that the file is no longer displayed.
  812. $edit = array($field_name . '[' . LANGUAGE_NONE . '][0][display]' => FALSE);
  813. $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
  814. $this->assertNoRaw($default_output, 'Field is hidden when "display" option is unchecked.');
  815. }
  816. }
  817. /**
  818. * Tests various validations.
  819. */
  820. class FileFieldValidateTestCase extends FileFieldTestCase {
  821. protected $field;
  822. protected $node_type;
  823. public static function getInfo() {
  824. return array(
  825. 'name' => 'File field validation tests',
  826. 'description' => 'Tests validation functions such as file type, max file size, max size per node, and required.',
  827. 'group' => 'File',
  828. );
  829. }
  830. /**
  831. * Tests the required property on file fields.
  832. */
  833. function testRequired() {
  834. $type_name = 'article';
  835. $field_name = strtolower($this->randomName());
  836. $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
  837. $field = field_info_field($field_name);
  838. $instance = field_info_instance('node', $field_name, $type_name);
  839. $test_file = $this->getTestFile('text');
  840. // Try to post a new node without uploading a file.
  841. $langcode = LANGUAGE_NONE;
  842. $edit = array("title" => $this->randomName());
  843. $this->drupalPost('node/add/' . $type_name, $edit, t('Save'));
  844. $this->assertRaw(t('!title field is required.', array('!title' => $instance['label'])), 'Node save failed when required file field was empty.');
  845. // Create a new node with the uploaded file.
  846. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  847. $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)));
  848. $node = node_load($nid, NULL, TRUE);
  849. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  850. $this->assertFileExists($node_file, 'File exists after uploading to the required field.');
  851. $this->assertFileEntryExists($node_file, 'File entry exists after uploading to the required field.');
  852. // Try again with a multiple value field.
  853. field_delete_field($field_name);
  854. $this->createFileField($field_name, $type_name, array('cardinality' => FIELD_CARDINALITY_UNLIMITED), array('required' => '1'));
  855. // Try to post a new node without uploading a file in the multivalue field.
  856. $edit = array('title' => $this->randomName());
  857. $this->drupalPost('node/add/' . $type_name, $edit, t('Save'));
  858. $this->assertRaw(t('!title field is required.', array('!title' => $instance['label'])), 'Node save failed when required multiple value file field was empty.');
  859. // Create a new node with the uploaded file into the multivalue field.
  860. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  861. $node = node_load($nid, NULL, TRUE);
  862. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  863. $this->assertFileExists($node_file, 'File exists after uploading to the required multiple value field.');
  864. $this->assertFileEntryExists($node_file, 'File entry exists after uploading to the required multipel value field.');
  865. // Remove our file field.
  866. field_delete_field($field_name);
  867. }
  868. /**
  869. * Tests the max file size validator.
  870. */
  871. function testFileMaxSize() {
  872. $type_name = 'article';
  873. $field_name = strtolower($this->randomName());
  874. $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
  875. $field = field_info_field($field_name);
  876. $instance = field_info_instance('node', $field_name, $type_name);
  877. $small_file = $this->getTestFile('text', 131072); // 128KB.
  878. $large_file = $this->getTestFile('text', 1310720); // 1.2MB
  879. // Test uploading both a large and small file with different increments.
  880. $sizes = array(
  881. '1M' => 1048576,
  882. '1024K' => 1048576,
  883. '1048576' => 1048576,
  884. );
  885. foreach ($sizes as $max_filesize => $file_limit) {
  886. // Set the max file upload size.
  887. $this->updateFileField($field_name, $type_name, array('max_filesize' => $max_filesize));
  888. $instance = field_info_instance('node', $field_name, $type_name);
  889. // Create a new node with the small file, which should pass.
  890. $nid = $this->uploadNodeFile($small_file, $field_name, $type_name);
  891. $node = node_load($nid, NULL, TRUE);
  892. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  893. $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)));
  894. $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)));
  895. // Check that uploading the large file fails (1M limit).
  896. $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
  897. $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)));
  898. $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)));
  899. }
  900. // Turn off the max filesize.
  901. $this->updateFileField($field_name, $type_name, array('max_filesize' => ''));
  902. // Upload the big file successfully.
  903. $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
  904. $node = node_load($nid, NULL, TRUE);
  905. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  906. $this->assertFileExists($node_file, format_string('File exists after uploading a file (%filesize) with no max limit.', array('%filesize' => format_size($large_file->filesize))));
  907. $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))));
  908. // Remove our file field.
  909. field_delete_field($field_name);
  910. }
  911. /**
  912. * Tests file extension checking.
  913. */
  914. function testFileExtension() {
  915. $type_name = 'article';
  916. $field_name = strtolower($this->randomName());
  917. $this->createFileField($field_name, $type_name);
  918. $field = field_info_field($field_name);
  919. $instance = field_info_instance('node', $field_name, $type_name);
  920. $test_file = $this->getTestFile('image');
  921. list(, $test_file_extension) = explode('.', $test_file->filename);
  922. // Disable extension checking.
  923. $this->updateFileField($field_name, $type_name, array('file_extensions' => ''));
  924. // Check that the file can be uploaded with no extension checking.
  925. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  926. $node = node_load($nid, NULL, TRUE);
  927. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  928. $this->assertFileExists($node_file, 'File exists after uploading a file with no extension checking.');
  929. $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with no extension checking.');
  930. // Enable extension checking for text files.
  931. $this->updateFileField($field_name, $type_name, array('file_extensions' => 'txt'));
  932. // Check that the file with the wrong extension cannot be uploaded.
  933. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  934. $error_message = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => 'txt'));
  935. $this->assertRaw($error_message, 'Node save failed when file uploaded with the wrong extension.');
  936. // Enable extension checking for text and image files.
  937. $this->updateFileField($field_name, $type_name, array('file_extensions' => "txt $test_file_extension"));
  938. // Check that the file can be uploaded with extension checking.
  939. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  940. $node = node_load($nid, NULL, TRUE);
  941. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  942. $this->assertFileExists($node_file, 'File exists after uploading a file with extension checking.');
  943. $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with extension checking.');
  944. // Remove our file field.
  945. field_delete_field($field_name);
  946. }
  947. }
  948. /**
  949. * Tests that files are uploaded to proper locations.
  950. */
  951. class FileFieldPathTestCase extends FileFieldTestCase {
  952. public static function getInfo() {
  953. return array(
  954. 'name' => 'File field file path tests',
  955. 'description' => 'Test that files are uploaded to the proper location with token support.',
  956. 'group' => 'File',
  957. );
  958. }
  959. /**
  960. * Tests the normal formatter display on node display.
  961. */
  962. function testUploadPath() {
  963. $field_name = strtolower($this->randomName());
  964. $type_name = 'article';
  965. $field = $this->createFileField($field_name, $type_name);
  966. $test_file = $this->getTestFile('text');
  967. // Create a new node.
  968. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  969. // Check that the file was uploaded to the file root.
  970. $node = node_load($nid, NULL, TRUE);
  971. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  972. $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)));
  973. // Change the path to contain multiple subdirectories.
  974. $field = $this->updateFileField($field_name, $type_name, array('file_directory' => 'foo/bar/baz'));
  975. // Upload a new file into the subdirectories.
  976. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  977. // Check that the file was uploaded into the subdirectory.
  978. $node = node_load($nid, NULL, TRUE);
  979. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  980. $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)));
  981. // Check the path when used with tokens.
  982. // Change the path to contain multiple token directories.
  983. $field = $this->updateFileField($field_name, $type_name, array('file_directory' => '[current-user:uid]/[current-user:name]'));
  984. // Upload a new file into the token subdirectories.
  985. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  986. // Check that the file was uploaded into the subdirectory.
  987. $node = node_load($nid, NULL, TRUE);
  988. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  989. // Do token replacement using the same user which uploaded the file, not
  990. // the user running the test case.
  991. $data = array('user' => $this->admin_user);
  992. $subdirectory = token_replace('[user:uid]/[user:name]', $data);
  993. $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)));
  994. }
  995. /**
  996. * Asserts that a file is uploaded to the right location.
  997. *
  998. * @param $expected_path
  999. * The location where the file is expected to be uploaded. Duplicate file
  1000. * names to not need to be taken into account.
  1001. * @param $actual_path
  1002. * Where the file was actually uploaded.
  1003. * @param $message
  1004. * The message to display with this assertion.
  1005. */
  1006. function assertPathMatch($expected_path, $actual_path, $message) {
  1007. // Strip off the extension of the expected path to allow for _0, _1, etc.
  1008. // suffixes when the file hits a duplicate name.
  1009. $pos = strrpos($expected_path, '.');
  1010. $base_path = substr($expected_path, 0, $pos);
  1011. $extension = substr($expected_path, $pos + 1);
  1012. $result = preg_match('/' . preg_quote($base_path, '/') . '(_[0-9]+)?\.' . preg_quote($extension, '/') . '/', $actual_path);
  1013. $this->assertTrue($result, $message);
  1014. }
  1015. }
  1016. /**
  1017. * Tests the file token replacement in strings.
  1018. */
  1019. class FileTokenReplaceTestCase extends FileFieldTestCase {
  1020. public static function getInfo() {
  1021. return array(
  1022. 'name' => 'File token replacement',
  1023. 'description' => 'Generates text using placeholders for dummy content to check file token replacement.',
  1024. 'group' => 'File',
  1025. );
  1026. }
  1027. /**
  1028. * Creates a file, then tests the tokens generated from it.
  1029. */
  1030. function testFileTokenReplacement() {
  1031. global $language;
  1032. $url_options = array(
  1033. 'absolute' => TRUE,
  1034. 'language' => $language,
  1035. );
  1036. // Create file field.
  1037. $type_name = 'article';
  1038. $field_name = 'field_' . strtolower($this->randomName());
  1039. $this->createFileField($field_name, $type_name);
  1040. $field = field_info_field($field_name);
  1041. $instance = field_info_instance('node', $field_name, $type_name);
  1042. $test_file = $this->getTestFile('text');
  1043. // Coping a file to test uploads with non-latin filenames.
  1044. $filename = drupal_dirname($test_file->uri) . '/текстовый файл.txt';
  1045. $test_file = file_copy($test_file, $filename);
  1046. // Create a new node with the uploaded file.
  1047. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  1048. // Load the node and the file.
  1049. $node = node_load($nid, NULL, TRUE);
  1050. $file = file_load($node->{$field_name}[LANGUAGE_NONE][0]['fid']);
  1051. // Generate and test sanitized tokens.
  1052. $tests = array();
  1053. $tests['[file:fid]'] = $file->fid;
  1054. $tests['[file:name]'] = check_plain($file->filename);
  1055. $tests['[file:path]'] = check_plain($file->uri);
  1056. $tests['[file:mime]'] = check_plain($file->filemime);
  1057. $tests['[file:size]'] = format_size($file->filesize);
  1058. $tests['[file:url]'] = check_plain(file_create_url($file->uri));
  1059. $tests['[file:timestamp]'] = format_date($file->timestamp, 'medium', '', NULL, $language->language);
  1060. $tests['[file:timestamp:short]'] = format_date($file->timestamp, 'short', '', NULL, $language->language);
  1061. $tests['[file:owner]'] = check_plain(format_username($this->admin_user));
  1062. $tests['[file:owner:uid]'] = $file->uid;
  1063. // Test to make sure that we generated something for each token.
  1064. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
  1065. foreach ($tests as $input => $expected) {
  1066. $output = token_replace($input, array('file' => $file), array('language' => $language));
  1067. $this->assertEqual($output, $expected, format_string('Sanitized file token %token replaced.', array('%token' => $input)));
  1068. }
  1069. // Generate and test unsanitized tokens.
  1070. $tests['[file:name]'] = $file->filename;
  1071. $tests['[file:path]'] = $file->uri;
  1072. $tests['[file:mime]'] = $file->filemime;
  1073. $tests['[file:size]'] = format_size($file->filesize);
  1074. foreach ($tests as $input => $expected) {
  1075. $output = token_replace($input, array('file' => $file), array('language' => $language, 'sanitize' => FALSE));
  1076. $this->assertEqual($output, $expected, format_string('Unsanitized file token %token replaced.', array('%token' => $input)));
  1077. }
  1078. }
  1079. }
  1080. /**
  1081. * Tests file access on private nodes.
  1082. */
  1083. class FilePrivateTestCase extends FileFieldTestCase {
  1084. public static function getInfo() {
  1085. return array(
  1086. 'name' => 'Private file test',
  1087. 'description' => 'Uploads a test to a private node and checks access.',
  1088. 'group' => 'File',
  1089. );
  1090. }
  1091. function setUp() {
  1092. parent::setUp(array('node_access_test', 'field_test'));
  1093. node_access_rebuild();
  1094. variable_set('node_access_test_private', TRUE);
  1095. }
  1096. /**
  1097. * Tests file access for file uploaded to a private node.
  1098. */
  1099. function testPrivateFile() {
  1100. // Use 'page' instead of 'article', so that the 'article' image field does
  1101. // not conflict with this test. If in the future the 'page' type gets its
  1102. // own default file or image field, this test can be made more robust by
  1103. // using a custom node type.
  1104. $type_name = 'page';
  1105. $field_name = strtolower($this->randomName());
  1106. $this->createFileField($field_name, $type_name, array('uri_scheme' => 'private'));
  1107. // Create a field with no view access - see field_test_field_access().
  1108. $no_access_field_name = 'field_no_view_access';
  1109. $this->createFileField($no_access_field_name, $type_name, array('uri_scheme' => 'private'));
  1110. $test_file = $this->getTestFile('text');
  1111. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name, TRUE, array('private' => TRUE));
  1112. $node = node_load($nid, NULL, TRUE);
  1113. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  1114. // Ensure the file can be downloaded.
  1115. $this->drupalGet(file_create_url($node_file->uri));
  1116. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
  1117. $this->drupalLogOut();
  1118. $this->drupalGet(file_create_url($node_file->uri));
  1119. $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
  1120. // Test with the field that should deny access through field access.
  1121. $this->drupalLogin($this->admin_user);
  1122. $nid = $this->uploadNodeFile($test_file, $no_access_field_name, $type_name, TRUE, array('private' => TRUE));
  1123. $node = node_load($nid, NULL, TRUE);
  1124. $node_file = (object) $node->{$no_access_field_name}[LANGUAGE_NONE][0];
  1125. // Ensure the file cannot be downloaded.
  1126. $this->drupalGet(file_create_url($node_file->uri));
  1127. $this->assertResponse(403, 'Confirmed that access is denied for the file without view field access permission.');
  1128. // Attempt to reuse the existing file when creating a new node, and confirm
  1129. // that access is still denied.
  1130. $edit = array();
  1131. $edit['title'] = $this->randomName(8);
  1132. $edit[$field_name . '[' . LANGUAGE_NONE . '][0][fid]'] = $node_file->fid;
  1133. $this->drupalPost('node/add/page', $edit, t('Save'));
  1134. $new_node = $this->drupalGetNodeByTitle($edit['title']);
  1135. $this->assertTrue(!empty($new_node), 'Node was created.');
  1136. $this->assertUrl('node/' . $new_node->nid);
  1137. $this->assertNoRaw($node_file->filename, 'File without view field access permission does not appear after attempting to attach it to a new node.');
  1138. $this->drupalGet(file_create_url($node_file->uri));
  1139. $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.');
  1140. }
  1141. }