file.test 72 KB

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