file.test 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505
  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. * 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. }