file.test 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934
  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. * Tests validation with the Upload button.
  536. */
  537. function testWidgetValidation() {
  538. $type_name = 'article';
  539. $field_name = strtolower($this->randomName());
  540. $this->createFileField($field_name, $type_name);
  541. $this->updateFileField($field_name, $type_name, array('file_extensions' => 'txt'));
  542. foreach (array('nojs', 'js') as $type) {
  543. // Create node and prepare files for upload.
  544. $node = $this->drupalCreateNode(array('type' => 'article'));
  545. $nid = $node->nid;
  546. $this->drupalGet("node/$nid/edit");
  547. $test_file_text = $this->getTestFile('text');
  548. $test_file_image = $this->getTestFile('image');
  549. $field = field_info_field($field_name);
  550. $name = 'files[' . $field_name . '_' . LANGUAGE_NONE . '_0]';
  551. // Upload file with incorrect extension, check for validation error.
  552. $edit[$name] = drupal_realpath($test_file_image->uri);
  553. switch ($type) {
  554. case 'nojs':
  555. $this->drupalPost(NULL, $edit, t('Upload'));
  556. break;
  557. case 'js':
  558. $button = $this->xpath('//input[@type="submit" and @value="' . t('Upload') . '"]');
  559. $this->drupalPostAJAX(NULL, $edit, array((string) $button[0]['name'] => (string) $button[0]['value']));
  560. break;
  561. }
  562. $error_message = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => 'txt'));
  563. $this->assertRaw($error_message, t('Validation error when file with wrong extension uploaded (JSMode=%type).', array('%type' => $type)));
  564. // Upload file with correct extension, check that error message is removed.
  565. $edit[$name] = drupal_realpath($test_file_text->uri);
  566. switch ($type) {
  567. case 'nojs':
  568. $this->drupalPost(NULL, $edit, t('Upload'));
  569. break;
  570. case 'js':
  571. $button = $this->xpath('//input[@type="submit" and @value="' . t('Upload') . '"]');
  572. $this->drupalPostAJAX(NULL, $edit, array((string) $button[0]['name'] => (string) $button[0]['value']));
  573. break;
  574. }
  575. $this->assertNoRaw($error_message, t('Validation error removed when file with correct extension uploaded (JSMode=%type).', array('%type' => $type)));
  576. }
  577. }
  578. /**
  579. * Helper for testing exploiting the temporary file removal using fid.
  580. *
  581. * @param int $victim_uid
  582. * The victim user ID.
  583. * @param int $attacker_uid
  584. * The attacker user ID.
  585. */
  586. protected function doTestTemporaryFileRemovalExploit($victim_uid, $attacker_uid) {
  587. // Use 'page' instead of 'article', so that the 'article' image field does
  588. // not conflict with this test. If in the future the 'page' type gets its
  589. // own default file or image field, this test can be made more robust by
  590. // using a custom node type.
  591. $type_name = 'page';
  592. $field_name = 'test_file_field';
  593. $this->createFileField($field_name, $type_name);
  594. $test_file = $this->getTestFile('text');
  595. foreach (array('nojs', 'js') as $type) {
  596. // Create a temporary file owned by the anonymous victim user. This will be
  597. // as if they had uploaded the file, but not saved the node they were
  598. // editing or creating.
  599. $victim_tmp_file = $this->createTemporaryFile('some text', $victim_uid);
  600. $victim_tmp_file = file_load($victim_tmp_file->fid);
  601. $this->assertTrue($victim_tmp_file->status != FILE_STATUS_PERMANENT, 'New file saved to disk is temporary.');
  602. $this->assertFalse(empty($victim_tmp_file->fid), 'New file has a fid');
  603. $this->assertEqual($victim_uid, $victim_tmp_file->uid, 'New file belongs to the victim user');
  604. // Have attacker create a new node with a different uploaded file and
  605. // ensure it got uploaded successfully.
  606. // @todo Can we test AJAX? See https://www.drupal.org/node/2538260
  607. $edit = array(
  608. 'title' => $type . '-title',
  609. );
  610. // Attach a file to a node.
  611. $langcode = LANGUAGE_NONE;
  612. $edit['files[' . $field_name . '_' . $langcode . '_0]'] = drupal_realpath($test_file->uri);
  613. $this->drupalPost("node/add/$type_name", $edit, 'Save');
  614. $node = $this->drupalGetNodeByTitle($edit['title']);
  615. $node_file = file_load($node->{$field_name}[$langcode][0]['fid']);
  616. $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
  617. $this->assertEqual($attacker_uid, $node_file->uid, 'New file belongs to the attacker.');
  618. // Ensure the file can be downloaded.
  619. $this->drupalGet(file_create_url($node_file->uri));
  620. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
  621. // "Click" the remove button (emulating either a nojs or js submission).
  622. // In this POST request, the attacker "guesses" the fid of the victim's
  623. // temporary file and uses that to remove this file.
  624. $this->drupalGet('node/' . $node->nid . '/edit');
  625. switch ($type) {
  626. case 'nojs':
  627. $this->drupalPost(NULL, array("{$field_name}[$langcode][0][fid]" => (string) $victim_tmp_file->fid), 'Remove');
  628. break;
  629. case 'js':
  630. $button = $this->xpath('//input[@type="submit" and @value="Remove"]');
  631. $this->drupalPostAJAX(NULL, array("{$field_name}[$langcode][0][fid]" => (string) $victim_tmp_file->fid), array((string) $button[0]['name'] => (string) $button[0]['value']));
  632. break;
  633. }
  634. // The victim's temporary file should not be removed by the attacker's
  635. // POST request.
  636. $this->assertFileExists($victim_tmp_file);
  637. }
  638. }
  639. /**
  640. * Tests upload and remove buttons for multiple multi-valued File fields.
  641. */
  642. function testMultiValuedWidget() {
  643. // Use 'page' instead of 'article', so that the 'article' image field does
  644. // not conflict with this test. If in the future the 'page' type gets its
  645. // own default file or image field, this test can be made more robust by
  646. // using a custom node type.
  647. $type_name = 'page';
  648. $field_name = strtolower($this->randomName());
  649. $field_name2 = strtolower($this->randomName());
  650. $this->createFileField($field_name, $type_name, array('cardinality' => 3));
  651. $this->createFileField($field_name2, $type_name, array('cardinality' => 3));
  652. $field = field_info_field($field_name);
  653. $instance = field_info_instance('node', $field_name, $type_name);
  654. $field2 = field_info_field($field_name2);
  655. $instance2 = field_info_instance('node', $field_name2, $type_name);
  656. $test_file = $this->getTestFile('text');
  657. foreach (array('nojs', 'js') as $type) {
  658. // Visit the node creation form, and upload 3 files for each field. Since
  659. // the field has cardinality of 3, ensure the "Upload" button is displayed
  660. // until after the 3rd file, and after that, isn't displayed. Because
  661. // SimpleTest triggers the last button with a given name, so upload to the
  662. // second field first.
  663. // @todo This is only testing a non-Ajax upload, because drupalPostAJAX()
  664. // does not yet emulate jQuery's file upload.
  665. //
  666. $this->drupalGet("node/add/$type_name");
  667. foreach (array($field_name2, $field_name) as $each_field_name) {
  668. for ($delta = 0; $delta < 3; $delta++) {
  669. $edit = array('files[' . $each_field_name . '_' . LANGUAGE_NONE . '_' . $delta . ']' => drupal_realpath($test_file->uri));
  670. // If the Upload button doesn't exist, drupalPost() will automatically
  671. // fail with an assertion message.
  672. $this->drupalPost(NULL, $edit, t('Upload'));
  673. }
  674. }
  675. $this->assertNoFieldByXpath('//input[@type="submit"]', t('Upload'), 'After uploading 3 files for each field, the "Upload" button is no longer displayed.');
  676. $num_expected_remove_buttons = 6;
  677. foreach (array($field_name, $field_name2) as $current_field_name) {
  678. // How many uploaded files for the current field are remaining.
  679. $remaining = 3;
  680. // Test clicking each "Remove" button. For extra robustness, test them out
  681. // of sequential order. They are 0-indexed, and get renumbered after each
  682. // iteration, so array(1, 1, 0) means:
  683. // - First remove the 2nd file.
  684. // - Then remove what is then the 2nd file (was originally the 3rd file).
  685. // - Then remove the first file.
  686. foreach (array(1,1,0) as $delta) {
  687. // Ensure we have the expected number of Remove buttons, and that they
  688. // are numbered sequentially.
  689. $buttons = $this->xpath('//input[@type="submit" and @value="Remove"]');
  690. $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)));
  691. foreach ($buttons as $i => $button) {
  692. $key = $i >= $remaining ? $i - $remaining : $i;
  693. $check_field_name = $field_name2;
  694. if ($current_field_name == $field_name && $i < $remaining) {
  695. $check_field_name = $field_name;
  696. }
  697. $this->assertIdentical((string) $button['name'], $check_field_name . '_' . LANGUAGE_NONE . '_' . $key. '_remove_button');
  698. }
  699. // "Click" the remove button (emulating either a nojs or js submission).
  700. $button_name = $current_field_name . '_' . LANGUAGE_NONE . '_' . $delta . '_remove_button';
  701. switch ($type) {
  702. case 'nojs':
  703. // drupalPost() takes a $submit parameter that is the value of the
  704. // button whose click we want to emulate. Since we have multiple
  705. // buttons with the value "Remove", and want to control which one we
  706. // use, we change the value of the other ones to something else.
  707. // Since non-clicked buttons aren't included in the submitted POST
  708. // data, and since drupalPost() will result in $this being updated
  709. // with a newly rebuilt form, this doesn't cause problems.
  710. foreach ($buttons as $button) {
  711. if ($button['name'] != $button_name) {
  712. $button['value'] = 'DUMMY';
  713. }
  714. }
  715. $this->drupalPost(NULL, array(), t('Remove'));
  716. break;
  717. case 'js':
  718. // drupalPostAJAX() lets us target the button precisely, so we don't
  719. // require the workaround used above for nojs.
  720. $this->drupalPostAJAX(NULL, array(), array($button_name => t('Remove')));
  721. break;
  722. }
  723. $num_expected_remove_buttons--;
  724. $remaining--;
  725. // Ensure an "Upload" button for the current field is displayed with the
  726. // correct name.
  727. $upload_button_name = $current_field_name . '_' . LANGUAGE_NONE . '_' . $remaining . '_upload_button';
  728. $buttons = $this->xpath('//input[@type="submit" and @value="Upload" and @name=:name]', array(':name' => $upload_button_name));
  729. $this->assertTrue(is_array($buttons) && count($buttons) == 1, format_string('The upload button is displayed with the correct name (JSMode=%type).', array('%type' => $type)));
  730. // Ensure only at most one button per field is displayed.
  731. $buttons = $this->xpath('//input[@type="submit" and @value="Upload"]');
  732. $expected = $current_field_name == $field_name ? 1 : 2;
  733. $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)));
  734. }
  735. }
  736. // Ensure the page now has no Remove buttons.
  737. $this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), format_string('After removing all files, there is no "Remove" button displayed (JSMode=%type).', array('%type' => $type)));
  738. // Save the node and ensure it does not have any files.
  739. $this->drupalPost(NULL, array('title' => $this->randomName()), t('Save'));
  740. $matches = array();
  741. preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
  742. $nid = $matches[1];
  743. $node = node_load($nid, NULL, TRUE);
  744. $this->assertTrue(empty($node->{$field_name}[LANGUAGE_NONE][0]['fid']), 'Node was successfully saved without any files.');
  745. }
  746. }
  747. /**
  748. * Tests a file field with a "Private files" upload destination setting.
  749. */
  750. function testPrivateFileSetting() {
  751. // Use 'page' instead of 'article', so that the 'article' image field does
  752. // not conflict with this test. If in the future the 'page' type gets its
  753. // own default file or image field, this test can be made more robust by
  754. // using a custom node type.
  755. $type_name = 'page';
  756. $field_name = strtolower($this->randomName());
  757. $this->createFileField($field_name, $type_name);
  758. $field = field_info_field($field_name);
  759. $instance = field_info_instance('node', $field_name, $type_name);
  760. $test_file = $this->getTestFile('text');
  761. // Change the field setting to make its files private, and upload a file.
  762. $edit = array('field[settings][uri_scheme]' => 'private');
  763. $this->drupalPost("admin/structure/types/manage/$type_name/fields/$field_name", $edit, t('Save settings'));
  764. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  765. $node = node_load($nid, NULL, TRUE);
  766. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  767. $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
  768. // Ensure the private file is available to the user who uploaded it.
  769. $this->drupalGet(file_create_url($node_file->uri));
  770. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
  771. // Ensure we can't change 'uri_scheme' field settings while there are some
  772. // entities with uploaded files.
  773. $this->drupalGet("admin/structure/types/manage/$type_name/fields/$field_name");
  774. $this->assertFieldByXpath('//input[@id="edit-field-settings-uri-scheme-public" and @disabled="disabled"]', 'public', 'Upload destination setting disabled.');
  775. // Delete node and confirm that setting could be changed.
  776. node_delete($nid);
  777. $this->drupalGet("admin/structure/types/manage/$type_name/fields/$field_name");
  778. $this->assertFieldByXpath('//input[@id="edit-field-settings-uri-scheme-public" and not(@disabled)]', 'public', 'Upload destination setting enabled.');
  779. }
  780. /**
  781. * Tests that download restrictions on private files work on comments.
  782. */
  783. function testPrivateFileComment() {
  784. $user = $this->drupalCreateUser(array('access comments'));
  785. // Remove access comments permission from anon user.
  786. $edit = array(
  787. DRUPAL_ANONYMOUS_RID . '[access comments]' => FALSE,
  788. );
  789. $this->drupalPost('admin/people/permissions', $edit, t('Save permissions'));
  790. // Create a new field.
  791. $edit = array(
  792. 'fields[_add_new_field][label]' => $label = $this->randomName(),
  793. 'fields[_add_new_field][field_name]' => $name = strtolower($this->randomName()),
  794. 'fields[_add_new_field][type]' => 'file',
  795. 'fields[_add_new_field][widget_type]' => 'file_generic',
  796. );
  797. $this->drupalPost('admin/structure/types/manage/article/comment/fields', $edit, t('Save'));
  798. $edit = array('field[settings][uri_scheme]' => 'private');
  799. $this->drupalPost(NULL, $edit, t('Save field settings'));
  800. $this->drupalPost(NULL, array(), t('Save settings'));
  801. // Create node.
  802. $text_file = $this->getTestFile('text');
  803. $edit = array(
  804. 'title' => $this->randomName(),
  805. );
  806. $this->drupalPost('node/add/article', $edit, t('Save'));
  807. $node = $this->drupalGetNodeByTitle($edit['title']);
  808. // Add a comment with a file.
  809. $text_file = $this->getTestFile('text');
  810. $edit = array(
  811. 'files[field_' . $name . '_' . LANGUAGE_NONE . '_' . 0 . ']' => drupal_realpath($text_file->uri),
  812. 'comment_body[' . LANGUAGE_NONE . '][0][value]' => $comment_body = $this->randomName(),
  813. );
  814. $this->drupalPost(NULL, $edit, t('Save'));
  815. // Get the comment ID.
  816. preg_match('/comment-([0-9]+)/', $this->getUrl(), $matches);
  817. $cid = $matches[1];
  818. // Log in as normal user.
  819. $this->drupalLogin($user);
  820. $comment = comment_load($cid);
  821. $comment_file = (object) $comment->{'field_' . $name}[LANGUAGE_NONE][0];
  822. $this->assertFileExists($comment_file, 'New file saved to disk on node creation.');
  823. // Test authenticated file download.
  824. $url = file_create_url($comment_file->uri);
  825. $this->assertNotEqual($url, NULL, 'Confirmed that the URL is valid');
  826. $this->drupalGet(file_create_url($comment_file->uri));
  827. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
  828. // Test anonymous file download.
  829. $this->drupalLogout();
  830. $this->drupalGet(file_create_url($comment_file->uri));
  831. $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
  832. // Unpublishes node.
  833. $this->drupalLogin($this->admin_user);
  834. $edit = array(
  835. 'status' => FALSE,
  836. );
  837. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  838. // Ensures normal user can no longer download the file.
  839. $this->drupalLogin($user);
  840. $this->drupalGet(file_create_url($comment_file->uri));
  841. $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
  842. }
  843. }
  844. /**
  845. * Tests file handling with node revisions.
  846. */
  847. class FileFieldRevisionTestCase extends FileFieldTestCase {
  848. public static function getInfo() {
  849. return array(
  850. 'name' => 'File field revision test',
  851. 'description' => 'Test creating and deleting revisions with files attached.',
  852. 'group' => 'File',
  853. );
  854. }
  855. /**
  856. * Tests creating multiple revisions of a node and managing attached files.
  857. *
  858. * Expected behaviors:
  859. * - Adding a new revision will make another entry in the field table, but
  860. * the original file will not be duplicated.
  861. * - Deleting a revision should not delete the original file if the file
  862. * is in use by another revision.
  863. * - When the last revision that uses a file is deleted, the original file
  864. * should be deleted also.
  865. */
  866. function testRevisions() {
  867. $type_name = 'article';
  868. $field_name = strtolower($this->randomName());
  869. $this->createFileField($field_name, $type_name);
  870. $field = field_info_field($field_name);
  871. $instance = field_info_instance('node', $field_name, $type_name);
  872. // Attach the same fields to users.
  873. $this->attachFileField($field_name, 'user', 'user');
  874. $test_file = $this->getTestFile('text');
  875. // Create a new node with the uploaded file.
  876. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  877. // Check that the file exists on disk and in the database.
  878. $node = node_load($nid, NULL, TRUE);
  879. $node_file_r1 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  880. $node_vid_r1 = $node->vid;
  881. $this->assertFileExists($node_file_r1, 'New file saved to disk on node creation.');
  882. $this->assertFileEntryExists($node_file_r1, 'File entry exists in database on node creation.');
  883. $this->assertFileIsPermanent($node_file_r1, 'File is permanent.');
  884. // Upload another file to the same node in a new revision.
  885. $this->replaceNodeFile($test_file, $field_name, $nid);
  886. $node = node_load($nid, NULL, TRUE);
  887. $node_file_r2 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  888. $node_vid_r2 = $node->vid;
  889. $this->assertFileExists($node_file_r2, 'Replacement file exists on disk after creating new revision.');
  890. $this->assertFileEntryExists($node_file_r2, 'Replacement file entry exists in database after creating new revision.');
  891. $this->assertFileIsPermanent($node_file_r2, 'Replacement file is permanent.');
  892. // Check that the original file is still in place on the first revision.
  893. $node = node_load($nid, $node_vid_r1, TRUE);
  894. $this->assertEqual($node_file_r1, (object) $node->{$field_name}[LANGUAGE_NONE][0], 'Original file still in place after replacing file in new revision.');
  895. $this->assertFileExists($node_file_r1, 'Original file still in place after replacing file in new revision.');
  896. $this->assertFileEntryExists($node_file_r1, 'Original file entry still in place after replacing file in new revision');
  897. $this->assertFileIsPermanent($node_file_r1, 'Original file is still permanent.');
  898. // Save a new version of the node without any changes.
  899. // Check that the file is still the same as the previous revision.
  900. $this->drupalPost('node/' . $nid . '/edit', array('revision' => '1'), t('Save'));
  901. $node = node_load($nid, NULL, TRUE);
  902. $node_file_r3 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  903. $node_vid_r3 = $node->vid;
  904. $this->assertEqual($node_file_r2, $node_file_r3, 'Previous revision file still in place after creating a new revision without a new file.');
  905. $this->assertFileIsPermanent($node_file_r3, 'New revision file is permanent.');
  906. // Revert to the first revision and check that the original file is active.
  907. $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r1 . '/revert', array(), t('Revert'));
  908. $node = node_load($nid, NULL, TRUE);
  909. $node_file_r4 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  910. $node_vid_r4 = $node->vid;
  911. $this->assertEqual($node_file_r1, $node_file_r4, 'Original revision file still in place after reverting to the original revision.');
  912. $this->assertFileIsPermanent($node_file_r4, 'Original revision file still permanent after reverting to the original revision.');
  913. // Delete the second revision and check that the file is kept (since it is
  914. // still being used by the third revision).
  915. $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r2 . '/delete', array(), t('Delete'));
  916. $this->assertFileExists($node_file_r3, 'Second file is still available after deleting second revision, since it is being used by the third revision.');
  917. $this->assertFileEntryExists($node_file_r3, 'Second file entry is still available after deleting second revision, since it is being used by the third revision.');
  918. $this->assertFileIsPermanent($node_file_r3, 'Second file entry is still permanent after deleting second revision, since it is being used by the third revision.');
  919. // Attach the second file to a user.
  920. $user = $this->drupalCreateUser();
  921. $edit = (array) $user;
  922. $edit[$field_name][LANGUAGE_NONE][0] = (array) $node_file_r3;
  923. user_save($user, $edit);
  924. $this->drupalGet('user/' . $user->uid . '/edit');
  925. // Delete the third revision and check that the file is not deleted yet.
  926. $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r3 . '/delete', array(), t('Delete'));
  927. $this->assertFileExists($node_file_r3, 'Second file is still available after deleting third revision, since it is being used by the user.');
  928. $this->assertFileEntryExists($node_file_r3, 'Second file entry is still available after deleting third revision, since it is being used by the user.');
  929. $this->assertFileIsPermanent($node_file_r3, 'Second file entry is still permanent after deleting third revision, since it is being used by the user.');
  930. // Delete the user and check that the file is also deleted.
  931. user_delete($user->uid);
  932. // TODO: This seems like a bug in File API. Clearing the stat cache should
  933. // not be necessary here. The file really is deleted, but stream wrappers
  934. // doesn't seem to think so unless we clear the PHP file stat() cache.
  935. clearstatcache();
  936. $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.');
  937. $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.');
  938. // Delete the entire node and check that the original file is deleted.
  939. $this->drupalPost('node/' . $nid . '/delete', array(), t('Delete'));
  940. $this->assertFileNotExists($node_file_r1, 'Original file is deleted after deleting the entire node with two revisions remaining.');
  941. $this->assertFileEntryNotExists($node_file_r1, 'Original file entry is deleted after deleting the entire node with two revisions remaining.');
  942. }
  943. }
  944. /**
  945. * Tests that formatters are working properly.
  946. */
  947. class FileFieldDisplayTestCase extends FileFieldTestCase {
  948. public static function getInfo() {
  949. return array(
  950. 'name' => 'File field display tests',
  951. 'description' => 'Test the display of file fields in node and views.',
  952. 'group' => 'File',
  953. );
  954. }
  955. /**
  956. * Tests normal formatter display on node display.
  957. */
  958. function testNodeDisplay() {
  959. $field_name = strtolower($this->randomName());
  960. $type_name = 'article';
  961. $field_settings = array(
  962. 'display_field' => '1',
  963. 'display_default' => '1',
  964. 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  965. );
  966. $instance_settings = array(
  967. 'description_field' => '1',
  968. );
  969. $widget_settings = array();
  970. $this->createFileField($field_name, $type_name, $field_settings, $instance_settings, $widget_settings);
  971. $field = field_info_field($field_name);
  972. $instance = field_info_instance('node', $field_name, $type_name);
  973. // Create a new node *without* the file field set, and check that the field
  974. // is not shown for each node display.
  975. $node = $this->drupalCreateNode(array('type' => $type_name));
  976. $file_formatters = array('file_default', 'file_table', 'file_url_plain', 'hidden');
  977. foreach ($file_formatters as $formatter) {
  978. $edit = array(
  979. "fields[$field_name][type]" => $formatter,
  980. );
  981. $this->drupalPost("admin/structure/types/manage/$type_name/display", $edit, t('Save'));
  982. $this->drupalGet('node/' . $node->nid);
  983. $this->assertNoText($field_name, format_string('Field label is hidden when no file attached for formatter %formatter', array('%formatter' => $formatter)));
  984. }
  985. $test_file = $this->getTestFile('text');
  986. // Create a new node with the uploaded file.
  987. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  988. $this->drupalGet('node/' . $nid . '/edit');
  989. // Check that the default formatter is displaying with the file name.
  990. $node = node_load($nid, NULL, TRUE);
  991. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  992. $default_output = theme('file_link', array('file' => $node_file));
  993. $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
  994. // Turn the "display" option off and check that the file is no longer displayed.
  995. $edit = array($field_name . '[' . LANGUAGE_NONE . '][0][display]' => FALSE);
  996. $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
  997. $this->assertNoRaw($default_output, 'Field is hidden when "display" option is unchecked.');
  998. // Test that fields appear as expected during the preview.
  999. // Add a second file.
  1000. $name = 'files[' . $field_name . '_' . LANGUAGE_NONE . '_1]';
  1001. $edit[$name] = drupal_realpath($test_file->uri);
  1002. // Uncheck the display checkboxes and go to the preview.
  1003. $edit[$field_name . '[' . LANGUAGE_NONE . '][0][display]'] = FALSE;
  1004. $edit[$field_name . '[' . LANGUAGE_NONE . '][1][display]'] = FALSE;
  1005. $this->drupalPost('node/' . $nid . '/edit', $edit, t('Preview'));
  1006. $this->assertRaw($field_name . '[' . LANGUAGE_NONE . '][0][display]', 'First file appears as expected.');
  1007. $this->assertRaw($field_name . '[' . LANGUAGE_NONE . '][1][display]', 'Second file appears as expected.');
  1008. }
  1009. /**
  1010. * Tests default display of File Field.
  1011. */
  1012. function testDefaultFileFieldDisplay() {
  1013. $field_name = strtolower($this->randomName());
  1014. $type_name = 'article';
  1015. $field_settings = array(
  1016. 'display_field' => '1',
  1017. 'display_default' => '0',
  1018. );
  1019. $instance_settings = array(
  1020. 'description_field' => '1',
  1021. );
  1022. $widget_settings = array();
  1023. $this->createFileField($field_name, $type_name, $field_settings, $instance_settings, $widget_settings);
  1024. $field = field_info_field($field_name);
  1025. $instance = field_info_instance('node', $field_name, $type_name);
  1026. $test_file = $this->getTestFile('text');
  1027. // Create a new node with the uploaded file.
  1028. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  1029. $this->drupalGet('node/' . $nid . '/edit');
  1030. $this->assertFieldByXPath('//input[@type="checkbox" and @name="' . $field_name . '[und][0][display]"]', NULL, 'Default file display checkbox field exists.');
  1031. $this->assertFieldByXPath('//input[@type="checkbox" and @name="' . $field_name . '[und][0][display]" and not(@checked)]', NULL, 'Default file display is off.');
  1032. }
  1033. }
  1034. /**
  1035. * Tests various validations.
  1036. */
  1037. class FileFieldValidateTestCase extends FileFieldTestCase {
  1038. protected $field;
  1039. protected $node_type;
  1040. public static function getInfo() {
  1041. return array(
  1042. 'name' => 'File field validation tests',
  1043. 'description' => 'Tests validation functions such as file type, max file size, max size per node, and required.',
  1044. 'group' => 'File',
  1045. );
  1046. }
  1047. /**
  1048. * Tests the required property on file fields.
  1049. */
  1050. function testRequired() {
  1051. $type_name = 'article';
  1052. $field_name = strtolower($this->randomName());
  1053. $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
  1054. $field = field_info_field($field_name);
  1055. $instance = field_info_instance('node', $field_name, $type_name);
  1056. $test_file = $this->getTestFile('text');
  1057. // Try to post a new node without uploading a file.
  1058. $langcode = LANGUAGE_NONE;
  1059. $edit = array("title" => $this->randomName());
  1060. $this->drupalPost('node/add/' . $type_name, $edit, t('Save'));
  1061. $this->assertRaw(t('!title field is required.', array('!title' => $instance['label'])), 'Node save failed when required file field was empty.');
  1062. // Create a new node with the uploaded file.
  1063. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  1064. $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)));
  1065. $node = node_load($nid, NULL, TRUE);
  1066. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  1067. $this->assertFileExists($node_file, 'File exists after uploading to the required field.');
  1068. $this->assertFileEntryExists($node_file, 'File entry exists after uploading to the required field.');
  1069. // Try again with a multiple value field.
  1070. field_delete_field($field_name);
  1071. $this->createFileField($field_name, $type_name, array('cardinality' => FIELD_CARDINALITY_UNLIMITED), array('required' => '1'));
  1072. // Try to post a new node without uploading a file in the multivalue field.
  1073. $edit = array('title' => $this->randomName());
  1074. $this->drupalPost('node/add/' . $type_name, $edit, t('Save'));
  1075. $this->assertRaw(t('!title field is required.', array('!title' => $instance['label'])), 'Node save failed when required multiple value file field was empty.');
  1076. // Create a new node with the uploaded file into the multivalue field.
  1077. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  1078. $node = node_load($nid, NULL, TRUE);
  1079. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  1080. $this->assertFileExists($node_file, 'File exists after uploading to the required multiple value field.');
  1081. $this->assertFileEntryExists($node_file, 'File entry exists after uploading to the required multipel value field.');
  1082. // Remove our file field.
  1083. field_delete_field($field_name);
  1084. }
  1085. /**
  1086. * Tests the max file size validator.
  1087. */
  1088. function testFileMaxSize() {
  1089. $type_name = 'article';
  1090. $field_name = strtolower($this->randomName());
  1091. $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
  1092. $field = field_info_field($field_name);
  1093. $instance = field_info_instance('node', $field_name, $type_name);
  1094. $small_file = $this->getTestFile('text', 131072); // 128KB.
  1095. $large_file = $this->getTestFile('text', 1310720); // 1.2MB
  1096. // Test uploading both a large and small file with different increments.
  1097. $sizes = array(
  1098. '1M' => 1048576,
  1099. '1024K' => 1048576,
  1100. '1048576' => 1048576,
  1101. );
  1102. foreach ($sizes as $max_filesize => $file_limit) {
  1103. // Set the max file upload size.
  1104. $this->updateFileField($field_name, $type_name, array('max_filesize' => $max_filesize));
  1105. $instance = field_info_instance('node', $field_name, $type_name);
  1106. // Create a new node with the small file, which should pass.
  1107. $nid = $this->uploadNodeFile($small_file, $field_name, $type_name);
  1108. $node = node_load($nid, NULL, TRUE);
  1109. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  1110. $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)));
  1111. $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)));
  1112. // Check that uploading the large file fails (1M limit).
  1113. $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
  1114. $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)));
  1115. $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)));
  1116. }
  1117. // Turn off the max filesize.
  1118. $this->updateFileField($field_name, $type_name, array('max_filesize' => ''));
  1119. // Upload the big file successfully.
  1120. $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
  1121. $node = node_load($nid, NULL, TRUE);
  1122. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  1123. $this->assertFileExists($node_file, format_string('File exists after uploading a file (%filesize) with no max limit.', array('%filesize' => format_size($large_file->filesize))));
  1124. $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))));
  1125. // Remove our file field.
  1126. field_delete_field($field_name);
  1127. }
  1128. /**
  1129. * Tests file extension checking.
  1130. */
  1131. function testFileExtension() {
  1132. $type_name = 'article';
  1133. $field_name = strtolower($this->randomName());
  1134. $this->createFileField($field_name, $type_name);
  1135. $field = field_info_field($field_name);
  1136. $instance = field_info_instance('node', $field_name, $type_name);
  1137. $test_file = $this->getTestFile('image');
  1138. list(, $test_file_extension) = explode('.', $test_file->filename);
  1139. // Disable extension checking.
  1140. $this->updateFileField($field_name, $type_name, array('file_extensions' => ''));
  1141. // Check that the file can be uploaded with no extension checking.
  1142. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  1143. $node = node_load($nid, NULL, TRUE);
  1144. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  1145. $this->assertFileExists($node_file, 'File exists after uploading a file with no extension checking.');
  1146. $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with no extension checking.');
  1147. // Enable extension checking for text files.
  1148. $this->updateFileField($field_name, $type_name, array('file_extensions' => 'txt'));
  1149. // Check that the file with the wrong extension cannot be uploaded.
  1150. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  1151. $error_message = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => 'txt'));
  1152. $this->assertRaw($error_message, 'Node save failed when file uploaded with the wrong extension.');
  1153. // Enable extension checking for text and image files.
  1154. $this->updateFileField($field_name, $type_name, array('file_extensions' => "txt $test_file_extension"));
  1155. // Check that the file can be uploaded with extension checking.
  1156. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  1157. $node = node_load($nid, NULL, TRUE);
  1158. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  1159. $this->assertFileExists($node_file, 'File exists after uploading a file with extension checking.');
  1160. $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with extension checking.');
  1161. // Remove our file field.
  1162. field_delete_field($field_name);
  1163. }
  1164. }
  1165. /**
  1166. * Tests that files are uploaded to proper locations.
  1167. */
  1168. class FileFieldPathTestCase extends FileFieldTestCase {
  1169. public static function getInfo() {
  1170. return array(
  1171. 'name' => 'File field file path tests',
  1172. 'description' => 'Test that files are uploaded to the proper location with token support.',
  1173. 'group' => 'File',
  1174. );
  1175. }
  1176. /**
  1177. * Tests the normal formatter display on node display.
  1178. */
  1179. function testUploadPath() {
  1180. $field_name = strtolower($this->randomName());
  1181. $type_name = 'article';
  1182. $field = $this->createFileField($field_name, $type_name);
  1183. $test_file = $this->getTestFile('text');
  1184. // Create a new node.
  1185. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  1186. // Check that the file was uploaded to the file root.
  1187. $node = node_load($nid, NULL, TRUE);
  1188. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  1189. $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)));
  1190. // Change the path to contain multiple subdirectories.
  1191. $field = $this->updateFileField($field_name, $type_name, array('file_directory' => 'foo/bar/baz'));
  1192. // Upload a new file into the subdirectories.
  1193. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  1194. // Check that the file was uploaded into the subdirectory.
  1195. $node = node_load($nid, NULL, TRUE);
  1196. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  1197. $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)));
  1198. // Check the path when used with tokens.
  1199. // Change the path to contain multiple token directories.
  1200. $field = $this->updateFileField($field_name, $type_name, array('file_directory' => '[current-user:uid]/[current-user:name]'));
  1201. // Upload a new file into the token subdirectories.
  1202. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  1203. // Check that the file was uploaded into the subdirectory.
  1204. $node = node_load($nid, NULL, TRUE);
  1205. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  1206. // Do token replacement using the same user which uploaded the file, not
  1207. // the user running the test case.
  1208. $data = array('user' => $this->admin_user);
  1209. $subdirectory = token_replace('[user:uid]/[user:name]', $data);
  1210. $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)));
  1211. }
  1212. /**
  1213. * Asserts that a file is uploaded to the right location.
  1214. *
  1215. * @param $expected_path
  1216. * The location where the file is expected to be uploaded. Duplicate file
  1217. * names to not need to be taken into account.
  1218. * @param $actual_path
  1219. * Where the file was actually uploaded.
  1220. * @param $message
  1221. * The message to display with this assertion.
  1222. */
  1223. function assertPathMatch($expected_path, $actual_path, $message) {
  1224. // Strip off the extension of the expected path to allow for _0, _1, etc.
  1225. // suffixes when the file hits a duplicate name.
  1226. $pos = strrpos($expected_path, '.');
  1227. $base_path = substr($expected_path, 0, $pos);
  1228. $extension = substr($expected_path, $pos + 1);
  1229. $result = preg_match('/' . preg_quote($base_path, '/') . '(_[0-9]+)?\.' . preg_quote($extension, '/') . '/', $actual_path);
  1230. $this->assertTrue($result, $message);
  1231. }
  1232. }
  1233. /**
  1234. * Tests the file token replacement in strings.
  1235. */
  1236. class FileTokenReplaceTestCase extends FileFieldTestCase {
  1237. public static function getInfo() {
  1238. return array(
  1239. 'name' => 'File token replacement',
  1240. 'description' => 'Generates text using placeholders for dummy content to check file token replacement.',
  1241. 'group' => 'File',
  1242. );
  1243. }
  1244. /**
  1245. * Creates a file, then tests the tokens generated from it.
  1246. */
  1247. function testFileTokenReplacement() {
  1248. global $language;
  1249. $url_options = array(
  1250. 'absolute' => TRUE,
  1251. 'language' => $language,
  1252. );
  1253. // Create file field.
  1254. $type_name = 'article';
  1255. $field_name = 'field_' . strtolower($this->randomName());
  1256. $this->createFileField($field_name, $type_name);
  1257. $field = field_info_field($field_name);
  1258. $instance = field_info_instance('node', $field_name, $type_name);
  1259. $test_file = $this->getTestFile('text');
  1260. // Coping a file to test uploads with non-latin filenames.
  1261. $filename = drupal_dirname($test_file->uri) . '/текстовый файл.txt';
  1262. $test_file = file_copy($test_file, $filename);
  1263. // Create a new node with the uploaded file.
  1264. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  1265. // Load the node and the file.
  1266. $node = node_load($nid, NULL, TRUE);
  1267. $file = file_load($node->{$field_name}[LANGUAGE_NONE][0]['fid']);
  1268. // Generate and test sanitized tokens.
  1269. $tests = array();
  1270. $tests['[file:fid]'] = $file->fid;
  1271. $tests['[file:name]'] = check_plain($file->filename);
  1272. $tests['[file:path]'] = check_plain($file->uri);
  1273. $tests['[file:mime]'] = check_plain($file->filemime);
  1274. $tests['[file:size]'] = format_size($file->filesize);
  1275. $tests['[file:url]'] = check_plain(file_create_url($file->uri));
  1276. $tests['[file:timestamp]'] = format_date($file->timestamp, 'medium', '', NULL, $language->language);
  1277. $tests['[file:timestamp:short]'] = format_date($file->timestamp, 'short', '', NULL, $language->language);
  1278. $tests['[file:owner]'] = check_plain(format_username($this->admin_user));
  1279. $tests['[file:owner:uid]'] = $file->uid;
  1280. // Test to make sure that we generated something for each token.
  1281. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
  1282. foreach ($tests as $input => $expected) {
  1283. $output = token_replace($input, array('file' => $file), array('language' => $language));
  1284. $this->assertEqual($output, $expected, format_string('Sanitized file token %token replaced.', array('%token' => $input)));
  1285. }
  1286. // Generate and test unsanitized tokens.
  1287. $tests['[file:name]'] = $file->filename;
  1288. $tests['[file:path]'] = $file->uri;
  1289. $tests['[file:mime]'] = $file->filemime;
  1290. $tests['[file:size]'] = format_size($file->filesize);
  1291. foreach ($tests as $input => $expected) {
  1292. $output = token_replace($input, array('file' => $file), array('language' => $language, 'sanitize' => FALSE));
  1293. $this->assertEqual($output, $expected, format_string('Unsanitized file token %token replaced.', array('%token' => $input)));
  1294. }
  1295. }
  1296. }
  1297. /**
  1298. * Tests file access on private nodes.
  1299. */
  1300. class FilePrivateTestCase extends FileFieldTestCase {
  1301. public static function getInfo() {
  1302. return array(
  1303. 'name' => 'Private file test',
  1304. 'description' => 'Uploads a test to a private node and checks access.',
  1305. 'group' => 'File',
  1306. );
  1307. }
  1308. function setUp() {
  1309. parent::setUp(array('node_access_test', 'field_test'));
  1310. node_access_rebuild();
  1311. variable_set('node_access_test_private', TRUE);
  1312. }
  1313. /**
  1314. * Tests file access for file uploaded to a private node.
  1315. */
  1316. function testPrivateFile() {
  1317. // Use 'page' instead of 'article', so that the 'article' image field does
  1318. // not conflict with this test. If in the future the 'page' type gets its
  1319. // own default file or image field, this test can be made more robust by
  1320. // using a custom node type.
  1321. $type_name = 'page';
  1322. $field_name = strtolower($this->randomName());
  1323. $this->createFileField($field_name, $type_name, array('uri_scheme' => 'private'));
  1324. // Create a field with no view access - see field_test_field_access().
  1325. $no_access_field_name = 'field_no_view_access';
  1326. $this->createFileField($no_access_field_name, $type_name, array('uri_scheme' => 'private'));
  1327. $test_file = $this->getTestFile('text');
  1328. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name, TRUE, array('private' => TRUE));
  1329. $node = node_load($nid, NULL, TRUE);
  1330. $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
  1331. // Ensure the file can be downloaded.
  1332. $this->drupalGet(file_create_url($node_file->uri));
  1333. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
  1334. $this->drupalLogOut();
  1335. $this->drupalGet(file_create_url($node_file->uri));
  1336. $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
  1337. // Test with the field that should deny access through field access.
  1338. $this->drupalLogin($this->admin_user);
  1339. $nid = $this->uploadNodeFile($test_file, $no_access_field_name, $type_name, TRUE, array('private' => TRUE));
  1340. $node = node_load($nid, NULL, TRUE);
  1341. $node_file = (object) $node->{$no_access_field_name}[LANGUAGE_NONE][0];
  1342. // Ensure the file cannot be downloaded.
  1343. $this->drupalGet(file_create_url($node_file->uri));
  1344. $this->assertResponse(403, 'Confirmed that access is denied for the file without view field access permission.');
  1345. // Attempt to reuse the existing file when creating a new node, and confirm
  1346. // that access is still denied.
  1347. $edit = array();
  1348. $edit['title'] = $this->randomName(8);
  1349. $edit[$field_name . '[' . LANGUAGE_NONE . '][0][fid]'] = $node_file->fid;
  1350. $this->drupalPost('node/add/page', $edit, t('Save'));
  1351. $new_node = $this->drupalGetNodeByTitle($edit['title']);
  1352. $this->assertTrue(!empty($new_node), 'Node was created.');
  1353. $this->assertUrl('node/' . $new_node->nid);
  1354. $this->assertNoRaw($node_file->filename, 'File without view field access permission does not appear after attempting to attach it to a new node.');
  1355. $this->drupalGet(file_create_url($node_file->uri));
  1356. $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.');
  1357. // As an anonymous user, create a temporary file with no references and
  1358. // confirm that only the session that uploaded it may view it.
  1359. $this->drupalLogout();
  1360. user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array(
  1361. "create $type_name content",
  1362. 'access content',
  1363. ));
  1364. $test_file = $this->getTestFile('text');
  1365. $this->drupalGet('node/add/' . $type_name);
  1366. $edit = array('files[' . $field_name . '_' . LANGUAGE_NONE . '_0]' => drupal_realpath($test_file->uri));
  1367. $this->drupalPost(NULL, $edit, t('Upload'));
  1368. $files = file_load_multiple(array(), array('uid' => 0));
  1369. $this->assertEqual(1, count($files), 'Loaded one anonymous file.');
  1370. $file = end($files);
  1371. $this->assertNotEqual($file->status, FILE_STATUS_PERMANENT, 'File is temporary.');
  1372. $usage = file_usage_list($file);
  1373. $this->assertFalse($usage, 'No file usage found.');
  1374. $file_url = file_create_url($file->uri);
  1375. $this->drupalGet($file_url);
  1376. $this->assertResponse(200, 'Confirmed that the anonymous uploader has access to the temporary file.');
  1377. // Close the prior connection and remove the session cookie.
  1378. $this->curlClose();
  1379. $this->cookies = array();
  1380. $this->drupalGet($file_url);
  1381. $this->assertResponse(403, 'Confirmed that another anonymous user cannot access the temporary file.');
  1382. // As an anonymous user, create a permanent file that is referenced by a
  1383. // published node and confirm that all anonymous users may view it.
  1384. $test_file = $this->getTestFile('text');
  1385. $this->drupalGet('node/add/' . $type_name);
  1386. $edit = array();
  1387. $edit['title'] = $this->randomName();
  1388. $edit['files[' . $field_name . '_' . LANGUAGE_NONE . '_0]'] = drupal_realpath($test_file->uri);
  1389. $this->drupalPost(NULL, $edit, t('Save'));
  1390. $new_node = $this->drupalGetNodeByTitle($edit['title']);
  1391. $file = file_load($new_node->{$field_name}[LANGUAGE_NONE][0]['fid']);
  1392. $this->assertEqual($file->status, FILE_STATUS_PERMANENT, 'File is permanent.');
  1393. $usage = file_usage_list($file);
  1394. $this->assertTrue($usage, 'File usage found.');
  1395. $file_url = file_create_url($file->uri);
  1396. $this->drupalGet($file_url);
  1397. $this->assertResponse(200, 'Confirmed that the anonymous uploader has access to the permanent file that is referenced by a published node.');
  1398. // Close the prior connection and remove the session cookie.
  1399. $this->curlClose();
  1400. $this->cookies = array();
  1401. $this->drupalGet($file_url);
  1402. $this->assertResponse(200, 'Confirmed that another anonymous user also has access to the permanent file that is referenced by a published node.');
  1403. // As an anonymous user, create a permanent file that is referenced by an
  1404. // unpublished node and confirm that no anonymous users may view it (even
  1405. // the session that uploaded the file) because they cannot view the
  1406. // unpublished node.
  1407. $test_file = $this->getTestFile('text');
  1408. $this->drupalGet('node/add/' . $type_name);
  1409. $edit = array();
  1410. $edit['title'] = $this->randomName();
  1411. $edit['files[' . $field_name . '_' . LANGUAGE_NONE . '_0]'] = drupal_realpath($test_file->uri);
  1412. $this->drupalPost(NULL, $edit, t('Save'));
  1413. $new_node = $this->drupalGetNodeByTitle($edit['title']);
  1414. $new_node->status = NODE_NOT_PUBLISHED;
  1415. node_save($new_node);
  1416. $file = file_load($new_node->{$field_name}[LANGUAGE_NONE][0]['fid']);
  1417. $this->assertEqual($file->status, FILE_STATUS_PERMANENT, 'File is permanent.');
  1418. $usage = file_usage_list($file);
  1419. $this->assertTrue($usage, 'File usage found.');
  1420. $file_url = file_create_url($file->uri);
  1421. $this->drupalGet($file_url);
  1422. $this->assertResponse(403, 'Confirmed that the anonymous uploader cannot access the permanent file when it is referenced by an unpublished node.');
  1423. // Close the prior connection and remove the session cookie.
  1424. $this->curlClose();
  1425. $this->cookies = array();
  1426. $this->drupalGet($file_url);
  1427. $this->assertResponse(403, 'Confirmed that another anonymous user cannot access the permanent file when it is referenced by an unpublished node.');
  1428. }
  1429. /**
  1430. * Tests file access for private nodes when file download access is granted.
  1431. */
  1432. function testPrivateFileDownloadAccessGranted() {
  1433. // Tell file_module_test to attempt to grant access to all private files,
  1434. // and ensure that it is doing so correctly.
  1435. $test_file = $this->getTestFile('text');
  1436. $uri = file_unmanaged_move($test_file->uri, 'private://');
  1437. $file_url = file_create_url($uri);
  1438. $this->drupalGet($file_url);
  1439. $this->assertResponse(403, 'Access is not granted to an arbitrary private file by default.');
  1440. variable_set('file_module_test_grant_download_access', TRUE);
  1441. $this->drupalGet($file_url);
  1442. $this->assertResponse(200, 'Access is granted to an arbitrary private file after a module grants access to all private files in hook_file_download().');
  1443. // Create a public node with a file attached.
  1444. $type_name = 'page';
  1445. $field_name = strtolower($this->randomName());
  1446. $this->createFileField($field_name, $type_name, array('uri_scheme' => 'private'));
  1447. $test_file = $this->getTestFile('text');
  1448. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name, TRUE, array('private' => FALSE));
  1449. $node = node_load($nid, NULL, TRUE);
  1450. $file_url = file_create_url($node->{$field_name}[LANGUAGE_NONE][0]['uri']);
  1451. // Unpublish the node and ensure that only administrators (not anonymous
  1452. // users) can access the node and download the file; the expectation is
  1453. // that the File module's hook_file_download() implementation will deny
  1454. // access and thereby override the file_module_test module's access grant.
  1455. $node->status = NODE_NOT_PUBLISHED;
  1456. node_save($node);
  1457. $this->drupalLogin($this->admin_user);
  1458. $this->drupalGet("node/$nid");
  1459. $this->assertResponse(200, 'Administrator can access the unpublished node.');
  1460. $this->drupalGet($file_url);
  1461. $this->assertResponse(200, 'Administrator can download the file attached to the unpublished node.');
  1462. $this->drupalLogOut();
  1463. $this->drupalGet("node/$nid");
  1464. $this->assertResponse(403, 'Anonymous user cannot access the unpublished node.');
  1465. $this->drupalGet($file_url);
  1466. $this->assertResponse(403, 'Anonymous user cannot download the file attached to the unpublished node.');
  1467. // Re-publish the node and ensure that the node and file can be accessed by
  1468. // everyone.
  1469. $node->status = NODE_PUBLISHED;
  1470. node_save($node);
  1471. $this->drupalLogin($this->admin_user);
  1472. $this->drupalGet("node/$nid");
  1473. $this->assertResponse(200, 'Administrator can access the published node.');
  1474. $this->drupalGet($file_url);
  1475. $this->assertResponse(200, 'Administrator can download the file attached to the published node.');
  1476. $this->drupalLogOut();
  1477. $this->drupalGet("node/$nid");
  1478. $this->assertResponse(200, 'Anonymous user can access the published node.');
  1479. $this->drupalGet($file_url);
  1480. $this->assertResponse(200, 'Anonymous user can download the file attached to the published node.');
  1481. // Make the node private via the node access system and test that only
  1482. // administrators (not anonymous users) can access the node and download
  1483. // the file.
  1484. $node->private = TRUE;
  1485. node_save($node);
  1486. $this->drupalLogin($this->admin_user);
  1487. $this->drupalGet("node/$nid");
  1488. $this->assertResponse(200, 'Administrator can access the private node.');
  1489. $this->drupalGet($file_url);
  1490. $this->assertResponse(200, 'Administrator can download the file attached to the private node.');
  1491. $this->drupalLogOut();
  1492. $this->drupalGet("node/$nid");
  1493. $this->assertResponse(403, 'Anonymous user cannot access the private node.');
  1494. $this->drupalGet($file_url);
  1495. $this->assertResponse(403, 'Anonymous user cannot download the file attached to the private node.');
  1496. }
  1497. }
  1498. /**
  1499. * Confirm that file field submissions work correctly for anonymous visitors.
  1500. */
  1501. class FileFieldAnonymousSubmission extends FileFieldTestCase {
  1502. public static function getInfo() {
  1503. return array(
  1504. 'name' => 'File form anonymous submission',
  1505. 'description' => 'Test anonymous form submission.',
  1506. 'group' => 'File',
  1507. );
  1508. }
  1509. function setUp() {
  1510. parent::setUp();
  1511. // Allow node submissions by anonymous users.
  1512. user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array(
  1513. 'create article content',
  1514. 'access content',
  1515. ));
  1516. }
  1517. /**
  1518. * Tests the basic node submission for an anonymous visitor.
  1519. */
  1520. function testAnonymousNode() {
  1521. $bundle_label = 'Article';
  1522. $node_title = 'Test page';
  1523. // Load the node form.
  1524. $this->drupalGet('node/add/article');
  1525. $this->assertResponse(200, 'Loaded the article node form.');
  1526. $this->assertText(strip_tags(t('Create @name', array('@name' => $bundle_label))));
  1527. $edit = array(
  1528. 'title' => $node_title,
  1529. 'body[und][0][value]' => 'Test article',
  1530. 'body[und][0][format]' => 'filtered_html',
  1531. );
  1532. $this->drupalPost(NULL, $edit, t('Save'));
  1533. $this->assertResponse(200);
  1534. $t_args = array('@type' => $bundle_label, '%title' => $node_title);
  1535. $this->assertText(strip_tags(t('@type %title has been created.', $t_args)), 'The node was created.');
  1536. $matches = array();
  1537. if (preg_match('@node/(\d+)$@', $this->getUrl(), $matches)) {
  1538. $nid = end($matches);
  1539. $this->assertNotEqual($nid, 0, 'The node ID was extracted from the URL.');
  1540. $node = node_load($nid);
  1541. $this->assertNotEqual($node, NULL, 'The node was loaded successfully.');
  1542. }
  1543. }
  1544. /**
  1545. * Tests file submission for an anonymous visitor.
  1546. */
  1547. function testAnonymousNodeWithFile() {
  1548. $bundle_label = 'Article';
  1549. $node_title = 'Test page';
  1550. // Load the node form.
  1551. $this->drupalGet('node/add/article');
  1552. $this->assertResponse(200, 'Loaded the article node form.');
  1553. $this->assertText(strip_tags(t('Create @name', array('@name' => $bundle_label))));
  1554. // Generate an image file.
  1555. $image = $this->getTestImage();
  1556. // Submit the form.
  1557. $edit = array(
  1558. 'title' => $node_title,
  1559. 'body[und][0][value]' => 'Test article',
  1560. 'body[und][0][format]' => 'filtered_html',
  1561. 'files[field_image_und_0]' => drupal_realpath($image->uri),
  1562. );
  1563. $this->drupalPost(NULL, $edit, t('Save'));
  1564. $this->assertResponse(200);
  1565. $t_args = array('@type' => $bundle_label, '%title' => $node_title);
  1566. $this->assertText(strip_tags(t('@type %title has been created.', $t_args)), 'The node was created.');
  1567. $matches = array();
  1568. if (preg_match('@node/(\d+)$@', $this->getUrl(), $matches)) {
  1569. $nid = end($matches);
  1570. $this->assertNotEqual($nid, 0, 'The node ID was extracted from the URL.');
  1571. $node = node_load($nid);
  1572. $this->assertNotEqual($node, NULL, 'The node was loaded successfully.');
  1573. $this->assertEqual($node->field_image[LANGUAGE_NONE][0]['filename'], $image->filename, 'The image was uploaded successfully.');
  1574. }
  1575. }
  1576. /**
  1577. * Tests file submission for an anonymous visitor with a missing node title.
  1578. */
  1579. function testAnonymousNodeWithFileWithoutTitle() {
  1580. $this->drupalLogout();
  1581. $this->_testNodeWithFileWithoutTitle();
  1582. }
  1583. /**
  1584. * Tests file submission for an authenticated user with a missing node title.
  1585. */
  1586. function testAuthenticatedNodeWithFileWithoutTitle() {
  1587. $admin_user = $this->drupalCreateUser(array(
  1588. 'bypass node access',
  1589. 'access content overview',
  1590. 'administer nodes',
  1591. ));
  1592. $this->drupalLogin($admin_user);
  1593. $this->_testNodeWithFileWithoutTitle();
  1594. }
  1595. /**
  1596. * Helper method to test file submissions with missing node titles.
  1597. */
  1598. protected function _testNodeWithFileWithoutTitle() {
  1599. $bundle_label = 'Article';
  1600. $node_title = 'Test page';
  1601. // Load the node form.
  1602. $this->drupalGet('node/add/article');
  1603. $this->assertResponse(200, 'Loaded the article node form.');
  1604. $this->assertText(strip_tags(t('Create @name', array('@name' => $bundle_label))));
  1605. // Generate an image file.
  1606. $image = $this->getTestImage();
  1607. // Submit the form but exclude the title field.
  1608. $edit = array(
  1609. 'body[und][0][value]' => 'Test article',
  1610. 'body[und][0][format]' => 'filtered_html',
  1611. 'files[field_image_und_0]' => drupal_realpath($image->uri),
  1612. );
  1613. $this->drupalPost(NULL, $edit, t('Save'));
  1614. $this->assertResponse(200);
  1615. $t_args = array('@type' => $bundle_label, '%title' => $node_title);
  1616. $this->assertNoText(strip_tags(t('@type %title has been created.', $t_args)), 'The node was created.');
  1617. $this->assertText(t('!name field is required.', array('!name' => t('Title'))));
  1618. // Submit the form again but this time with the missing title field. This
  1619. // should still work.
  1620. $edit = array(
  1621. 'title' => $node_title,
  1622. );
  1623. $this->drupalPost(NULL, $edit, t('Save'));
  1624. // Confirm the final submission actually worked.
  1625. $t_args = array('@type' => $bundle_label, '%title' => $node_title);
  1626. $this->assertText(strip_tags(t('@type %title has been created.', $t_args)), 'The node was created.');
  1627. $matches = array();
  1628. if (preg_match('@node/(\d+)$@', $this->getUrl(), $matches)) {
  1629. $nid = end($matches);
  1630. $this->assertNotEqual($nid, 0, 'The node ID was extracted from the URL.');
  1631. $node = node_load($nid);
  1632. $this->assertNotEqual($node, NULL, 'The node was loaded successfully.');
  1633. $this->assertEqual($node->field_image[LANGUAGE_NONE][0]['filename'], $image->filename, 'The image was uploaded successfully.');
  1634. }
  1635. }
  1636. /**
  1637. * Generates a test image.
  1638. *
  1639. * @return stdClass
  1640. * A file object.
  1641. */
  1642. function getTestImage() {
  1643. // Get a file to upload.
  1644. $file = current($this->drupalGetTestFiles('image'));
  1645. // Add a filesize property to files as would be read by file_load().
  1646. $file->filesize = filesize($file->uri);
  1647. return $file;
  1648. }
  1649. }
  1650. /**
  1651. * Tests the file_scan_directory() function.
  1652. */
  1653. class FileScanDirectory extends FileFieldTestCase {
  1654. /**
  1655. * @var string
  1656. */
  1657. protected $path;
  1658. /**
  1659. * {@inheritdoc}
  1660. */
  1661. public static function getInfo() {
  1662. return array(
  1663. 'name' => 'File ScanDirectory',
  1664. 'description' => 'Tests the file_scan_directory() function.',
  1665. 'group' => 'File',
  1666. );
  1667. }
  1668. /**
  1669. * {@inheritdoc}
  1670. */
  1671. function setUp() {
  1672. parent::setUp();
  1673. $this->path = 'modules/file/tests/fixtures/file_scan_ignore';
  1674. }
  1675. /**
  1676. * Tests file_scan_directory() obeys 'file_scan_ignore_directories' setting.
  1677. * If nomask is not passed as argument, it should use the default settings.
  1678. * If nomask is passed as argument, it should obey this rule.
  1679. */
  1680. public function testNoMask() {
  1681. $files = file_scan_directory($this->path, '/\.txt$/');
  1682. $this->assertEqual(3, count($files), '3 text files found when not ignoring directories.');
  1683. global $conf;
  1684. $conf['file_scan_ignore_directories'] = array('frontend_framework');
  1685. $files = file_scan_directory($this->path, '/\.txt$/');
  1686. $this->assertEqual(1, count($files), '1 text files found when ignoring directories called "frontend_framework".');
  1687. // Make that directories specified by default still work when a new nomask is provided.
  1688. $files = file_scan_directory($this->path, '/\.txt$/', array('nomask' => '/^c.txt/'));
  1689. $this->assertEqual(2, count($files), '2 text files found when an "nomask" option is passed in.');
  1690. // Ensure that the directories in file_scan_ignore_directories are escaped using preg_quote.
  1691. $conf['file_scan_ignore_directories'] = array('frontend.*');
  1692. $files = file_scan_directory($this->path, '/\.txt$/');
  1693. $this->assertEqual(3, count($files), '2 text files found when ignoring a directory that is not there.');
  1694. }
  1695. }