file.test 60 KB

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