file.test 125 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116
  1. <?php
  2. /**
  3. * @file
  4. * This provides SimpleTests for the core file handling functionality.
  5. * These include FileValidateTest and FileSaveTest.
  6. */
  7. /**
  8. * Helper validator that returns the $errors parameter.
  9. */
  10. function file_test_validator($file, $errors) {
  11. return $errors;
  12. }
  13. /**
  14. * Helper function for testing file_scan_directory().
  15. *
  16. * Each time the function is called the file is stored in a static variable.
  17. * When the function is called with no $filepath parameter, the results are
  18. * returned.
  19. *
  20. * @param $filepath
  21. * File path
  22. * @return
  23. * If $filepath is NULL, an array of all previous $filepath parameters
  24. */
  25. function file_test_file_scan_callback($filepath = NULL) {
  26. $files = &drupal_static(__FUNCTION__, array());
  27. if (isset($filepath)) {
  28. $files[] = $filepath;
  29. }
  30. else {
  31. return $files;
  32. }
  33. }
  34. /**
  35. * Reset static variables used by file_test_file_scan_callback().
  36. */
  37. function file_test_file_scan_callback_reset() {
  38. drupal_static_reset('file_test_file_scan_callback');
  39. }
  40. /**
  41. * Base class for file tests that adds some additional file specific
  42. * assertions and helper functions.
  43. */
  44. class FileTestCase extends DrupalWebTestCase {
  45. /**
  46. * Check that two files have the same values for all fields other than the
  47. * timestamp.
  48. *
  49. * @param $before
  50. * File object to compare.
  51. * @param $after
  52. * File object to compare.
  53. */
  54. function assertFileUnchanged($before, $after) {
  55. $this->assertEqual($before->fid, $after->fid, format_string('File id is the same: %file1 == %file2.', array('%file1' => $before->fid, '%file2' => $after->fid)), 'File unchanged');
  56. $this->assertEqual($before->uid, $after->uid, format_string('File owner is the same: %file1 == %file2.', array('%file1' => $before->uid, '%file2' => $after->uid)), 'File unchanged');
  57. $this->assertEqual($before->filename, $after->filename, format_string('File name is the same: %file1 == %file2.', array('%file1' => $before->filename, '%file2' => $after->filename)), 'File unchanged');
  58. $this->assertEqual($before->uri, $after->uri, format_string('File path is the same: %file1 == %file2.', array('%file1' => $before->uri, '%file2' => $after->uri)), 'File unchanged');
  59. $this->assertEqual($before->filemime, $after->filemime, format_string('File MIME type is the same: %file1 == %file2.', array('%file1' => $before->filemime, '%file2' => $after->filemime)), 'File unchanged');
  60. $this->assertEqual($before->filesize, $after->filesize, format_string('File size is the same: %file1 == %file2.', array('%file1' => $before->filesize, '%file2' => $after->filesize)), 'File unchanged');
  61. $this->assertEqual($before->status, $after->status, format_string('File status is the same: %file1 == %file2.', array('%file1' => $before->status, '%file2' => $after->status)), 'File unchanged');
  62. }
  63. /**
  64. * Check that two files are not the same by comparing the fid and filepath.
  65. *
  66. * @param $file1
  67. * File object to compare.
  68. * @param $file2
  69. * File object to compare.
  70. */
  71. function assertDifferentFile($file1, $file2) {
  72. $this->assertNotEqual($file1->fid, $file2->fid, format_string('Files have different ids: %file1 != %file2.', array('%file1' => $file1->fid, '%file2' => $file2->fid)), 'Different file');
  73. $this->assertNotEqual($file1->uri, $file2->uri, format_string('Files have different paths: %file1 != %file2.', array('%file1' => $file1->uri, '%file2' => $file2->uri)), 'Different file');
  74. }
  75. /**
  76. * Check that two files are the same by comparing the fid and filepath.
  77. *
  78. * @param $file1
  79. * File object to compare.
  80. * @param $file2
  81. * File object to compare.
  82. */
  83. function assertSameFile($file1, $file2) {
  84. $this->assertEqual($file1->fid, $file2->fid, format_string('Files have the same ids: %file1 == %file2.', array('%file1' => $file1->fid, '%file2-fid' => $file2->fid)), 'Same file');
  85. $this->assertEqual($file1->uri, $file2->uri, format_string('Files have the same path: %file1 == %file2.', array('%file1' => $file1->uri, '%file2' => $file2->uri)), 'Same file');
  86. }
  87. /**
  88. * Helper function to test the permissions of a file.
  89. *
  90. * @param $filepath
  91. * String file path.
  92. * @param $expected_mode
  93. * Octal integer like 0664 or 0777.
  94. * @param $message
  95. * Optional message.
  96. */
  97. function assertFilePermissions($filepath, $expected_mode, $message = NULL) {
  98. // Clear out PHP's file stat cache to be sure we see the current value.
  99. clearstatcache();
  100. // Mask out all but the last three octets.
  101. $actual_mode = fileperms($filepath) & 0777;
  102. $expected_mode = $expected_mode & 0777;
  103. // PHP on Windows has limited support for file permissions. Usually each of
  104. // "user", "group" and "other" use one octal digit (3 bits) to represent the
  105. // read/write/execute bits. On Windows, chmod() ignores the "group" and
  106. // "other" bits, and fileperms() returns the "user" bits in all three
  107. // positions. $expected_mode is updated to reflect this.
  108. if (substr(PHP_OS, 0, 3) == 'WIN') {
  109. // Reset the "group" and "other" bits.
  110. $expected_mode = $expected_mode & 0700;
  111. // Shift the "user" bits to the "group" and "other" positions also.
  112. $expected_mode = $expected_mode | $expected_mode >> 3 | $expected_mode >> 6;
  113. }
  114. if (!isset($message)) {
  115. $message = t('Expected file permission to be %expected, actually were %actual.', array('%actual' => decoct($actual_mode), '%expected' => decoct($expected_mode)));
  116. }
  117. $this->assertEqual($actual_mode, $expected_mode, $message);
  118. }
  119. /**
  120. * Helper function to test the permissions of a directory.
  121. *
  122. * @param $directory
  123. * String directory path.
  124. * @param $expected_mode
  125. * Octal integer like 0664 or 0777.
  126. * @param $message
  127. * Optional message.
  128. */
  129. function assertDirectoryPermissions($directory, $expected_mode, $message = NULL) {
  130. // Clear out PHP's file stat cache to be sure we see the current value.
  131. clearstatcache();
  132. // Mask out all but the last three octets.
  133. $actual_mode = fileperms($directory) & 0777;
  134. $expected_mode = $expected_mode & 0777;
  135. // PHP on Windows has limited support for file permissions. Usually each of
  136. // "user", "group" and "other" use one octal digit (3 bits) to represent the
  137. // read/write/execute bits. On Windows, chmod() ignores the "group" and
  138. // "other" bits, and fileperms() returns the "user" bits in all three
  139. // positions. $expected_mode is updated to reflect this.
  140. if (substr(PHP_OS, 0, 3) == 'WIN') {
  141. // Reset the "group" and "other" bits.
  142. $expected_mode = $expected_mode & 0700;
  143. // Shift the "user" bits to the "group" and "other" positions also.
  144. $expected_mode = $expected_mode | $expected_mode >> 3 | $expected_mode >> 6;
  145. }
  146. if (!isset($message)) {
  147. $message = t('Expected directory permission to be %expected, actually were %actual.', array('%actual' => decoct($actual_mode), '%expected' => decoct($expected_mode)));
  148. }
  149. $this->assertEqual($actual_mode, $expected_mode, $message);
  150. }
  151. /**
  152. * Create a directory and assert it exists.
  153. *
  154. * @param $path
  155. * Optional string with a directory path. If none is provided, a random
  156. * name in the site's files directory will be used.
  157. * @return
  158. * The path to the directory.
  159. */
  160. function createDirectory($path = NULL) {
  161. // A directory to operate on.
  162. if (!isset($path)) {
  163. $path = file_default_scheme() . '://' . $this->randomName();
  164. }
  165. $this->assertTrue(drupal_mkdir($path) && is_dir($path), 'Directory was created successfully.');
  166. return $path;
  167. }
  168. /**
  169. * Create a file and save it to the files table and assert that it occurs
  170. * correctly.
  171. *
  172. * @param $filepath
  173. * Optional string specifying the file path. If none is provided then a
  174. * randomly named file will be created in the site's files directory.
  175. * @param $contents
  176. * Optional contents to save into the file. If a NULL value is provided an
  177. * arbitrary string will be used.
  178. * @param $scheme
  179. * Optional string indicating the stream scheme to use. Drupal core includes
  180. * public, private, and temporary. The public wrapper is the default.
  181. * @return
  182. * File object.
  183. */
  184. function createFile($filepath = NULL, $contents = NULL, $scheme = NULL) {
  185. if (!isset($filepath)) {
  186. // Prefix with non-latin characters to ensure that all file-related
  187. // tests work with international filenames.
  188. $filepath = 'Файл для тестирования ' . $this->randomName();
  189. }
  190. if (!isset($scheme)) {
  191. $scheme = file_default_scheme();
  192. }
  193. $filepath = $scheme . '://' . $filepath;
  194. if (!isset($contents)) {
  195. $contents = "file_put_contents() doesn't seem to appreciate empty strings so let's put in some data.";
  196. }
  197. file_put_contents($filepath, $contents);
  198. $this->assertTrue(is_file($filepath), 'The test file exists on the disk.', 'Create test file');
  199. $file = new stdClass();
  200. $file->uri = $filepath;
  201. $file->filename = drupal_basename($file->uri);
  202. $file->filemime = 'text/plain';
  203. $file->uid = 1;
  204. $file->timestamp = REQUEST_TIME;
  205. $file->filesize = filesize($file->uri);
  206. $file->status = 0;
  207. // Write the record directly rather than calling file_save() so we don't
  208. // invoke the hooks.
  209. $this->assertNotIdentical(drupal_write_record('file_managed', $file), FALSE, 'The file was added to the database.', 'Create test file');
  210. return $file;
  211. }
  212. }
  213. /**
  214. * Base class for file tests that use the file_test module to test uploads and
  215. * hooks.
  216. */
  217. class FileHookTestCase extends FileTestCase {
  218. function setUp() {
  219. // Install file_test module
  220. parent::setUp('file_test');
  221. // Clear out any hook calls.
  222. file_test_reset();
  223. }
  224. /**
  225. * Assert that all of the specified hook_file_* hooks were called once, other
  226. * values result in failure.
  227. *
  228. * @param $expected
  229. * Array with string containing with the hook name, e.g. 'load', 'save',
  230. * 'insert', etc.
  231. */
  232. function assertFileHooksCalled($expected) {
  233. // Determine which hooks were called.
  234. $actual = array_keys(array_filter(file_test_get_all_calls()));
  235. // Determine if there were any expected that were not called.
  236. $uncalled = array_diff($expected, $actual);
  237. if (count($uncalled)) {
  238. $this->assertTrue(FALSE, format_string('Expected hooks %expected to be called but %uncalled was not called.', array('%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled))));
  239. }
  240. else {
  241. $this->assertTrue(TRUE, format_string('All the expected hooks were called: %expected', array('%expected' => empty($expected) ? t('(none)') : implode(', ', $expected))));
  242. }
  243. // Determine if there were any unexpected calls.
  244. $unexpected = array_diff($actual, $expected);
  245. if (count($unexpected)) {
  246. $this->assertTrue(FALSE, format_string('Unexpected hooks were called: %unexpected.', array('%unexpected' => empty($unexpected) ? t('(none)') : implode(', ', $unexpected))));
  247. }
  248. else {
  249. $this->assertTrue(TRUE, 'No unexpected hooks were called.');
  250. }
  251. }
  252. /**
  253. * Assert that a hook_file_* hook was called a certain number of times.
  254. *
  255. * @param $hook
  256. * String with the hook name, e.g. 'load', 'save', 'insert', etc.
  257. * @param $expected_count
  258. * Optional integer count.
  259. * @param $message
  260. * Optional translated string message.
  261. */
  262. function assertFileHookCalled($hook, $expected_count = 1, $message = NULL) {
  263. $actual_count = count(file_test_get_calls($hook));
  264. if (!isset($message)) {
  265. if ($actual_count == $expected_count) {
  266. $message = format_string('hook_file_@name was called correctly.', array('@name' => $hook));
  267. }
  268. elseif ($expected_count == 0) {
  269. $message = format_plural($actual_count, 'hook_file_@name was not expected to be called but was actually called once.', 'hook_file_@name was not expected to be called but was actually called @count times.', array('@name' => $hook, '@count' => $actual_count));
  270. }
  271. else {
  272. $message = format_string('hook_file_@name was expected to be called %expected times but was called %actual times.', array('@name' => $hook, '%expected' => $expected_count, '%actual' => $actual_count));
  273. }
  274. }
  275. $this->assertEqual($actual_count, $expected_count, $message);
  276. }
  277. }
  278. /**
  279. * This will run tests against the file_space_used() function.
  280. */
  281. class FileSpaceUsedTest extends FileTestCase {
  282. public static function getInfo() {
  283. return array(
  284. 'name' => 'File space used tests',
  285. 'description' => 'Tests the file_space_used() function.',
  286. 'group' => 'File API',
  287. );
  288. }
  289. function setUp() {
  290. parent::setUp();
  291. // Create records for a couple of users with different sizes.
  292. $file = array('uid' => 2, 'uri' => 'public://example1.txt', 'filesize' => 50, 'status' => FILE_STATUS_PERMANENT);
  293. drupal_write_record('file_managed', $file);
  294. $file = array('uid' => 2, 'uri' => 'public://example2.txt', 'filesize' => 20, 'status' => FILE_STATUS_PERMANENT);
  295. drupal_write_record('file_managed', $file);
  296. $file = array('uid' => 3, 'uri' => 'public://example3.txt', 'filesize' => 100, 'status' => FILE_STATUS_PERMANENT);
  297. drupal_write_record('file_managed', $file);
  298. $file = array('uid' => 3, 'uri' => 'public://example4.txt', 'filesize' => 200, 'status' => FILE_STATUS_PERMANENT);
  299. drupal_write_record('file_managed', $file);
  300. // Now create some non-permanent files.
  301. $file = array('uid' => 2, 'uri' => 'public://example5.txt', 'filesize' => 1, 'status' => 0);
  302. drupal_write_record('file_managed', $file);
  303. $file = array('uid' => 3, 'uri' => 'public://example6.txt', 'filesize' => 3, 'status' => 0);
  304. drupal_write_record('file_managed', $file);
  305. }
  306. /**
  307. * Test different users with the default status.
  308. */
  309. function testFileSpaceUsed() {
  310. // Test different users with default status.
  311. $this->assertEqual(file_space_used(2), 70);
  312. $this->assertEqual(file_space_used(3), 300);
  313. $this->assertEqual(file_space_used(), 370);
  314. // Test the status fields
  315. $this->assertEqual(file_space_used(NULL, 0), 4);
  316. $this->assertEqual(file_space_used(NULL, FILE_STATUS_PERMANENT), 370);
  317. // Test both the user and status.
  318. $this->assertEqual(file_space_used(1, 0), 0);
  319. $this->assertEqual(file_space_used(1, FILE_STATUS_PERMANENT), 0);
  320. $this->assertEqual(file_space_used(2, 0), 1);
  321. $this->assertEqual(file_space_used(2, FILE_STATUS_PERMANENT), 70);
  322. $this->assertEqual(file_space_used(3, 0), 3);
  323. $this->assertEqual(file_space_used(3, FILE_STATUS_PERMANENT), 300);
  324. }
  325. }
  326. /**
  327. * This will run tests against the file validation functions (file_validate_*).
  328. */
  329. class FileValidatorTest extends DrupalWebTestCase {
  330. protected $image;
  331. protected $non_image;
  332. public static function getInfo() {
  333. return array(
  334. 'name' => 'File validator tests',
  335. 'description' => 'Tests the functions used to validate uploaded files.',
  336. 'group' => 'File API',
  337. );
  338. }
  339. function setUp() {
  340. parent::setUp();
  341. $this->image = new stdClass();
  342. $this->image->uri = 'misc/druplicon.png';
  343. $this->image->filename = drupal_basename($this->image->uri);
  344. $this->non_image = new stdClass();
  345. $this->non_image->uri = 'misc/jquery.js';
  346. $this->non_image->filename = drupal_basename($this->non_image->uri);
  347. }
  348. /**
  349. * Test the file_validate_extensions() function.
  350. */
  351. function testFileValidateExtensions() {
  352. $file = new stdClass();
  353. $file->filename = 'asdf.txt';
  354. $errors = file_validate_extensions($file, 'asdf txt pork');
  355. $this->assertEqual(count($errors), 0, 'Valid extension accepted.', 'File');
  356. $file->filename = 'asdf.txt';
  357. $errors = file_validate_extensions($file, 'exe png');
  358. $this->assertEqual(count($errors), 1, 'Invalid extension blocked.', 'File');
  359. }
  360. /**
  361. * This ensures a specific file is actually an image.
  362. */
  363. function testFileValidateIsImage() {
  364. $this->assertTrue(file_exists($this->image->uri), 'The image being tested exists.', 'File');
  365. $errors = file_validate_is_image($this->image);
  366. $this->assertEqual(count($errors), 0, 'No error reported for our image file.', 'File');
  367. $this->assertTrue(file_exists($this->non_image->uri), 'The non-image being tested exists.', 'File');
  368. $errors = file_validate_is_image($this->non_image);
  369. $this->assertEqual(count($errors), 1, 'An error reported for our non-image file.', 'File');
  370. }
  371. /**
  372. * This ensures the resolution of a specific file is within bounds.
  373. * The image will be resized if it's too large.
  374. */
  375. function testFileValidateImageResolution() {
  376. // Non-images.
  377. $errors = file_validate_image_resolution($this->non_image);
  378. $this->assertEqual(count($errors), 0, 'Should not get any errors for a non-image file.', 'File');
  379. $errors = file_validate_image_resolution($this->non_image, '50x50', '100x100');
  380. $this->assertEqual(count($errors), 0, 'Do not check the resolution on non files.', 'File');
  381. // Minimum size.
  382. $errors = file_validate_image_resolution($this->image);
  383. $this->assertEqual(count($errors), 0, 'No errors for an image when there is no minimum or maximum resolution.', 'File');
  384. $errors = file_validate_image_resolution($this->image, 0, '200x1');
  385. $this->assertEqual(count($errors), 1, 'Got an error for an image that was not wide enough.', 'File');
  386. $errors = file_validate_image_resolution($this->image, 0, '1x200');
  387. $this->assertEqual(count($errors), 1, 'Got an error for an image that was not tall enough.', 'File');
  388. $errors = file_validate_image_resolution($this->image, 0, '200x200');
  389. $this->assertEqual(count($errors), 1, 'Small images report an error.', 'File');
  390. // Maximum size.
  391. if (image_get_toolkit()) {
  392. // Copy the image so that the original doesn't get resized.
  393. copy('misc/druplicon.png', 'temporary://druplicon.png');
  394. $this->image->uri = 'temporary://druplicon.png';
  395. $errors = file_validate_image_resolution($this->image, '10x5');
  396. $this->assertEqual(count($errors), 0, 'No errors should be reported when an oversized image can be scaled down.', 'File');
  397. $info = image_get_info($this->image->uri);
  398. $this->assertTrue($info['width'] <= 10, 'Image scaled to correct width.', 'File');
  399. $this->assertTrue($info['height'] <= 5, 'Image scaled to correct height.', 'File');
  400. drupal_unlink('temporary://druplicon.png');
  401. // Combine maximum and minimum size.
  402. copy('misc/druplicon.png', 'temporary://druplicon.png');
  403. $this->image->uri = 'temporary://druplicon.png';
  404. $errors = file_validate_image_resolution($this->image, '10x5', '5x5');
  405. $this->assertEqual(count($errors), 1, 'Got an error for an image that was too small after resizing to maximum size.', 'File');
  406. drupal_unlink('temporary://druplicon.png');
  407. }
  408. else {
  409. // TODO: should check that the error is returned if no toolkit is available.
  410. $errors = file_validate_image_resolution($this->image, '5x10');
  411. $this->assertEqual(count($errors), 1, 'Oversize images that cannot be scaled get an error.', 'File');
  412. }
  413. }
  414. /**
  415. * This will ensure the filename length is valid.
  416. */
  417. function testFileValidateNameLength() {
  418. // Create a new file object.
  419. $file = new stdClass();
  420. // Add a filename with an allowed length and test it.
  421. $file->filename = str_repeat('x', 240);
  422. $this->assertEqual(strlen($file->filename), 240);
  423. $errors = file_validate_name_length($file);
  424. $this->assertEqual(count($errors), 0, 'No errors reported for 240 length filename.', 'File');
  425. // Add a filename with a length too long and test it.
  426. $file->filename = str_repeat('x', 241);
  427. $errors = file_validate_name_length($file);
  428. $this->assertEqual(count($errors), 1, 'An error reported for 241 length filename.', 'File');
  429. // Add a filename with an empty string and test it.
  430. $file->filename = '';
  431. $errors = file_validate_name_length($file);
  432. $this->assertEqual(count($errors), 1, 'An error reported for 0 length filename.', 'File');
  433. }
  434. /**
  435. * Test file_validate_size().
  436. */
  437. function testFileValidateSize() {
  438. // Create a file with a size of 1000 bytes, and quotas of only 1 byte.
  439. $file = new stdClass();
  440. $file->filesize = 1000;
  441. $errors = file_validate_size($file, 0, 0);
  442. $this->assertEqual(count($errors), 0, 'No limits means no errors.', 'File');
  443. $errors = file_validate_size($file, 1, 0);
  444. $this->assertEqual(count($errors), 1, 'Error for the file being over the limit.', 'File');
  445. $errors = file_validate_size($file, 0, 1);
  446. $this->assertEqual(count($errors), 1, 'Error for the user being over their limit.', 'File');
  447. $errors = file_validate_size($file, 1, 1);
  448. $this->assertEqual(count($errors), 2, 'Errors for both the file and their limit.', 'File');
  449. }
  450. }
  451. /**
  452. * Tests the file_unmanaged_save_data() function.
  453. */
  454. class FileUnmanagedSaveDataTest extends FileTestCase {
  455. public static function getInfo() {
  456. return array(
  457. 'name' => 'Unmanaged file save data',
  458. 'description' => 'Tests the unmanaged file save data function.',
  459. 'group' => 'File API',
  460. );
  461. }
  462. /**
  463. * Test the file_unmanaged_save_data() function.
  464. */
  465. function testFileSaveData() {
  466. $contents = $this->randomName(8);
  467. // No filename.
  468. $filepath = file_unmanaged_save_data($contents);
  469. $this->assertTrue($filepath, 'Unnamed file saved correctly.');
  470. $this->assertEqual(file_uri_scheme($filepath), file_default_scheme(), "File was placed in Drupal's files directory.");
  471. $this->assertEqual($contents, file_get_contents($filepath), 'Contents of the file are correct.');
  472. // Provide a filename.
  473. $filepath = file_unmanaged_save_data($contents, 'public://asdf.txt', FILE_EXISTS_REPLACE);
  474. $this->assertTrue($filepath, 'Unnamed file saved correctly.');
  475. $this->assertEqual('asdf.txt', drupal_basename($filepath), 'File was named correctly.');
  476. $this->assertEqual($contents, file_get_contents($filepath), 'Contents of the file are correct.');
  477. $this->assertFilePermissions($filepath, variable_get('file_chmod_file', 0664));
  478. }
  479. }
  480. /**
  481. * Tests the file_unmanaged_save_data() function on remote filesystems.
  482. */
  483. class RemoteFileUnmanagedSaveDataTest extends FileUnmanagedSaveDataTest {
  484. public static function getInfo() {
  485. $info = parent::getInfo();
  486. $info['group'] = 'File API (remote)';
  487. return $info;
  488. }
  489. function setUp() {
  490. parent::setUp('file_test');
  491. variable_set('file_default_scheme', 'dummy-remote');
  492. }
  493. }
  494. /**
  495. * Test the file_save_upload() function.
  496. */
  497. class FileSaveUploadTest extends FileHookTestCase {
  498. /**
  499. * An image file path for uploading.
  500. */
  501. protected $image;
  502. /**
  503. * A PHP file path for upload security testing.
  504. */
  505. protected $phpfile;
  506. /**
  507. * The largest file id when the test starts.
  508. */
  509. protected $maxFidBefore;
  510. /**
  511. * An image extension.
  512. */
  513. protected $image_extension;
  514. public static function getInfo() {
  515. return array(
  516. 'name' => 'File uploading',
  517. 'description' => 'Tests the file uploading functions.',
  518. 'group' => 'File API',
  519. );
  520. }
  521. function setUp() {
  522. parent::setUp();
  523. $account = $this->drupalCreateUser(array('access content'));
  524. $this->drupalLogin($account);
  525. $image_files = $this->drupalGetTestFiles('image');
  526. $this->image = current($image_files);
  527. list(, $this->image_extension) = explode('.', $this->image->filename);
  528. $this->assertTrue(is_file($this->image->uri), "The image file we're going to upload exists.");
  529. $this->phpfile = current($this->drupalGetTestFiles('php'));
  530. $this->assertTrue(is_file($this->phpfile->uri), "The PHP file we're going to upload exists.");
  531. $this->maxFidBefore = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
  532. // Upload with replace to guarantee there's something there.
  533. $edit = array(
  534. 'file_test_replace' => FILE_EXISTS_REPLACE,
  535. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  536. );
  537. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  538. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  539. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  540. // Check that the correct hooks were called then clean out the hook
  541. // counters.
  542. $this->assertFileHooksCalled(array('validate', 'insert'));
  543. file_test_reset();
  544. }
  545. /**
  546. * Test the file_save_upload() function.
  547. */
  548. function testNormal() {
  549. $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
  550. $this->assertTrue($max_fid_after > $this->maxFidBefore, 'A new file was created.');
  551. $file1 = file_load($max_fid_after);
  552. $this->assertTrue($file1, 'Loaded the file.');
  553. // MIME type of the uploaded image may be either image/jpeg or image/png.
  554. $this->assertEqual(substr($file1->filemime, 0, 5), 'image', 'A MIME type was set.');
  555. // Reset the hook counters to get rid of the 'load' we just called.
  556. file_test_reset();
  557. // Upload a second file.
  558. $max_fid_before = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
  559. $image2 = current($this->drupalGetTestFiles('image'));
  560. $edit = array('files[file_test_upload]' => drupal_realpath($image2->uri));
  561. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  562. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  563. $this->assertRaw(t('You WIN!'));
  564. $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
  565. // Check that the correct hooks were called.
  566. $this->assertFileHooksCalled(array('validate', 'insert'));
  567. $file2 = file_load($max_fid_after);
  568. $this->assertTrue($file2);
  569. // MIME type of the uploaded image may be either image/jpeg or image/png.
  570. $this->assertEqual(substr($file2->filemime, 0, 5), 'image', 'A MIME type was set.');
  571. // Load both files using file_load_multiple().
  572. $files = file_load_multiple(array($file1->fid, $file2->fid));
  573. $this->assertTrue(isset($files[$file1->fid]), 'File was loaded successfully');
  574. $this->assertTrue(isset($files[$file2->fid]), 'File was loaded successfully');
  575. // Upload a third file to a subdirectory.
  576. $image3 = current($this->drupalGetTestFiles('image'));
  577. $image3_realpath = drupal_realpath($image3->uri);
  578. $dir = $this->randomName();
  579. $edit = array(
  580. 'files[file_test_upload]' => $image3_realpath,
  581. 'file_subdir' => $dir,
  582. );
  583. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  584. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  585. $this->assertRaw(t('You WIN!'));
  586. $this->assertTrue(is_file('temporary://' . $dir . '/' . trim(drupal_basename($image3_realpath))));
  587. // Check that file_load_multiple() with no arguments returns FALSE.
  588. $this->assertFalse(file_load_multiple(), 'No files were loaded.');
  589. }
  590. /**
  591. * Test extension handling.
  592. */
  593. function testHandleExtension() {
  594. // The file being tested is a .gif which is in the default safe list
  595. // of extensions to allow when the extension validator isn't used. This is
  596. // implicitly tested at the testNormal() test. Here we tell
  597. // file_save_upload() to only allow ".foo".
  598. $extensions = 'foo';
  599. $edit = array(
  600. 'file_test_replace' => FILE_EXISTS_REPLACE,
  601. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  602. 'extensions' => $extensions,
  603. );
  604. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  605. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  606. $message = t('Only files with the following extensions are allowed:') . ' <em class="placeholder">' . $extensions . '</em>';
  607. $this->assertRaw($message, 'Cannot upload a disallowed extension');
  608. $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
  609. // Check that the correct hooks were called.
  610. $this->assertFileHooksCalled(array('validate'));
  611. // Reset the hook counters.
  612. file_test_reset();
  613. $extensions = 'foo ' . $this->image_extension;
  614. // Now tell file_save_upload() to allow the extension of our test image.
  615. $edit = array(
  616. 'file_test_replace' => FILE_EXISTS_REPLACE,
  617. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  618. 'extensions' => $extensions,
  619. );
  620. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  621. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  622. $this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload an allowed extension.');
  623. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  624. // Check that the correct hooks were called.
  625. $this->assertFileHooksCalled(array('validate', 'load', 'update'));
  626. // Reset the hook counters.
  627. file_test_reset();
  628. // Now tell file_save_upload() to allow any extension.
  629. $edit = array(
  630. 'file_test_replace' => FILE_EXISTS_REPLACE,
  631. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  632. 'allow_all_extensions' => 'empty_array',
  633. );
  634. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  635. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  636. $this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload any extension.');
  637. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  638. // Check that the correct hooks were called.
  639. $this->assertFileHooksCalled(array('validate', 'load', 'update'));
  640. // Reset the hook counters.
  641. file_test_reset();
  642. // Now tell file_save_upload() to allow any extension and try and upload a
  643. // malicious file.
  644. $edit = array(
  645. 'file_test_replace' => FILE_EXISTS_REPLACE,
  646. 'files[file_test_upload]' => drupal_realpath($this->phpfile->uri),
  647. 'is_image_file' => FALSE,
  648. 'allow_all_extensions' => 'empty_array',
  649. );
  650. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  651. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  652. $message = t('For security reasons, your upload has been renamed to') . ' <em class="placeholder">' . $this->phpfile->filename . '_.txt' . '</em>';
  653. $this->assertRaw($message, 'Dangerous file was renamed.');
  654. $this->assertText('File name is php-2.php_.txt.');
  655. $this->assertRaw(t('File MIME type is text/plain.'), "Dangerous file's MIME type was changed.");
  656. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  657. // Check that the correct hooks were called.
  658. $this->assertFileHooksCalled(array('validate', 'insert'));
  659. }
  660. /**
  661. * Test dangerous file handling.
  662. */
  663. function testHandleDangerousFile() {
  664. // Allow the .php extension and make sure it gets munged and given a .txt
  665. // extension for safety. Also check to make sure its MIME type was changed.
  666. $edit = array(
  667. 'file_test_replace' => FILE_EXISTS_REPLACE,
  668. 'files[file_test_upload]' => drupal_realpath($this->phpfile->uri),
  669. 'is_image_file' => FALSE,
  670. 'extensions' => 'php',
  671. );
  672. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  673. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  674. $message = t('For security reasons, your upload has been renamed to') . ' <em class="placeholder">' . $this->phpfile->filename . '_.txt' . '</em>';
  675. $this->assertRaw($message, 'Dangerous file was renamed.');
  676. $this->assertRaw('File name is php-2.php_.txt.');
  677. $this->assertRaw(t('File MIME type is text/plain.'), "Dangerous file's MIME type was changed.");
  678. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  679. // Check that the correct hooks were called.
  680. $this->assertFileHooksCalled(array('validate', 'insert'));
  681. // Ensure dangerous files are not renamed when insecure uploads is TRUE.
  682. // Turn on insecure uploads.
  683. variable_set('allow_insecure_uploads', 1);
  684. // Reset the hook counters.
  685. file_test_reset();
  686. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  687. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  688. $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
  689. $this->assertRaw(t('File name is !filename', array('!filename' => $this->phpfile->filename)), 'Dangerous file was not renamed when insecure uploads is TRUE.');
  690. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  691. // Check that the correct hooks were called.
  692. $this->assertFileHooksCalled(array('validate', 'insert'));
  693. // Reset the hook counters.
  694. file_test_reset();
  695. // Even with insecure uploads allowed, the .php file should not be uploaded
  696. // if it is not explicitly included in the list of allowed extensions.
  697. $edit['extensions'] = 'foo';
  698. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  699. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  700. $message = t('Only files with the following extensions are allowed:') . ' <em class="placeholder">' . $edit['extensions'] . '</em>';
  701. $this->assertRaw($message, 'Cannot upload a disallowed extension');
  702. $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
  703. // Check that the correct hooks were called.
  704. $this->assertFileHooksCalled(array('validate'));
  705. // Reset the hook counters.
  706. file_test_reset();
  707. // Turn off insecure uploads, then try the same thing as above (ensure that
  708. // the .php file is still rejected since it's not in the list of allowed
  709. // extensions).
  710. variable_set('allow_insecure_uploads', 0);
  711. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  712. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  713. $message = t('Only files with the following extensions are allowed:') . ' <em class="placeholder">' . $edit['extensions'] . '</em>';
  714. $this->assertRaw($message, 'Cannot upload a disallowed extension');
  715. $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
  716. // Check that the correct hooks were called.
  717. $this->assertFileHooksCalled(array('validate'));
  718. // Reset the hook counters.
  719. file_test_reset();
  720. }
  721. /**
  722. * Test file munge handling.
  723. */
  724. function testHandleFileMunge() {
  725. // Ensure insecure uploads are disabled for this test.
  726. variable_set('allow_insecure_uploads', 0);
  727. $original_image_uri = $this->image->uri;
  728. $this->image = file_move($this->image, $this->image->uri . '.foo.' . $this->image_extension);
  729. // Reset the hook counters to get rid of the 'move' we just called.
  730. file_test_reset();
  731. $extensions = $this->image_extension;
  732. $edit = array(
  733. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  734. 'extensions' => $extensions,
  735. );
  736. $munged_filename = $this->image->filename;
  737. $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
  738. $munged_filename .= '_.' . $this->image_extension;
  739. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  740. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  741. $this->assertRaw(t('For security reasons, your upload has been renamed'), 'Found security message.');
  742. $this->assertRaw(t('File name is !filename', array('!filename' => $munged_filename)), 'File was successfully munged.');
  743. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  744. // Check that the correct hooks were called.
  745. $this->assertFileHooksCalled(array('validate', 'insert'));
  746. // Reset the hook counters.
  747. file_test_reset();
  748. // Ensure we don't munge the .foo extension if it is in the list of allowed
  749. // extensions.
  750. $extensions = 'foo ' . $this->image_extension;
  751. $edit = array(
  752. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  753. 'extensions' => $extensions,
  754. );
  755. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  756. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  757. $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
  758. $this->assertRaw(t('File name is @filename', array('@filename' => 'image-test.png.foo.png')), 'File was not munged when all extensions within it are allowed.');
  759. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  760. // Check that the correct hooks were called.
  761. $this->assertFileHooksCalled(array('validate', 'insert'));
  762. // Ensure we don't munge files if we're allowing any extension.
  763. // Reset the hook counters.
  764. file_test_reset();
  765. $edit = array(
  766. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  767. 'allow_all_extensions' => 'empty_array',
  768. );
  769. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  770. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  771. $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
  772. $this->assertRaw(t('File name is !filename', array('!filename' => $this->image->filename)), 'File was not munged when allowing any extension.');
  773. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  774. // Check that the correct hooks were called.
  775. $this->assertFileHooksCalled(array('validate', 'insert'));
  776. // Test that a dangerous extension such as .php is munged even if it is in
  777. // the list of allowed extensions.
  778. $this->image = file_move($this->image, $original_image_uri . '.php.' . $this->image_extension);
  779. // Reset the hook counters.
  780. file_test_reset();
  781. $extensions = 'php ' . $this->image_extension;
  782. $edit = array(
  783. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  784. 'extensions' => $extensions,
  785. );
  786. $munged_filename = $this->image->filename;
  787. $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
  788. $munged_filename .= '_.' . $this->image_extension;
  789. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  790. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  791. $this->assertRaw(t('For security reasons, your upload has been renamed'), 'Found security message.');
  792. $this->assertRaw(t('File name is @filename', array('@filename' => $munged_filename)), 'File was successfully munged.');
  793. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  794. // Check that the correct hooks were called.
  795. $this->assertFileHooksCalled(array('validate', 'insert'));
  796. // Reset the hook counters.
  797. file_test_reset();
  798. // Dangerous extensions are munged even when all extensions are allowed.
  799. $edit = array(
  800. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  801. 'allow_all_extensions' => 'empty_array',
  802. );
  803. $munged_filename = $this->image->filename;
  804. $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
  805. $munged_filename .= '_.' . $this->image_extension;
  806. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  807. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  808. $this->assertRaw(t('For security reasons, your upload has been renamed'), 'Found security message.');
  809. $this->assertRaw(t('File name is @filename.', array('@filename' => 'image-test.png_.php_.png_.txt')), 'File was successfully munged.');
  810. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  811. // Check that the correct hooks were called.
  812. $this->assertFileHooksCalled(array('validate', 'insert'));
  813. // Dangerous extensions are munged if is renamed to end in .txt.
  814. $this->image = file_move($this->image, $original_image_uri . '.cgi.' . $this->image_extension . '.txt');
  815. // Reset the hook counters.
  816. file_test_reset();
  817. $edit = array(
  818. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  819. 'allow_all_extensions' => 'empty_array',
  820. );
  821. $munged_filename = $this->image->filename;
  822. $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
  823. $munged_filename .= '_.' . $this->image_extension;
  824. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  825. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  826. $this->assertRaw(t('For security reasons, your upload has been renamed'), 'Found security message.');
  827. $this->assertRaw(t('File name is @filename.', array('@filename' => 'image-test.png_.cgi_.png_.txt')), 'File was successfully munged.');
  828. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  829. // Check that the correct hooks were called.
  830. $this->assertFileHooksCalled(array('validate', 'insert'));
  831. // Reset the hook counters.
  832. file_test_reset();
  833. // Ensure that setting $validators['file_validate_extensions'] = array('')
  834. // rejects all files without munging or renaming.
  835. $edit = array(
  836. 'files[file_test_upload]' => drupal_realpath($this->image->uri),
  837. 'allow_all_extensions' => 'empty_string',
  838. );
  839. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  840. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  841. $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found security message.');
  842. $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
  843. // Check that the correct hooks were called.
  844. $this->assertFileHooksCalled(array('validate'));
  845. }
  846. /**
  847. * Test renaming when uploading over a file that already exists.
  848. */
  849. function testExistingRename() {
  850. $edit = array(
  851. 'file_test_replace' => FILE_EXISTS_RENAME,
  852. 'files[file_test_upload]' => drupal_realpath($this->image->uri)
  853. );
  854. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  855. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  856. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  857. // Check that the correct hooks were called.
  858. $this->assertFileHooksCalled(array('validate', 'insert'));
  859. }
  860. /**
  861. * Test replacement when uploading over a file that already exists.
  862. */
  863. function testExistingReplace() {
  864. $edit = array(
  865. 'file_test_replace' => FILE_EXISTS_REPLACE,
  866. 'files[file_test_upload]' => drupal_realpath($this->image->uri)
  867. );
  868. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  869. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  870. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  871. // Check that the correct hooks were called.
  872. $this->assertFileHooksCalled(array('validate', 'load', 'update'));
  873. }
  874. /**
  875. * Test for failure when uploading over a file that already exists.
  876. */
  877. function testExistingError() {
  878. $edit = array(
  879. 'file_test_replace' => FILE_EXISTS_ERROR,
  880. 'files[file_test_upload]' => drupal_realpath($this->image->uri)
  881. );
  882. $this->drupalPost('file-test/upload', $edit, t('Submit'));
  883. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  884. $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
  885. // Check that the no hooks were called while failing.
  886. $this->assertFileHooksCalled(array());
  887. }
  888. /**
  889. * Test for no failures when not uploading a file.
  890. */
  891. function testNoUpload() {
  892. $this->drupalPost('file-test/upload', array(), t('Submit'));
  893. $this->assertNoRaw(t('Epic upload FAIL!'), 'Failure message not found.');
  894. }
  895. }
  896. /**
  897. * Test the file_save_upload() function on remote filesystems.
  898. */
  899. class RemoteFileSaveUploadTest extends FileSaveUploadTest {
  900. public static function getInfo() {
  901. $info = parent::getInfo();
  902. $info['group'] = 'File API (remote)';
  903. return $info;
  904. }
  905. function setUp() {
  906. parent::setUp('file_test');
  907. variable_set('file_default_scheme', 'dummy-remote');
  908. }
  909. }
  910. /**
  911. * Directory related tests.
  912. */
  913. class FileDirectoryTest extends FileTestCase {
  914. public static function getInfo() {
  915. return array(
  916. 'name' => 'File paths and directories',
  917. 'description' => 'Tests operations dealing with directories.',
  918. 'group' => 'File API',
  919. );
  920. }
  921. /**
  922. * Test local directory handling functions.
  923. */
  924. function testFileCheckLocalDirectoryHandling() {
  925. $directory = file_default_scheme() . '://';
  926. // Check a new recursively created local directory for correct file system
  927. // permissions.
  928. $parent = $this->randomName();
  929. $child = $this->randomName();
  930. // Files directory already exists.
  931. $this->assertTrue(is_dir($directory), 'Files directory already exists.', 'File');
  932. // Make files directory writable only.
  933. $old_mode = fileperms($directory);
  934. // Create the directories.
  935. $parent_path = $directory . DIRECTORY_SEPARATOR . $parent;
  936. $child_path = $parent_path . DIRECTORY_SEPARATOR . $child;
  937. $this->assertTrue(drupal_mkdir($child_path, 0775, TRUE), 'No error reported when creating new local directories.', 'File');
  938. // Ensure new directories also exist.
  939. $this->assertTrue(is_dir($parent_path), 'New parent directory actually exists.', 'File');
  940. $this->assertTrue(is_dir($child_path), 'New child directory actually exists.', 'File');
  941. // Check that new directory permissions were set properly.
  942. $this->assertDirectoryPermissions($parent_path, 0775);
  943. $this->assertDirectoryPermissions($child_path, 0775);
  944. // Check that existing directory permissions were not modified.
  945. $this->assertDirectoryPermissions($directory, $old_mode);
  946. }
  947. /**
  948. * Test directory handling functions.
  949. */
  950. function testFileCheckDirectoryHandling() {
  951. // A directory to operate on.
  952. $directory = file_default_scheme() . '://' . $this->randomName() . '/' . $this->randomName();
  953. $this->assertFalse(is_dir($directory), 'Directory does not exist prior to testing.');
  954. // Non-existent directory.
  955. $this->assertFalse(file_prepare_directory($directory, 0), 'Error reported for non-existing directory.', 'File');
  956. // Make a directory.
  957. $this->assertTrue(file_prepare_directory($directory, FILE_CREATE_DIRECTORY), 'No error reported when creating a new directory.', 'File');
  958. // Make sure directory actually exists.
  959. $this->assertTrue(is_dir($directory), 'Directory actually exists.', 'File');
  960. if (substr(PHP_OS, 0, 3) != 'WIN') {
  961. // PHP on Windows doesn't support any kind of useful read-only mode for
  962. // directories. When executing a chmod() on a directory, PHP only sets the
  963. // read-only flag, which doesn't prevent files to actually be written
  964. // in the directory on any recent version of Windows.
  965. // Make directory read only.
  966. @drupal_chmod($directory, 0444);
  967. $this->assertFalse(file_prepare_directory($directory, 0), 'Error reported for a non-writeable directory.', 'File');
  968. // Test directory permission modification.
  969. $this->assertTrue(file_prepare_directory($directory, FILE_MODIFY_PERMISSIONS), 'No error reported when making directory writeable.', 'File');
  970. }
  971. // Test that the directory has the correct permissions.
  972. $this->assertDirectoryPermissions($directory, variable_get('file_chmod_directory', 0775));
  973. // Remove .htaccess file to then test that it gets re-created.
  974. @drupal_unlink(file_default_scheme() . '://.htaccess');
  975. $this->assertFalse(is_file(file_default_scheme() . '://.htaccess'), 'Successfully removed the .htaccess file in the files directory.', 'File');
  976. file_ensure_htaccess();
  977. $this->assertTrue(is_file(file_default_scheme() . '://.htaccess'), 'Successfully re-created the .htaccess file in the files directory.', 'File');
  978. // Verify contents of .htaccess file.
  979. $file = file_get_contents(file_default_scheme() . '://.htaccess');
  980. $this->assertEqual($file, file_htaccess_lines(FALSE), 'The .htaccess file contains the proper content.', 'File');
  981. }
  982. /**
  983. * This will take a directory and path, and find a valid filepath that is not
  984. * taken by another file.
  985. */
  986. function testFileCreateNewFilepath() {
  987. // First we test against an imaginary file that does not exist in a
  988. // directory.
  989. $basename = 'xyz.txt';
  990. $directory = 'misc';
  991. $original = $directory . '/' . $basename;
  992. $path = file_create_filename($basename, $directory);
  993. $this->assertEqual($path, $original, format_string('New filepath %new equals %original.', array('%new' => $path, '%original' => $original)), 'File');
  994. // Then we test against a file that already exists within that directory.
  995. $basename = 'druplicon.png';
  996. $original = $directory . '/' . $basename;
  997. $expected = $directory . '/druplicon_0.png';
  998. $path = file_create_filename($basename, $directory);
  999. $this->assertEqual($path, $expected, format_string('Creating a new filepath from %original equals %new.', array('%new' => $path, '%original' => $original)), 'File');
  1000. try {
  1001. $filename = "a\xFFtest\x80€.txt";
  1002. file_create_filename($filename, $directory);
  1003. $this->fail('Expected exception not thrown');
  1004. }
  1005. catch (RuntimeException $e) {
  1006. $this->assertEqual("Invalid filename '$filename'", $e->getMessage(), 'The invalid filename has been detected and RuntimeException has been thrown.');
  1007. }
  1008. // @TODO: Finally we copy a file into a directory several times, to ensure a properly iterating filename suffix.
  1009. }
  1010. /**
  1011. * This will test the filepath for a destination based on passed flags and
  1012. * whether or not the file exists.
  1013. *
  1014. * If a file exists, file_destination($destination, $replace) will either
  1015. * return:
  1016. * - the existing filepath, if $replace is FILE_EXISTS_REPLACE
  1017. * - a new filepath if FILE_EXISTS_RENAME
  1018. * - an error (returning FALSE) if FILE_EXISTS_ERROR.
  1019. * If the file doesn't currently exist, then it will simply return the
  1020. * filepath.
  1021. */
  1022. function testFileDestination() {
  1023. // First test for non-existent file.
  1024. $destination = 'misc/xyz.txt';
  1025. $path = file_destination($destination, FILE_EXISTS_REPLACE);
  1026. $this->assertEqual($path, $destination, 'Non-existing filepath destination is correct with FILE_EXISTS_REPLACE.', 'File');
  1027. $path = file_destination($destination, FILE_EXISTS_RENAME);
  1028. $this->assertEqual($path, $destination, 'Non-existing filepath destination is correct with FILE_EXISTS_RENAME.', 'File');
  1029. $path = file_destination($destination, FILE_EXISTS_ERROR);
  1030. $this->assertEqual($path, $destination, 'Non-existing filepath destination is correct with FILE_EXISTS_ERROR.', 'File');
  1031. $destination = 'misc/druplicon.png';
  1032. $path = file_destination($destination, FILE_EXISTS_REPLACE);
  1033. $this->assertEqual($path, $destination, 'Existing filepath destination remains the same with FILE_EXISTS_REPLACE.', 'File');
  1034. $path = file_destination($destination, FILE_EXISTS_RENAME);
  1035. $this->assertNotEqual($path, $destination, 'A new filepath destination is created when filepath destination already exists with FILE_EXISTS_RENAME.', 'File');
  1036. $path = file_destination($destination, FILE_EXISTS_ERROR);
  1037. $this->assertEqual($path, FALSE, 'An error is returned when filepath destination already exists with FILE_EXISTS_ERROR.', 'File');
  1038. try {
  1039. file_destination("core/misc/a\xFFtest\x80€.txt", FILE_EXISTS_REPLACE);
  1040. $this->fail('Expected exception not thrown');
  1041. }
  1042. catch (RuntimeException $e) {
  1043. $this->assertEqual("Invalid filename 'a\xFFtest\x80€.txt'", $e->getMessage(), 'The invalid destination has been detected and RuntimeException has been thrown.');
  1044. }
  1045. }
  1046. /**
  1047. * Ensure that the file_directory_temp() function always returns a value.
  1048. */
  1049. function testFileDirectoryTemp() {
  1050. // Start with an empty variable to ensure we have a clean slate.
  1051. variable_set('file_temporary_path', '');
  1052. $tmp_directory = file_directory_temp();
  1053. $this->assertEqual(empty($tmp_directory), FALSE, 'file_directory_temp() returned a non-empty value.');
  1054. $setting = variable_get('file_temporary_path', '');
  1055. $this->assertEqual($setting, $tmp_directory, "The 'file_temporary_path' variable has the same value that file_directory_temp() returned.");
  1056. }
  1057. }
  1058. /**
  1059. * Directory related tests.
  1060. */
  1061. class RemoteFileDirectoryTest extends FileDirectoryTest {
  1062. public static function getInfo() {
  1063. $info = parent::getInfo();
  1064. $info['group'] = 'File API (remote)';
  1065. return $info;
  1066. }
  1067. function setUp() {
  1068. parent::setUp('file_test');
  1069. variable_set('file_default_scheme', 'dummy-remote');
  1070. }
  1071. }
  1072. /**
  1073. * Tests the file_scan_directory() function.
  1074. */
  1075. class FileScanDirectoryTest extends FileTestCase {
  1076. protected $path;
  1077. public static function getInfo() {
  1078. return array(
  1079. 'name' => 'File scan directory',
  1080. 'description' => 'Tests the file_scan_directory() function.',
  1081. 'group' => 'File API',
  1082. );
  1083. }
  1084. function setUp() {
  1085. parent::setUp();
  1086. $this->path = drupal_get_path('module', 'simpletest') . '/files';
  1087. }
  1088. /**
  1089. * Check the format of the returned values.
  1090. */
  1091. function testReturn() {
  1092. // Grab a listing of all the JavaSscript files and check that they're
  1093. // passed to the callback.
  1094. $all_files = file_scan_directory($this->path, '/^javascript-/');
  1095. ksort($all_files);
  1096. $this->assertEqual(2, count($all_files), 'Found two, expected javascript files.');
  1097. // Check the first file.
  1098. $file = reset($all_files);
  1099. $this->assertEqual(key($all_files), $file->uri, 'Correct array key was used for the first returned file.');
  1100. $this->assertEqual($file->uri, $this->path . '/javascript-1.txt', 'First file name was set correctly.');
  1101. $this->assertEqual($file->filename, 'javascript-1.txt', 'First basename was set correctly');
  1102. $this->assertEqual($file->name, 'javascript-1', 'First name was set correctly.');
  1103. // Check the second file.
  1104. $file = next($all_files);
  1105. $this->assertEqual(key($all_files), $file->uri, 'Correct array key was used for the second returned file.');
  1106. $this->assertEqual($file->uri, $this->path . '/javascript-2.script', 'Second file name was set correctly.');
  1107. $this->assertEqual($file->filename, 'javascript-2.script', 'Second basename was set correctly');
  1108. $this->assertEqual($file->name, 'javascript-2', 'Second name was set correctly.');
  1109. }
  1110. /**
  1111. * Check that the callback function is called correctly.
  1112. */
  1113. function testOptionCallback() {
  1114. // When nothing is matched nothing should be passed to the callback.
  1115. $all_files = file_scan_directory($this->path, '/^NONEXISTINGFILENAME/', array('callback' => 'file_test_file_scan_callback'));
  1116. $this->assertEqual(0, count($all_files), 'No files were found.');
  1117. $results = file_test_file_scan_callback();
  1118. file_test_file_scan_callback_reset();
  1119. $this->assertEqual(0, count($results), 'No files were passed to the callback.');
  1120. // Grab a listing of all the JavaSscript files and check that they're
  1121. // passed to the callback.
  1122. $all_files = file_scan_directory($this->path, '/^javascript-/', array('callback' => 'file_test_file_scan_callback'));
  1123. $this->assertEqual(2, count($all_files), 'Found two, expected javascript files.');
  1124. $results = file_test_file_scan_callback();
  1125. file_test_file_scan_callback_reset();
  1126. $this->assertEqual(2, count($results), 'Files were passed to the callback.');
  1127. }
  1128. /**
  1129. * Check that the no-mask parameter is honored.
  1130. */
  1131. function testOptionNoMask() {
  1132. // Grab a listing of all the JavaSscript files.
  1133. $all_files = file_scan_directory($this->path, '/^javascript-/');
  1134. $this->assertEqual(2, count($all_files), 'Found two, expected javascript files.');
  1135. // Now use the nomast parameter to filter out the .script file.
  1136. $filtered_files = file_scan_directory($this->path, '/^javascript-/', array('nomask' => '/.script$/'));
  1137. $this->assertEqual(1, count($filtered_files), 'Filtered correctly.');
  1138. }
  1139. /**
  1140. * Check that key parameter sets the return value's key.
  1141. */
  1142. function testOptionKey() {
  1143. // "filename", for the path starting with $dir.
  1144. $expected = array($this->path . '/javascript-1.txt', $this->path . '/javascript-2.script');
  1145. $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'filepath')));
  1146. sort($actual);
  1147. $this->assertEqual($expected, $actual, 'Returned the correct values for the filename key.');
  1148. // "basename", for the basename of the file.
  1149. $expected = array('javascript-1.txt', 'javascript-2.script');
  1150. $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'filename')));
  1151. sort($actual);
  1152. $this->assertEqual($expected, $actual, 'Returned the correct values for the basename key.');
  1153. // "name" for the name of the file without an extension.
  1154. $expected = array('javascript-1', 'javascript-2');
  1155. $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'name')));
  1156. sort($actual);
  1157. $this->assertEqual($expected, $actual, 'Returned the correct values for the name key.');
  1158. // Invalid option that should default back to "filename".
  1159. $expected = array($this->path . '/javascript-1.txt', $this->path . '/javascript-2.script');
  1160. $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'INVALID')));
  1161. sort($actual);
  1162. $this->assertEqual($expected, $actual, 'An invalid key defaulted back to the default.');
  1163. }
  1164. /**
  1165. * Check that the recurse option decends into subdirectories.
  1166. */
  1167. function testOptionRecurse() {
  1168. $files = file_scan_directory(drupal_get_path('module', 'simpletest'), '/^javascript-/', array('recurse' => FALSE));
  1169. $this->assertTrue(empty($files), "Without recursion couldn't find javascript files.");
  1170. $files = file_scan_directory(drupal_get_path('module', 'simpletest'), '/^javascript-/', array('recurse' => TRUE));
  1171. $this->assertEqual(2, count($files), 'With recursion we found the expected javascript files.');
  1172. }
  1173. /**
  1174. * Check that the min_depth options lets us ignore files in the starting
  1175. * directory.
  1176. */
  1177. function testOptionMinDepth() {
  1178. $files = file_scan_directory($this->path, '/^javascript-/', array('min_depth' => 0));
  1179. $this->assertEqual(2, count($files), 'No minimum-depth gets files in current directory.');
  1180. $files = file_scan_directory($this->path, '/^javascript-/', array('min_depth' => 1));
  1181. $this->assertTrue(empty($files), "Minimum-depth of 1 successfully excludes files from current directory.");
  1182. }
  1183. }
  1184. /**
  1185. * Tests the file_scan_directory() function on remote filesystems.
  1186. */
  1187. class RemoteFileScanDirectoryTest extends FileScanDirectoryTest {
  1188. public static function getInfo() {
  1189. $info = parent::getInfo();
  1190. $info['group'] = 'File API (remote)';
  1191. return $info;
  1192. }
  1193. function setUp() {
  1194. parent::setUp('file_test');
  1195. variable_set('file_default_scheme', 'dummy-remote');
  1196. }
  1197. }
  1198. /**
  1199. * Deletion related tests.
  1200. */
  1201. class FileUnmanagedDeleteTest extends FileTestCase {
  1202. public static function getInfo() {
  1203. return array(
  1204. 'name' => 'Unmanaged file delete',
  1205. 'description' => 'Tests the unmanaged file delete function.',
  1206. 'group' => 'File API',
  1207. );
  1208. }
  1209. /**
  1210. * Delete a normal file.
  1211. */
  1212. function testNormal() {
  1213. // Create a file for testing
  1214. $file = $this->createFile();
  1215. // Delete a regular file
  1216. $this->assertTrue(file_unmanaged_delete($file->uri), 'Deleted worked.');
  1217. $this->assertFalse(file_exists($file->uri), 'Test file has actually been deleted.');
  1218. }
  1219. /**
  1220. * Try deleting a missing file.
  1221. */
  1222. function testMissing() {
  1223. // Try to delete a non-existing file
  1224. $this->assertTrue(file_unmanaged_delete(file_default_scheme() . '/' . $this->randomName()), 'Returns true when deleting a non-existent file.');
  1225. }
  1226. /**
  1227. * Try deleting a directory.
  1228. */
  1229. function testDirectory() {
  1230. // A directory to operate on.
  1231. $directory = $this->createDirectory();
  1232. // Try to delete a directory
  1233. $this->assertFalse(file_unmanaged_delete($directory), 'Could not delete the delete directory.');
  1234. $this->assertTrue(file_exists($directory), 'Directory has not been deleted.');
  1235. }
  1236. }
  1237. /**
  1238. * Deletion related tests on remote filesystems.
  1239. */
  1240. class RemoteFileUnmanagedDeleteTest extends FileUnmanagedDeleteTest {
  1241. public static function getInfo() {
  1242. $info = parent::getInfo();
  1243. $info['group'] = 'File API (remote)';
  1244. return $info;
  1245. }
  1246. function setUp() {
  1247. parent::setUp('file_test');
  1248. variable_set('file_default_scheme', 'dummy-remote');
  1249. }
  1250. }
  1251. /**
  1252. * Deletion related tests.
  1253. */
  1254. class FileUnmanagedDeleteRecursiveTest extends FileTestCase {
  1255. public static function getInfo() {
  1256. return array(
  1257. 'name' => 'Unmanaged recursive file delete',
  1258. 'description' => 'Tests the unmanaged file delete recursive function.',
  1259. 'group' => 'File API',
  1260. );
  1261. }
  1262. /**
  1263. * Delete a normal file.
  1264. */
  1265. function testSingleFile() {
  1266. // Create a file for testing
  1267. $filepath = file_default_scheme() . '://' . $this->randomName();
  1268. file_put_contents($filepath, '');
  1269. // Delete the file.
  1270. $this->assertTrue(file_unmanaged_delete_recursive($filepath), 'Function reported success.');
  1271. $this->assertFalse(file_exists($filepath), 'Test file has been deleted.');
  1272. }
  1273. /**
  1274. * Try deleting an empty directory.
  1275. */
  1276. function testEmptyDirectory() {
  1277. // A directory to operate on.
  1278. $directory = $this->createDirectory();
  1279. // Delete the directory.
  1280. $this->assertTrue(file_unmanaged_delete_recursive($directory), 'Function reported success.');
  1281. $this->assertFalse(file_exists($directory), 'Directory has been deleted.');
  1282. }
  1283. /**
  1284. * Try deleting a directory with some files.
  1285. */
  1286. function testDirectory() {
  1287. // A directory to operate on.
  1288. $directory = $this->createDirectory();
  1289. $filepathA = $directory . '/A';
  1290. $filepathB = $directory . '/B';
  1291. file_put_contents($filepathA, '');
  1292. file_put_contents($filepathB, '');
  1293. // Delete the directory.
  1294. $this->assertTrue(file_unmanaged_delete_recursive($directory), 'Function reported success.');
  1295. $this->assertFalse(file_exists($filepathA), 'Test file A has been deleted.');
  1296. $this->assertFalse(file_exists($filepathB), 'Test file B has been deleted.');
  1297. $this->assertFalse(file_exists($directory), 'Directory has been deleted.');
  1298. }
  1299. /**
  1300. * Try deleting subdirectories with some files.
  1301. */
  1302. function testSubDirectory() {
  1303. // A directory to operate on.
  1304. $directory = $this->createDirectory();
  1305. $subdirectory = $this->createDirectory($directory . '/sub');
  1306. $filepathA = $directory . '/A';
  1307. $filepathB = $subdirectory . '/B';
  1308. file_put_contents($filepathA, '');
  1309. file_put_contents($filepathB, '');
  1310. // Delete the directory.
  1311. $this->assertTrue(file_unmanaged_delete_recursive($directory), 'Function reported success.');
  1312. $this->assertFalse(file_exists($filepathA), 'Test file A has been deleted.');
  1313. $this->assertFalse(file_exists($filepathB), 'Test file B has been deleted.');
  1314. $this->assertFalse(file_exists($subdirectory), 'Subdirectory has been deleted.');
  1315. $this->assertFalse(file_exists($directory), 'Directory has been deleted.');
  1316. }
  1317. }
  1318. /**
  1319. * Deletion related tests on remote filesystems.
  1320. */
  1321. class RemoteFileUnmanagedDeleteRecursiveTest extends FileUnmanagedDeleteRecursiveTest {
  1322. public static function getInfo() {
  1323. $info = parent::getInfo();
  1324. $info['group'] = 'File API (remote)';
  1325. return $info;
  1326. }
  1327. function setUp() {
  1328. parent::setUp('file_test');
  1329. variable_set('file_default_scheme', 'dummy-remote');
  1330. }
  1331. }
  1332. /**
  1333. * Unmanaged move related tests.
  1334. */
  1335. class FileUnmanagedMoveTest extends FileTestCase {
  1336. public static function getInfo() {
  1337. return array(
  1338. 'name' => 'Unmanaged file moving',
  1339. 'description' => 'Tests the unmanaged file move function.',
  1340. 'group' => 'File API',
  1341. );
  1342. }
  1343. /**
  1344. * Move a normal file.
  1345. */
  1346. function testNormal() {
  1347. // Create a file for testing
  1348. $file = $this->createFile();
  1349. // Moving to a new name.
  1350. $desired_filepath = 'public://' . $this->randomName();
  1351. $new_filepath = file_unmanaged_move($file->uri, $desired_filepath, FILE_EXISTS_ERROR);
  1352. $this->assertTrue($new_filepath, 'Move was successful.');
  1353. $this->assertEqual($new_filepath, $desired_filepath, 'Returned expected filepath.');
  1354. $this->assertTrue(file_exists($new_filepath), 'File exists at the new location.');
  1355. $this->assertFalse(file_exists($file->uri), 'No file remains at the old location.');
  1356. $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
  1357. // Moving with rename.
  1358. $desired_filepath = 'public://' . $this->randomName();
  1359. $this->assertTrue(file_exists($new_filepath), 'File exists before moving.');
  1360. $this->assertTrue(file_put_contents($desired_filepath, ' '), 'Created a file so a rename will have to happen.');
  1361. $newer_filepath = file_unmanaged_move($new_filepath, $desired_filepath, FILE_EXISTS_RENAME);
  1362. $this->assertTrue($newer_filepath, 'Move was successful.');
  1363. $this->assertNotEqual($newer_filepath, $desired_filepath, 'Returned expected filepath.');
  1364. $this->assertTrue(file_exists($newer_filepath), 'File exists at the new location.');
  1365. $this->assertFalse(file_exists($new_filepath), 'No file remains at the old location.');
  1366. $this->assertFilePermissions($newer_filepath, variable_get('file_chmod_file', 0664));
  1367. // TODO: test moving to a directory (rather than full directory/file path)
  1368. // TODO: test creating and moving normal files (rather than streams)
  1369. }
  1370. /**
  1371. * Try to move a missing file.
  1372. */
  1373. function testMissing() {
  1374. // Move non-existent file.
  1375. $new_filepath = file_unmanaged_move($this->randomName(), $this->randomName());
  1376. $this->assertFalse($new_filepath, 'Moving a missing file fails.');
  1377. }
  1378. /**
  1379. * Try to move a file onto itself.
  1380. */
  1381. function testOverwriteSelf() {
  1382. // Create a file for testing.
  1383. $file = $this->createFile();
  1384. // Move the file onto itself without renaming shouldn't make changes.
  1385. $new_filepath = file_unmanaged_move($file->uri, $file->uri, FILE_EXISTS_REPLACE);
  1386. $this->assertFalse($new_filepath, 'Moving onto itself without renaming fails.');
  1387. $this->assertTrue(file_exists($file->uri), 'File exists after moving onto itself.');
  1388. // Move the file onto itself with renaming will result in a new filename.
  1389. $new_filepath = file_unmanaged_move($file->uri, $file->uri, FILE_EXISTS_RENAME);
  1390. $this->assertTrue($new_filepath, 'Moving onto itself with renaming works.');
  1391. $this->assertFalse(file_exists($file->uri), 'Original file has been removed.');
  1392. $this->assertTrue(file_exists($new_filepath), 'File exists after moving onto itself.');
  1393. }
  1394. }
  1395. /**
  1396. * Unmanaged move related tests on remote filesystems.
  1397. */
  1398. class RemoteFileUnmanagedMoveTest extends FileUnmanagedMoveTest {
  1399. public static function getInfo() {
  1400. $info = parent::getInfo();
  1401. $info['group'] = 'File API (remote)';
  1402. return $info;
  1403. }
  1404. function setUp() {
  1405. parent::setUp('file_test');
  1406. variable_set('file_default_scheme', 'dummy-remote');
  1407. }
  1408. }
  1409. /**
  1410. * Unmanaged copy related tests.
  1411. */
  1412. class FileUnmanagedCopyTest extends FileTestCase {
  1413. public static function getInfo() {
  1414. return array(
  1415. 'name' => 'Unmanaged file copying',
  1416. 'description' => 'Tests the unmanaged file copy function.',
  1417. 'group' => 'File API',
  1418. );
  1419. }
  1420. /**
  1421. * Copy a normal file.
  1422. */
  1423. function testNormal() {
  1424. // Create a file for testing
  1425. $file = $this->createFile();
  1426. // Copying to a new name.
  1427. $desired_filepath = 'public://' . $this->randomName();
  1428. $new_filepath = file_unmanaged_copy($file->uri, $desired_filepath, FILE_EXISTS_ERROR);
  1429. $this->assertTrue($new_filepath, 'Copy was successful.');
  1430. $this->assertEqual($new_filepath, $desired_filepath, 'Returned expected filepath.');
  1431. $this->assertTrue(file_exists($file->uri), 'Original file remains.');
  1432. $this->assertTrue(file_exists($new_filepath), 'New file exists.');
  1433. $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
  1434. // Copying with rename.
  1435. $desired_filepath = 'public://' . $this->randomName();
  1436. $this->assertTrue(file_put_contents($desired_filepath, ' '), 'Created a file so a rename will have to happen.');
  1437. $newer_filepath = file_unmanaged_copy($file->uri, $desired_filepath, FILE_EXISTS_RENAME);
  1438. $this->assertTrue($newer_filepath, 'Copy was successful.');
  1439. $this->assertNotEqual($newer_filepath, $desired_filepath, 'Returned expected filepath.');
  1440. $this->assertTrue(file_exists($file->uri), 'Original file remains.');
  1441. $this->assertTrue(file_exists($newer_filepath), 'New file exists.');
  1442. $this->assertFilePermissions($newer_filepath, variable_get('file_chmod_file', 0664));
  1443. // TODO: test copying to a directory (rather than full directory/file path)
  1444. // TODO: test copying normal files using normal paths (rather than only streams)
  1445. }
  1446. /**
  1447. * Copy a non-existent file.
  1448. */
  1449. function testNonExistent() {
  1450. // Copy non-existent file
  1451. $desired_filepath = $this->randomName();
  1452. $this->assertFalse(file_exists($desired_filepath), "Randomly named file doesn't exists.");
  1453. $new_filepath = file_unmanaged_copy($desired_filepath, $this->randomName());
  1454. $this->assertFalse($new_filepath, 'Copying a missing file fails.');
  1455. }
  1456. /**
  1457. * Copy a file onto itself.
  1458. */
  1459. function testOverwriteSelf() {
  1460. // Create a file for testing
  1461. $file = $this->createFile();
  1462. // Copy the file onto itself with renaming works.
  1463. $new_filepath = file_unmanaged_copy($file->uri, $file->uri, FILE_EXISTS_RENAME);
  1464. $this->assertTrue($new_filepath, 'Copying onto itself with renaming works.');
  1465. $this->assertNotEqual($new_filepath, $file->uri, 'Copied file has a new name.');
  1466. $this->assertTrue(file_exists($file->uri), 'Original file exists after copying onto itself.');
  1467. $this->assertTrue(file_exists($new_filepath), 'Copied file exists after copying onto itself.');
  1468. $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
  1469. // Copy the file onto itself without renaming fails.
  1470. $new_filepath = file_unmanaged_copy($file->uri, $file->uri, FILE_EXISTS_ERROR);
  1471. $this->assertFalse($new_filepath, 'Copying onto itself without renaming fails.');
  1472. $this->assertTrue(file_exists($file->uri), 'File exists after copying onto itself.');
  1473. // Copy the file into same directory without renaming fails.
  1474. $new_filepath = file_unmanaged_copy($file->uri, drupal_dirname($file->uri), FILE_EXISTS_ERROR);
  1475. $this->assertFalse($new_filepath, 'Copying onto itself fails.');
  1476. $this->assertTrue(file_exists($file->uri), 'File exists after copying onto itself.');
  1477. // Copy the file into same directory with renaming works.
  1478. $new_filepath = file_unmanaged_copy($file->uri, drupal_dirname($file->uri), FILE_EXISTS_RENAME);
  1479. $this->assertTrue($new_filepath, 'Copying into same directory works.');
  1480. $this->assertNotEqual($new_filepath, $file->uri, 'Copied file has a new name.');
  1481. $this->assertTrue(file_exists($file->uri), 'Original file exists after copying onto itself.');
  1482. $this->assertTrue(file_exists($new_filepath), 'Copied file exists after copying onto itself.');
  1483. $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
  1484. }
  1485. }
  1486. /**
  1487. * Unmanaged copy related tests on remote filesystems.
  1488. */
  1489. class RemoteFileUnmanagedCopyTest extends FileUnmanagedCopyTest {
  1490. public static function getInfo() {
  1491. $info = parent::getInfo();
  1492. $info['group'] = 'File API (remote)';
  1493. return $info;
  1494. }
  1495. function setUp() {
  1496. parent::setUp('file_test');
  1497. variable_set('file_default_scheme', 'dummy-remote');
  1498. }
  1499. }
  1500. /**
  1501. * Deletion related tests.
  1502. */
  1503. class FileDeleteTest extends FileHookTestCase {
  1504. public static function getInfo() {
  1505. return array(
  1506. 'name' => 'File delete',
  1507. 'description' => 'Tests the file delete function.',
  1508. 'group' => 'File API',
  1509. );
  1510. }
  1511. /**
  1512. * Tries deleting a normal file (as opposed to a directory, symlink, etc).
  1513. */
  1514. function testUnused() {
  1515. $file = $this->createFile();
  1516. // Check that deletion removes the file and database record.
  1517. $this->assertTrue(is_file($file->uri), 'File exists.');
  1518. $this->assertIdentical(file_delete($file), TRUE, 'Delete worked.');
  1519. $this->assertFileHooksCalled(array('delete'));
  1520. $this->assertFalse(file_exists($file->uri), 'Test file has actually been deleted.');
  1521. $this->assertFalse(file_load($file->fid), 'File was removed from the database.');
  1522. }
  1523. /**
  1524. * Tries deleting a file that is in use.
  1525. */
  1526. function testInUse() {
  1527. $file = $this->createFile();
  1528. file_usage_add($file, 'testing', 'test', 1);
  1529. file_usage_add($file, 'testing', 'test', 1);
  1530. file_usage_delete($file, 'testing', 'test', 1);
  1531. file_delete($file);
  1532. $usage = file_usage_list($file);
  1533. $this->assertEqual($usage['testing']['test'], array(1 => 1), 'Test file is still in use.');
  1534. $this->assertTrue(file_exists($file->uri), 'File still exists on the disk.');
  1535. $this->assertTrue(file_load($file->fid), 'File still exists in the database.');
  1536. // Clear out the call to hook_file_load().
  1537. file_test_reset();
  1538. file_usage_delete($file, 'testing', 'test', 1);
  1539. file_delete($file);
  1540. $usage = file_usage_list($file);
  1541. $this->assertFileHooksCalled(array('delete'));
  1542. $this->assertTrue(empty($usage), 'File usage data was removed.');
  1543. $this->assertFalse(file_exists($file->uri), 'File has been deleted after its last usage was removed.');
  1544. $this->assertFalse(file_load($file->fid), 'File was removed from the database.');
  1545. }
  1546. }
  1547. /**
  1548. * Move related tests
  1549. */
  1550. class FileMoveTest extends FileHookTestCase {
  1551. public static function getInfo() {
  1552. return array(
  1553. 'name' => 'File moving',
  1554. 'description' => 'Tests the file move function.',
  1555. 'group' => 'File API',
  1556. );
  1557. }
  1558. /**
  1559. * Move a normal file.
  1560. */
  1561. function testNormal() {
  1562. $contents = $this->randomName(10);
  1563. $source = $this->createFile(NULL, $contents);
  1564. $desired_filepath = 'public://' . $this->randomName();
  1565. // Clone the object so we don't have to worry about the function changing
  1566. // our reference copy.
  1567. $result = file_move(clone $source, $desired_filepath, FILE_EXISTS_ERROR);
  1568. // Check the return status and that the contents changed.
  1569. $this->assertTrue($result, 'File moved successfully.');
  1570. $this->assertFalse(file_exists($source->uri));
  1571. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file correctly written.');
  1572. // Check that the correct hooks were called.
  1573. $this->assertFileHooksCalled(array('move', 'load', 'update'));
  1574. // Make sure we got the same file back.
  1575. $this->assertEqual($source->fid, $result->fid, format_string("Source file id's' %fid is unchanged after move.", array('%fid' => $source->fid)));
  1576. // Reload the file from the database and check that the changes were
  1577. // actually saved.
  1578. $loaded_file = file_load($result->fid, TRUE);
  1579. $this->assertTrue($loaded_file, 'File can be loaded from the database.');
  1580. $this->assertFileUnchanged($result, $loaded_file);
  1581. }
  1582. /**
  1583. * Test renaming when moving onto a file that already exists.
  1584. */
  1585. function testExistingRename() {
  1586. // Setup a file to overwrite.
  1587. $contents = $this->randomName(10);
  1588. $source = $this->createFile(NULL, $contents);
  1589. $target = $this->createFile();
  1590. $this->assertDifferentFile($source, $target);
  1591. // Clone the object so we don't have to worry about the function changing
  1592. // our reference copy.
  1593. $result = file_move(clone $source, $target->uri, FILE_EXISTS_RENAME);
  1594. // Check the return status and that the contents changed.
  1595. $this->assertTrue($result, 'File moved successfully.');
  1596. $this->assertFalse(file_exists($source->uri));
  1597. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file correctly written.');
  1598. // Check that the correct hooks were called.
  1599. $this->assertFileHooksCalled(array('move', 'load', 'update'));
  1600. // Compare the returned value to what made it into the database.
  1601. $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
  1602. // The target file should not have been altered.
  1603. $this->assertFileUnchanged($target, file_load($target->fid, TRUE));
  1604. // Make sure we end up with two distinct files afterwards.
  1605. $this->assertDifferentFile($target, $result);
  1606. // Compare the source and results.
  1607. $loaded_source = file_load($source->fid, TRUE);
  1608. $this->assertEqual($loaded_source->fid, $result->fid, "Returned file's id matches the source.");
  1609. $this->assertNotEqual($loaded_source->uri, $source->uri, 'Returned file path has changed from the original.');
  1610. }
  1611. /**
  1612. * Test replacement when moving onto a file that already exists.
  1613. */
  1614. function testExistingReplace() {
  1615. // Setup a file to overwrite.
  1616. $contents = $this->randomName(10);
  1617. $source = $this->createFile(NULL, $contents);
  1618. $target = $this->createFile();
  1619. $this->assertDifferentFile($source, $target);
  1620. // Clone the object so we don't have to worry about the function changing
  1621. // our reference copy.
  1622. $result = file_move(clone $source, $target->uri, FILE_EXISTS_REPLACE);
  1623. // Look at the results.
  1624. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were overwritten.');
  1625. $this->assertFalse(file_exists($source->uri));
  1626. $this->assertTrue($result, 'File moved successfully.');
  1627. // Check that the correct hooks were called.
  1628. $this->assertFileHooksCalled(array('move', 'update', 'delete', 'load'));
  1629. // Reload the file from the database and check that the changes were
  1630. // actually saved.
  1631. $loaded_result = file_load($result->fid, TRUE);
  1632. $this->assertFileUnchanged($result, $loaded_result);
  1633. // Check that target was re-used.
  1634. $this->assertSameFile($target, $loaded_result);
  1635. // Source and result should be totally different.
  1636. $this->assertDifferentFile($source, $loaded_result);
  1637. }
  1638. /**
  1639. * Test replacement when moving onto itself.
  1640. */
  1641. function testExistingReplaceSelf() {
  1642. // Setup a file to overwrite.
  1643. $contents = $this->randomName(10);
  1644. $source = $this->createFile(NULL, $contents);
  1645. // Copy the file over itself. Clone the object so we don't have to worry
  1646. // about the function changing our reference copy.
  1647. $result = file_move(clone $source, $source->uri, FILE_EXISTS_REPLACE);
  1648. $this->assertFalse($result, 'File move failed.');
  1649. $this->assertEqual($contents, file_get_contents($source->uri), 'Contents of file were not altered.');
  1650. // Check that no hooks were called while failing.
  1651. $this->assertFileHooksCalled(array());
  1652. // Load the file from the database and make sure it is identical to what
  1653. // was returned.
  1654. $this->assertFileUnchanged($source, file_load($source->fid, TRUE));
  1655. }
  1656. /**
  1657. * Test that moving onto an existing file fails when FILE_EXISTS_ERROR is
  1658. * specified.
  1659. */
  1660. function testExistingError() {
  1661. $contents = $this->randomName(10);
  1662. $source = $this->createFile();
  1663. $target = $this->createFile(NULL, $contents);
  1664. $this->assertDifferentFile($source, $target);
  1665. // Clone the object so we don't have to worry about the function changing
  1666. // our reference copy.
  1667. $result = file_move(clone $source, $target->uri, FILE_EXISTS_ERROR);
  1668. // Check the return status and that the contents did not change.
  1669. $this->assertFalse($result, 'File move failed.');
  1670. $this->assertTrue(file_exists($source->uri));
  1671. $this->assertEqual($contents, file_get_contents($target->uri), 'Contents of file were not altered.');
  1672. // Check that no hooks were called while failing.
  1673. $this->assertFileHooksCalled(array());
  1674. // Load the file from the database and make sure it is identical to what
  1675. // was returned.
  1676. $this->assertFileUnchanged($source, file_load($source->fid, TRUE));
  1677. $this->assertFileUnchanged($target, file_load($target->fid, TRUE));
  1678. }
  1679. }
  1680. /**
  1681. * Copy related tests.
  1682. */
  1683. class FileCopyTest extends FileHookTestCase {
  1684. public static function getInfo() {
  1685. return array(
  1686. 'name' => 'File copying',
  1687. 'description' => 'Tests the file copy function.',
  1688. 'group' => 'File API',
  1689. );
  1690. }
  1691. /**
  1692. * Test file copying in the normal, base case.
  1693. */
  1694. function testNormal() {
  1695. $contents = $this->randomName(10);
  1696. $source = $this->createFile(NULL, $contents);
  1697. $desired_uri = 'public://' . $this->randomName();
  1698. // Clone the object so we don't have to worry about the function changing
  1699. // our reference copy.
  1700. $result = file_copy(clone $source, $desired_uri, FILE_EXISTS_ERROR);
  1701. // Check the return status and that the contents changed.
  1702. $this->assertTrue($result, 'File copied successfully.');
  1703. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were copied correctly.');
  1704. // Check that the correct hooks were called.
  1705. $this->assertFileHooksCalled(array('copy', 'insert'));
  1706. $this->assertDifferentFile($source, $result);
  1707. $this->assertEqual($result->uri, $desired_uri, 'The copied file object has the desired filepath.');
  1708. $this->assertTrue(file_exists($source->uri), 'The original file still exists.');
  1709. $this->assertTrue(file_exists($result->uri), 'The copied file exists.');
  1710. // Reload the file from the database and check that the changes were
  1711. // actually saved.
  1712. $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
  1713. }
  1714. /**
  1715. * Test renaming when copying over a file that already exists.
  1716. */
  1717. function testExistingRename() {
  1718. // Setup a file to overwrite.
  1719. $contents = $this->randomName(10);
  1720. $source = $this->createFile(NULL, $contents);
  1721. $target = $this->createFile();
  1722. $this->assertDifferentFile($source, $target);
  1723. // Clone the object so we don't have to worry about the function changing
  1724. // our reference copy.
  1725. $result = file_copy(clone $source, $target->uri, FILE_EXISTS_RENAME);
  1726. // Check the return status and that the contents changed.
  1727. $this->assertTrue($result, 'File copied successfully.');
  1728. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were copied correctly.');
  1729. $this->assertNotEqual($result->uri, $source->uri, 'Returned file path has changed from the original.');
  1730. // Check that the correct hooks were called.
  1731. $this->assertFileHooksCalled(array('copy', 'insert'));
  1732. // Load all the affected files to check the changes that actually made it
  1733. // to the database.
  1734. $loaded_source = file_load($source->fid, TRUE);
  1735. $loaded_target = file_load($target->fid, TRUE);
  1736. $loaded_result = file_load($result->fid, TRUE);
  1737. // Verify that the source file wasn't changed.
  1738. $this->assertFileUnchanged($source, $loaded_source);
  1739. // Verify that what was returned is what's in the database.
  1740. $this->assertFileUnchanged($result, $loaded_result);
  1741. // Make sure we end up with three distinct files afterwards.
  1742. $this->assertDifferentFile($loaded_source, $loaded_target);
  1743. $this->assertDifferentFile($loaded_target, $loaded_result);
  1744. $this->assertDifferentFile($loaded_source, $loaded_result);
  1745. }
  1746. /**
  1747. * Test replacement when copying over a file that already exists.
  1748. */
  1749. function testExistingReplace() {
  1750. // Setup a file to overwrite.
  1751. $contents = $this->randomName(10);
  1752. $source = $this->createFile(NULL, $contents);
  1753. $target = $this->createFile();
  1754. $this->assertDifferentFile($source, $target);
  1755. // Clone the object so we don't have to worry about the function changing
  1756. // our reference copy.
  1757. $result = file_copy(clone $source, $target->uri, FILE_EXISTS_REPLACE);
  1758. // Check the return status and that the contents changed.
  1759. $this->assertTrue($result, 'File copied successfully.');
  1760. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were overwritten.');
  1761. $this->assertDifferentFile($source, $result);
  1762. // Check that the correct hooks were called.
  1763. $this->assertFileHooksCalled(array('load', 'copy', 'update'));
  1764. // Load all the affected files to check the changes that actually made it
  1765. // to the database.
  1766. $loaded_source = file_load($source->fid, TRUE);
  1767. $loaded_target = file_load($target->fid, TRUE);
  1768. $loaded_result = file_load($result->fid, TRUE);
  1769. // Verify that the source file wasn't changed.
  1770. $this->assertFileUnchanged($source, $loaded_source);
  1771. // Verify that what was returned is what's in the database.
  1772. $this->assertFileUnchanged($result, $loaded_result);
  1773. // Target file was reused for the result.
  1774. $this->assertFileUnchanged($loaded_target, $loaded_result);
  1775. }
  1776. /**
  1777. * Test that copying over an existing file fails when FILE_EXISTS_ERROR is
  1778. * specified.
  1779. */
  1780. function testExistingError() {
  1781. $contents = $this->randomName(10);
  1782. $source = $this->createFile();
  1783. $target = $this->createFile(NULL, $contents);
  1784. $this->assertDifferentFile($source, $target);
  1785. // Clone the object so we don't have to worry about the function changing
  1786. // our reference copy.
  1787. $result = file_copy(clone $source, $target->uri, FILE_EXISTS_ERROR);
  1788. // Check the return status and that the contents were not changed.
  1789. $this->assertFalse($result, 'File copy failed.');
  1790. $this->assertEqual($contents, file_get_contents($target->uri), 'Contents of file were not altered.');
  1791. // Check that the correct hooks were called.
  1792. $this->assertFileHooksCalled(array());
  1793. $this->assertFileUnchanged($source, file_load($source->fid, TRUE));
  1794. $this->assertFileUnchanged($target, file_load($target->fid, TRUE));
  1795. }
  1796. }
  1797. /**
  1798. * Tests the file_load() function.
  1799. */
  1800. class FileLoadTest extends FileHookTestCase {
  1801. public static function getInfo() {
  1802. return array(
  1803. 'name' => 'File loading',
  1804. 'description' => 'Tests the file_load() function.',
  1805. 'group' => 'File API',
  1806. );
  1807. }
  1808. /**
  1809. * Try to load a non-existent file by fid.
  1810. */
  1811. function testLoadMissingFid() {
  1812. $this->assertFalse(file_load(-1), "Try to load an invalid fid fails.");
  1813. $this->assertFileHooksCalled(array());
  1814. }
  1815. /**
  1816. * Try to load a non-existent file by URI.
  1817. */
  1818. function testLoadMissingFilepath() {
  1819. $files = file_load_multiple(array(), array('uri' => 'foobar://misc/druplicon.png'));
  1820. $this->assertFalse(reset($files), "Try to load a file that doesn't exist in the database fails.");
  1821. $this->assertFileHooksCalled(array());
  1822. }
  1823. /**
  1824. * Try to load a non-existent file by status.
  1825. */
  1826. function testLoadInvalidStatus() {
  1827. $files = file_load_multiple(array(), array('status' => -99));
  1828. $this->assertFalse(reset($files), "Trying to load a file with an invalid status fails.");
  1829. $this->assertFileHooksCalled(array());
  1830. }
  1831. /**
  1832. * Load a single file and ensure that the correct values are returned.
  1833. */
  1834. function testSingleValues() {
  1835. // Create a new file object from scratch so we know the values.
  1836. $file = $this->createFile('druplicon.txt', NULL, 'public');
  1837. $by_fid_file = file_load($file->fid);
  1838. $this->assertFileHookCalled('load');
  1839. $this->assertTrue(is_object($by_fid_file), 'file_load() returned an object.');
  1840. $this->assertEqual($by_fid_file->fid, $file->fid, 'Loading by fid got the same fid.', 'File');
  1841. $this->assertEqual($by_fid_file->uri, $file->uri, 'Loading by fid got the correct filepath.', 'File');
  1842. $this->assertEqual($by_fid_file->filename, $file->filename, 'Loading by fid got the correct filename.', 'File');
  1843. $this->assertEqual($by_fid_file->filemime, $file->filemime, 'Loading by fid got the correct MIME type.', 'File');
  1844. $this->assertEqual($by_fid_file->status, $file->status, 'Loading by fid got the correct status.', 'File');
  1845. $this->assertTrue($by_fid_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
  1846. }
  1847. /**
  1848. * This will test loading file data from the database.
  1849. */
  1850. function testMultiple() {
  1851. // Create a new file object.
  1852. $file = $this->createFile('druplicon.txt', NULL, 'public');
  1853. // Load by path.
  1854. file_test_reset();
  1855. $by_path_files = file_load_multiple(array(), array('uri' => $file->uri));
  1856. $this->assertFileHookCalled('load');
  1857. $this->assertEqual(1, count($by_path_files), 'file_load_multiple() returned an array of the correct size.');
  1858. $by_path_file = reset($by_path_files);
  1859. $this->assertTrue($by_path_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
  1860. $this->assertEqual($by_path_file->fid, $file->fid, 'Loading by filepath got the correct fid.', 'File');
  1861. // Load by fid.
  1862. file_test_reset();
  1863. $by_fid_files = file_load_multiple(array($file->fid), array());
  1864. $this->assertFileHookCalled('load');
  1865. $this->assertEqual(1, count($by_fid_files), 'file_load_multiple() returned an array of the correct size.');
  1866. $by_fid_file = reset($by_fid_files);
  1867. $this->assertTrue($by_fid_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
  1868. $this->assertEqual($by_fid_file->uri, $file->uri, 'Loading by fid got the correct filepath.', 'File');
  1869. }
  1870. }
  1871. /**
  1872. * Tests the file_save() function.
  1873. */
  1874. class FileSaveTest extends FileHookTestCase {
  1875. public static function getInfo() {
  1876. return array(
  1877. 'name' => 'File saving',
  1878. 'description' => 'Tests the file_save() function.',
  1879. 'group' => 'File API',
  1880. );
  1881. }
  1882. function testFileSave() {
  1883. // Create a new file object.
  1884. $file = array(
  1885. 'uid' => 1,
  1886. 'filename' => 'druplicon.txt',
  1887. 'uri' => 'public://druplicon.txt',
  1888. 'filemime' => 'text/plain',
  1889. 'timestamp' => 1,
  1890. 'status' => FILE_STATUS_PERMANENT,
  1891. );
  1892. $file = (object) $file;
  1893. file_put_contents($file->uri, 'hello world');
  1894. // Save it, inserting a new record.
  1895. $saved_file = file_save($file);
  1896. // Check that the correct hooks were called.
  1897. $this->assertFileHooksCalled(array('insert'));
  1898. $this->assertNotNull($saved_file, 'Saving the file should give us back a file object.', 'File');
  1899. $this->assertTrue($saved_file->fid > 0, 'A new file ID is set when saving a new file to the database.', 'File');
  1900. $loaded_file = db_query('SELECT * FROM {file_managed} f WHERE f.fid = :fid', array(':fid' => $saved_file->fid))->fetch(PDO::FETCH_OBJ);
  1901. $this->assertNotNull($loaded_file, 'Record exists in the database.');
  1902. $this->assertEqual($loaded_file->status, $file->status, 'Status was saved correctly.');
  1903. $this->assertEqual($saved_file->filesize, filesize($file->uri), 'File size was set correctly.', 'File');
  1904. $this->assertTrue($saved_file->timestamp > 1, 'File size was set correctly.', 'File');
  1905. // Resave the file, updating the existing record.
  1906. file_test_reset();
  1907. $saved_file->status = 7;
  1908. $resaved_file = file_save($saved_file);
  1909. // Check that the correct hooks were called.
  1910. $this->assertFileHooksCalled(array('load', 'update'));
  1911. $this->assertEqual($resaved_file->fid, $saved_file->fid, 'The file ID of an existing file is not changed when updating the database.', 'File');
  1912. $this->assertTrue($resaved_file->timestamp >= $saved_file->timestamp, "Timestamp didn't go backwards.", 'File');
  1913. $loaded_file = db_query('SELECT * FROM {file_managed} f WHERE f.fid = :fid', array(':fid' => $saved_file->fid))->fetch(PDO::FETCH_OBJ);
  1914. $this->assertNotNull($loaded_file, 'Record still exists in the database.', 'File');
  1915. $this->assertEqual($loaded_file->status, $saved_file->status, 'Status was saved correctly.');
  1916. // Try to insert a second file with the same name apart from case insensitivity
  1917. // to ensure the 'uri' index allows for filenames with different cases.
  1918. $file = (object) array(
  1919. 'uid' => 1,
  1920. 'filename' => 'DRUPLICON.txt',
  1921. 'uri' => 'public://DRUPLICON.txt',
  1922. 'filemime' => 'text/plain',
  1923. 'timestamp' => 1,
  1924. 'status' => FILE_STATUS_PERMANENT,
  1925. );
  1926. file_put_contents($file->uri, 'hello world');
  1927. file_save($file);
  1928. }
  1929. }
  1930. /**
  1931. * Tests file usage functions.
  1932. */
  1933. class FileUsageTest extends FileTestCase {
  1934. public static function getInfo() {
  1935. return array(
  1936. 'name' => 'File usage',
  1937. 'description' => 'Tests the file usage functions.',
  1938. 'group' => 'File',
  1939. );
  1940. }
  1941. /**
  1942. * Tests file_usage_list().
  1943. */
  1944. function testGetUsage() {
  1945. $file = $this->createFile();
  1946. db_insert('file_usage')
  1947. ->fields(array(
  1948. 'fid' => $file->fid,
  1949. 'module' => 'testing',
  1950. 'type' => 'foo',
  1951. 'id' => 1,
  1952. 'count' => 1
  1953. ))
  1954. ->execute();
  1955. db_insert('file_usage')
  1956. ->fields(array(
  1957. 'fid' => $file->fid,
  1958. 'module' => 'testing',
  1959. 'type' => 'bar',
  1960. 'id' => 2,
  1961. 'count' => 2
  1962. ))
  1963. ->execute();
  1964. $usage = file_usage_list($file);
  1965. $this->assertEqual(count($usage['testing']), 2, 'Returned the correct number of items.');
  1966. $this->assertTrue(isset($usage['testing']['foo'][1]), 'Returned the correct id.');
  1967. $this->assertTrue(isset($usage['testing']['bar'][2]), 'Returned the correct id.');
  1968. $this->assertEqual($usage['testing']['foo'][1], 1, 'Returned the correct count.');
  1969. $this->assertEqual($usage['testing']['bar'][2], 2, 'Returned the correct count.');
  1970. }
  1971. /**
  1972. * Tests file_usage_add().
  1973. */
  1974. function testAddUsage() {
  1975. $file = $this->createFile();
  1976. file_usage_add($file, 'testing', 'foo', 1);
  1977. // Add the file twice to ensure that the count is incremented rather than
  1978. // creating additional records.
  1979. file_usage_add($file, 'testing', 'bar', 2);
  1980. file_usage_add($file, 'testing', 'bar', 2);
  1981. $usage = db_select('file_usage', 'f')
  1982. ->fields('f')
  1983. ->condition('f.fid', $file->fid)
  1984. ->execute()
  1985. ->fetchAllAssoc('id');
  1986. $this->assertEqual(count($usage), 2, 'Created two records');
  1987. $this->assertEqual($usage[1]->module, 'testing', 'Correct module');
  1988. $this->assertEqual($usage[2]->module, 'testing', 'Correct module');
  1989. $this->assertEqual($usage[1]->type, 'foo', 'Correct type');
  1990. $this->assertEqual($usage[2]->type, 'bar', 'Correct type');
  1991. $this->assertEqual($usage[1]->count, 1, 'Correct count');
  1992. $this->assertEqual($usage[2]->count, 2, 'Correct count');
  1993. }
  1994. /**
  1995. * Tests file_usage_delete().
  1996. */
  1997. function testRemoveUsage() {
  1998. $file = $this->createFile();
  1999. db_insert('file_usage')
  2000. ->fields(array(
  2001. 'fid' => $file->fid,
  2002. 'module' => 'testing',
  2003. 'type' => 'bar',
  2004. 'id' => 2,
  2005. 'count' => 3,
  2006. ))
  2007. ->execute();
  2008. // Normal decrement.
  2009. file_usage_delete($file, 'testing', 'bar', 2);
  2010. $count = db_select('file_usage', 'f')
  2011. ->fields('f', array('count'))
  2012. ->condition('f.fid', $file->fid)
  2013. ->execute()
  2014. ->fetchField();
  2015. $this->assertEqual(2, $count, 'The count was decremented correctly.');
  2016. // Multiple decrement and removal.
  2017. file_usage_delete($file, 'testing', 'bar', 2, 2);
  2018. $count = db_select('file_usage', 'f')
  2019. ->fields('f', array('count'))
  2020. ->condition('f.fid', $file->fid)
  2021. ->execute()
  2022. ->fetchField();
  2023. $this->assertIdentical(FALSE, $count, 'The count was removed entirely when empty.');
  2024. // Non-existent decrement.
  2025. file_usage_delete($file, 'testing', 'bar', 2);
  2026. $count = db_select('file_usage', 'f')
  2027. ->fields('f', array('count'))
  2028. ->condition('f.fid', $file->fid)
  2029. ->execute()
  2030. ->fetchField();
  2031. $this->assertIdentical(FALSE, $count, 'Decrementing non-exist record complete.');
  2032. }
  2033. }
  2034. /**
  2035. * Tests the file_validate() function..
  2036. */
  2037. class FileValidateTest extends FileHookTestCase {
  2038. public static function getInfo() {
  2039. return array(
  2040. 'name' => 'File validate',
  2041. 'description' => 'Tests the file_validate() function.',
  2042. 'group' => 'File API',
  2043. );
  2044. }
  2045. /**
  2046. * Test that the validators passed into are checked.
  2047. */
  2048. function testCallerValidation() {
  2049. $file = $this->createFile();
  2050. // Empty validators.
  2051. $this->assertEqual(file_validate($file, array()), array(), 'Validating an empty array works successfully.');
  2052. $this->assertFileHooksCalled(array('validate'));
  2053. // Use the file_test.module's test validator to ensure that passing tests
  2054. // return correctly.
  2055. file_test_reset();
  2056. file_test_set_return('validate', array());
  2057. $passing = array('file_test_validator' => array(array()));
  2058. $this->assertEqual(file_validate($file, $passing), array(), 'Validating passes.');
  2059. $this->assertFileHooksCalled(array('validate'));
  2060. // Now test for failures in validators passed in and by hook_validate.
  2061. file_test_reset();
  2062. file_test_set_return('validate', array('Epic fail'));
  2063. $failing = array('file_test_validator' => array(array('Failed', 'Badly')));
  2064. $this->assertEqual(file_validate($file, $failing), array('Failed', 'Badly', 'Epic fail'), 'Validating returns errors.');
  2065. $this->assertFileHooksCalled(array('validate'));
  2066. }
  2067. /**
  2068. * Tests hard-coded security check in file_validate().
  2069. */
  2070. public function testInsecureExtensions() {
  2071. $file = $this->createFile('test.php', 'Invalid PHP');
  2072. // Test that file_validate() will check for insecure extensions by default.
  2073. $errors = file_validate($file, array());
  2074. $this->assertEqual('For security reasons, your upload has been rejected.', $errors[0]);
  2075. $this->assertFileHooksCalled(array('validate'));
  2076. file_test_reset();
  2077. // Test that the 'allow_insecure_uploads' is respected.
  2078. variable_set('allow_insecure_uploads', 1);
  2079. $errors = file_validate($file, array());
  2080. $this->assertEqual(array(), $errors);
  2081. $this->assertFileHooksCalled(array('validate'));
  2082. }
  2083. }
  2084. /**
  2085. * Tests the file_save_data() function.
  2086. */
  2087. class FileSaveDataTest extends FileHookTestCase {
  2088. public static function getInfo() {
  2089. return array(
  2090. 'name' => 'File save data',
  2091. 'description' => 'Tests the file save data function.',
  2092. 'group' => 'File API',
  2093. );
  2094. }
  2095. /**
  2096. * Test the file_save_data() function when no filename is provided.
  2097. */
  2098. function testWithoutFilename() {
  2099. $contents = $this->randomName(8);
  2100. $result = file_save_data($contents);
  2101. $this->assertTrue($result, 'Unnamed file saved correctly.');
  2102. $this->assertEqual(file_default_scheme(), file_uri_scheme($result->uri), "File was placed in Drupal's files directory.");
  2103. $this->assertEqual($result->filename, drupal_basename($result->uri), "Filename was set to the file's basename.");
  2104. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of the file are correct.');
  2105. $this->assertEqual($result->filemime, 'application/octet-stream', 'A MIME type was set.');
  2106. $this->assertEqual($result->status, FILE_STATUS_PERMANENT, "The file's status was set to permanent.");
  2107. // Check that the correct hooks were called.
  2108. $this->assertFileHooksCalled(array('insert'));
  2109. // Verify that what was returned is what's in the database.
  2110. $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
  2111. }
  2112. /**
  2113. * Test the file_save_data() function when a filename is provided.
  2114. */
  2115. function testWithFilename() {
  2116. $contents = $this->randomName(8);
  2117. // Using filename with non-latin characters.
  2118. $filename = 'Текстовый файл.txt';
  2119. $result = file_save_data($contents, 'public://' . $filename);
  2120. $this->assertTrue($result, 'Unnamed file saved correctly.');
  2121. $this->assertEqual('public', file_uri_scheme($result->uri), "File was placed in Drupal's files directory.");
  2122. $this->assertEqual($filename, drupal_basename($result->uri), 'File was named correctly.');
  2123. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of the file are correct.');
  2124. $this->assertEqual($result->filemime, 'text/plain', 'A MIME type was set.');
  2125. $this->assertEqual($result->status, FILE_STATUS_PERMANENT, "The file's status was set to permanent.");
  2126. // Check that the correct hooks were called.
  2127. $this->assertFileHooksCalled(array('insert'));
  2128. // Verify that what was returned is what's in the database.
  2129. $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
  2130. }
  2131. /**
  2132. * Test file_save_data() when renaming around an existing file.
  2133. */
  2134. function testExistingRename() {
  2135. // Setup a file to overwrite.
  2136. $existing = $this->createFile();
  2137. $contents = $this->randomName(8);
  2138. $result = file_save_data($contents, $existing->uri, FILE_EXISTS_RENAME);
  2139. $this->assertTrue($result, 'File saved successfully.');
  2140. $this->assertEqual('public', file_uri_scheme($result->uri), "File was placed in Drupal's files directory.");
  2141. $this->assertEqual($result->filename, $existing->filename, 'Filename was set to the basename of the source, rather than that of the renamed file.');
  2142. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of the file are correct.');
  2143. $this->assertEqual($result->filemime, 'application/octet-stream', 'A MIME type was set.');
  2144. $this->assertEqual($result->status, FILE_STATUS_PERMANENT, "The file's status was set to permanent.");
  2145. // Check that the correct hooks were called.
  2146. $this->assertFileHooksCalled(array('insert'));
  2147. // Ensure that the existing file wasn't overwritten.
  2148. $this->assertDifferentFile($existing, $result);
  2149. $this->assertFileUnchanged($existing, file_load($existing->fid, TRUE));
  2150. // Verify that was returned is what's in the database.
  2151. $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
  2152. }
  2153. /**
  2154. * Test file_save_data() when replacing an existing file.
  2155. */
  2156. function testExistingReplace() {
  2157. // Setup a file to overwrite.
  2158. $existing = $this->createFile();
  2159. $contents = $this->randomName(8);
  2160. $result = file_save_data($contents, $existing->uri, FILE_EXISTS_REPLACE);
  2161. $this->assertTrue($result, 'File saved successfully.');
  2162. $this->assertEqual('public', file_uri_scheme($result->uri), "File was placed in Drupal's files directory.");
  2163. $this->assertEqual($result->filename, $existing->filename, 'Filename was set to the basename of the existing file, rather than preserving the original name.');
  2164. $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of the file are correct.');
  2165. $this->assertEqual($result->filemime, 'application/octet-stream', 'A MIME type was set.');
  2166. $this->assertEqual($result->status, FILE_STATUS_PERMANENT, "The file's status was set to permanent.");
  2167. // Check that the correct hooks were called.
  2168. $this->assertFileHooksCalled(array('load', 'update'));
  2169. // Verify that the existing file was re-used.
  2170. $this->assertSameFile($existing, $result);
  2171. // Verify that what was returned is what's in the database.
  2172. $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
  2173. }
  2174. /**
  2175. * Test that file_save_data() fails overwriting an existing file.
  2176. */
  2177. function testExistingError() {
  2178. $contents = $this->randomName(8);
  2179. $existing = $this->createFile(NULL, $contents);
  2180. // Check the overwrite error.
  2181. $result = file_save_data('asdf', $existing->uri, FILE_EXISTS_ERROR);
  2182. $this->assertFalse($result, 'Overwriting a file fails when FILE_EXISTS_ERROR is specified.');
  2183. $this->assertEqual($contents, file_get_contents($existing->uri), 'Contents of existing file were unchanged.');
  2184. // Check that no hooks were called while failing.
  2185. $this->assertFileHooksCalled(array());
  2186. // Ensure that the existing file wasn't overwritten.
  2187. $this->assertFileUnchanged($existing, file_load($existing->fid, TRUE));
  2188. }
  2189. }
  2190. /**
  2191. * Tests for download/file transfer functions.
  2192. */
  2193. class FileDownloadTest extends FileTestCase {
  2194. public static function getInfo() {
  2195. return array(
  2196. 'name' => 'File download',
  2197. 'description' => 'Tests for file download/transfer functions.',
  2198. 'group' => 'File API',
  2199. );
  2200. }
  2201. function setUp() {
  2202. parent::setUp('file_test');
  2203. // Clear out any hook calls.
  2204. file_test_reset();
  2205. }
  2206. /**
  2207. * Test the public file transfer system.
  2208. */
  2209. function testPublicFileTransfer() {
  2210. // Test generating an URL to a created file.
  2211. $file = $this->createFile();
  2212. $url = file_create_url($file->uri);
  2213. // URLs can't contain characters outside the ASCII set so $filename has to be
  2214. // encoded.
  2215. $filename = $GLOBALS['base_url'] . '/' . file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath() . '/' . rawurlencode($file->filename);
  2216. $this->assertEqual($filename, $url, 'Correctly generated a URL for a created file.');
  2217. $this->drupalHead($url);
  2218. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the created file.');
  2219. // Test generating an URL to a shipped file (i.e. a file that is part of
  2220. // Drupal core, a module or a theme, for example a JavaScript file).
  2221. $filepath = 'misc/jquery.js';
  2222. $url = file_create_url($filepath);
  2223. $this->assertEqual($GLOBALS['base_url'] . '/' . $filepath, $url, 'Correctly generated a URL for a shipped file.');
  2224. $this->drupalHead($url);
  2225. $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
  2226. }
  2227. /**
  2228. * Test the private file transfer system.
  2229. */
  2230. function testPrivateFileTransfer() {
  2231. // Set file downloads to private so handler functions get called.
  2232. // Create a file.
  2233. $contents = $this->randomName(8);
  2234. $file = $this->createFile(NULL, $contents, 'private');
  2235. $url = file_create_url($file->uri);
  2236. // Set file_test access header to allow the download.
  2237. file_test_reset();
  2238. file_test_set_return('download', array('x-foo' => 'Bar'));
  2239. $this->drupalGet($url);
  2240. $headers = $this->drupalGetHeaders();
  2241. $this->assertEqual($headers['x-foo'], 'Bar', 'Found header set by file_test module on private download.');
  2242. $this->assertResponse(200, 'Correctly allowed access to a file when file_test provides headers.');
  2243. // Ensure hook_file_download is fired correctly.
  2244. $hooks_results = file_test_get_all_calls();
  2245. $file_uri = !empty($hooks_results['download']) ? reset($hooks_results['download'][0]) : '';
  2246. $this->assertEqual($file->uri, $file_uri);
  2247. // Test that the file transferred correctly.
  2248. $this->assertEqual($contents, $this->content, 'Contents of the file are correct.');
  2249. // Deny access to all downloads via a -1 header.
  2250. file_test_set_return('download', -1);
  2251. $this->drupalHead($url);
  2252. $this->assertResponse(403, 'Correctly denied access to a file when file_test sets the header to -1.');
  2253. // Try non-existent file.
  2254. file_test_reset();
  2255. $url = file_create_url('private://' . $this->randomName());
  2256. $this->drupalHead($url);
  2257. $this->assertResponse(404, 'Correctly returned 404 response for a non-existent file.');
  2258. // Assert that hook_file_download is not called.
  2259. $hooks_results = file_test_get_all_calls();
  2260. $hook_download_results = isset($hooks_results['download']) ? $hooks_results['download'] : NULL;
  2261. $this->assertEqual(array(), $hook_download_results);
  2262. // Try requesting the private file url without a file specified.
  2263. file_test_reset();
  2264. $this->drupalGet('system/files');
  2265. $this->assertResponse(404, 'Correctly returned 404 response for a private file url without a file specified.');
  2266. // Assert that hook_file_download is not called.
  2267. $hooks_results = file_test_get_all_calls();
  2268. $hook_download_results = isset($hooks_results['download']) ? $hooks_results['download'] : NULL;
  2269. $this->assertEqual(array(), $hook_download_results);
  2270. }
  2271. /**
  2272. * Test file_create_url().
  2273. */
  2274. function testFileCreateUrl() {
  2275. global $base_url;
  2276. // Tilde (~) is excluded from this test because it is encoded by
  2277. // rawurlencode() in PHP 5.2 but not in PHP 5.3, as per RFC 3986.
  2278. // @see http://www.php.net/manual/en/function.rawurlencode.php#86506
  2279. $basename = " -._!$'\"()*@[]?&+%#,;=:\n\x00" . // "Special" ASCII characters.
  2280. "%23%25%26%2B%2F%3F" . // Characters that look like a percent-escaped string.
  2281. "éøïвβ中國書۞"; // Characters from various non-ASCII alphabets.
  2282. $basename_encoded = '%20-._%21%24%27%22%28%29%2A%40%5B%5D%3F%26%2B%25%23%2C%3B%3D%3A__' .
  2283. '%2523%2525%2526%252B%252F%253F' .
  2284. '%C3%A9%C3%B8%C3%AF%D0%B2%CE%B2%E4%B8%AD%E5%9C%8B%E6%9B%B8%DB%9E';
  2285. $this->checkUrl('public', '', $basename, $base_url . '/' . file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath() . '/' . $basename_encoded);
  2286. $this->checkUrl('private', '', $basename, $base_url . '/system/files/' . $basename_encoded);
  2287. $this->checkUrl('private', '', $basename, $base_url . '/?q=system/files/' . $basename_encoded, '0');
  2288. }
  2289. /**
  2290. * Download a file from the URL generated by file_create_url().
  2291. *
  2292. * Create a file with the specified scheme, directory and filename; check that
  2293. * the URL generated by file_create_url() for the specified file equals the
  2294. * specified URL; fetch the URL and then compare the contents to the file.
  2295. *
  2296. * @param $scheme
  2297. * A scheme, e.g. "public"
  2298. * @param $directory
  2299. * A directory, possibly ""
  2300. * @param $filename
  2301. * A filename
  2302. * @param $expected_url
  2303. * The expected URL
  2304. * @param $clean_url
  2305. * The value of the clean_url setting
  2306. */
  2307. private function checkUrl($scheme, $directory, $filename, $expected_url, $clean_url = '1') {
  2308. variable_set('clean_url', $clean_url);
  2309. // Convert $filename to a valid filename, i.e. strip characters not
  2310. // supported by the filesystem, and create the file in the specified
  2311. // directory.
  2312. $filepath = file_create_filename($filename, $directory);
  2313. $directory_uri = $scheme . '://' . dirname($filepath);
  2314. file_prepare_directory($directory_uri, FILE_CREATE_DIRECTORY);
  2315. $file = $this->createFile($filepath, NULL, $scheme);
  2316. $url = file_create_url($file->uri);
  2317. $this->assertEqual($url, $expected_url, 'Generated URL matches expected URL.');
  2318. if ($scheme == 'private') {
  2319. // Tell the implementation of hook_file_download() in file_test.module
  2320. // that this file may be downloaded.
  2321. file_test_set_return('download', array('x-foo' => 'Bar'));
  2322. }
  2323. $this->drupalGet($url);
  2324. if ($this->assertResponse(200) == 'pass') {
  2325. $this->assertRaw(file_get_contents($file->uri), 'Contents of the file are correct.');
  2326. }
  2327. file_delete($file);
  2328. }
  2329. }
  2330. /**
  2331. * Tests for file URL rewriting.
  2332. */
  2333. class FileURLRewritingTest extends FileTestCase {
  2334. public static function getInfo() {
  2335. return array(
  2336. 'name' => 'File URL rewriting',
  2337. 'description' => 'Tests for file URL rewriting.',
  2338. 'group' => 'File',
  2339. );
  2340. }
  2341. function setUp() {
  2342. parent::setUp('file_test');
  2343. }
  2344. /**
  2345. * Test the generating of rewritten shipped file URLs.
  2346. */
  2347. function testShippedFileURL() {
  2348. // Test generating an URL to a shipped file (i.e. a file that is part of
  2349. // Drupal core, a module or a theme, for example a JavaScript file).
  2350. // Test alteration of file URLs to use a CDN.
  2351. variable_set('file_test_hook_file_url_alter', 'cdn');
  2352. $filepath = 'misc/jquery.js';
  2353. $url = file_create_url($filepath);
  2354. $this->assertEqual(FILE_URL_TEST_CDN_1 . '/' . $filepath, $url, 'Correctly generated a CDN URL for a shipped file.');
  2355. $filepath = 'misc/favicon.ico';
  2356. $url = file_create_url($filepath);
  2357. $this->assertEqual(FILE_URL_TEST_CDN_2 . '/' . $filepath, $url, 'Correctly generated a CDN URL for a shipped file.');
  2358. // Test alteration of file URLs to use root-relative URLs.
  2359. variable_set('file_test_hook_file_url_alter', 'root-relative');
  2360. $filepath = 'misc/jquery.js';
  2361. $url = file_create_url($filepath);
  2362. $this->assertEqual(base_path() . '/' . $filepath, $url, 'Correctly generated a root-relative URL for a shipped file.');
  2363. $filepath = 'misc/favicon.ico';
  2364. $url = file_create_url($filepath);
  2365. $this->assertEqual(base_path() . '/' . $filepath, $url, 'Correctly generated a root-relative URL for a shipped file.');
  2366. // Test alteration of file URLs to use protocol-relative URLs.
  2367. variable_set('file_test_hook_file_url_alter', 'protocol-relative');
  2368. $filepath = 'misc/jquery.js';
  2369. $url = file_create_url($filepath);
  2370. $this->assertEqual('/' . base_path() . '/' . $filepath, $url, 'Correctly generated a protocol-relative URL for a shipped file.');
  2371. $filepath = 'misc/favicon.ico';
  2372. $url = file_create_url($filepath);
  2373. $this->assertEqual('/' . base_path() . '/' . $filepath, $url, 'Correctly generated a protocol-relative URL for a shipped file.');
  2374. }
  2375. /**
  2376. * Test the generating of rewritten public created file URLs.
  2377. */
  2378. function testPublicCreatedFileURL() {
  2379. // Test generating an URL to a created file.
  2380. // Test alteration of file URLs to use a CDN.
  2381. variable_set('file_test_hook_file_url_alter', 'cdn');
  2382. $file = $this->createFile();
  2383. $url = file_create_url($file->uri);
  2384. $public_directory_path = file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath();
  2385. $this->assertEqual(FILE_URL_TEST_CDN_2 . '/' . $public_directory_path . '/' . $file->filename, $url, 'Correctly generated a CDN URL for a created file.');
  2386. // Test alteration of file URLs to use root-relative URLs.
  2387. variable_set('file_test_hook_file_url_alter', 'root-relative');
  2388. $file = $this->createFile();
  2389. $url = file_create_url($file->uri);
  2390. $this->assertEqual(base_path() . '/' . $public_directory_path . '/' . $file->filename, $url, 'Correctly generated a root-relative URL for a created file.');
  2391. // Test alteration of file URLs to use a protocol-relative URLs.
  2392. variable_set('file_test_hook_file_url_alter', 'protocol-relative');
  2393. $file = $this->createFile();
  2394. $url = file_create_url($file->uri);
  2395. $this->assertEqual('/' . base_path() . '/' . $public_directory_path . '/' . $file->filename, $url, 'Correctly generated a protocol-relative URL for a created file.');
  2396. }
  2397. }
  2398. /**
  2399. * Tests for file_munge_filename() and file_unmunge_filename().
  2400. */
  2401. class FileNameMungingTest extends FileTestCase {
  2402. protected $bad_extension;
  2403. protected $name;
  2404. protected $name_with_uc_ext;
  2405. public static function getInfo() {
  2406. return array(
  2407. 'name' => 'File naming',
  2408. 'description' => 'Test filename munging and unmunging.',
  2409. 'group' => 'File API',
  2410. );
  2411. }
  2412. function setUp() {
  2413. parent::setUp();
  2414. $this->bad_extension = 'foo';
  2415. $this->name = $this->randomName() . '.' . $this->bad_extension . '.txt';
  2416. $this->name_with_uc_ext = $this->randomName() . '.' . strtoupper($this->bad_extension) . '.txt';
  2417. }
  2418. /**
  2419. * Create a file and munge/unmunge the name.
  2420. */
  2421. function testMunging() {
  2422. // Disable insecure uploads.
  2423. variable_set('allow_insecure_uploads', 0);
  2424. $munged_name = file_munge_filename($this->name, '', TRUE);
  2425. $messages = drupal_get_messages();
  2426. $this->assertTrue(in_array(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $munged_name)), $messages['status']), 'Alert properly set when a file is renamed.');
  2427. $this->assertNotEqual($munged_name, $this->name, format_string('The new filename (%munged) has been modified from the original (%original)', array('%munged' => $munged_name, '%original' => $this->name)));
  2428. }
  2429. /**
  2430. * Tests munging with a null byte in the filename.
  2431. */
  2432. function testMungeNullByte() {
  2433. $prefix = $this->randomName();
  2434. $filename = $prefix . '.' . $this->bad_extension . "\0.txt";
  2435. $this->assertEqual(file_munge_filename($filename, ''), $prefix . '.' . $this->bad_extension . '_.txt', 'A filename with a null byte is correctly munged to remove the null byte.');
  2436. }
  2437. /**
  2438. * If the allow_insecure_uploads variable evaluates to true, the file should
  2439. * come out untouched, no matter how evil the filename.
  2440. */
  2441. function testMungeIgnoreInsecure() {
  2442. variable_set('allow_insecure_uploads', 1);
  2443. $munged_name = file_munge_filename($this->name, '');
  2444. $this->assertIdentical($munged_name, $this->name, format_string('The original filename (%original) matches the munged filename (%munged) when insecure uploads are enabled.', array('%munged' => $munged_name, '%original' => $this->name)));
  2445. }
  2446. /**
  2447. * White listed extensions are ignored by file_munge_filename().
  2448. */
  2449. function testMungeIgnoreWhitelisted() {
  2450. // Declare our extension as whitelisted. The declared extensions should
  2451. // be case insensitive so test using one with a different case.
  2452. $munged_name = file_munge_filename($this->name_with_uc_ext, $this->bad_extension);
  2453. $this->assertIdentical($munged_name, $this->name_with_uc_ext, format_string('The new filename (%munged) matches the original (%original) once the extension has been whitelisted.', array('%munged' => $munged_name, '%original' => $this->name_with_uc_ext)));
  2454. // The allowed extensions should also be normalized.
  2455. $munged_name = file_munge_filename($this->name, strtoupper($this->bad_extension));
  2456. $this->assertIdentical($munged_name, $this->name, format_string('The new filename (%munged) matches the original (%original) also when the whitelisted extension is in uppercase.', array('%munged' => $munged_name, '%original' => $this->name)));
  2457. }
  2458. /**
  2459. * Tests unsafe extensions are munged by file_munge_filename().
  2460. */
  2461. public function testMungeUnsafe() {
  2462. $prefix = $this->randomName();
  2463. $name = "$prefix.php.txt";
  2464. // Put the php extension in the allowed list, but since it is in the unsafe
  2465. // extension list, it should still be munged.
  2466. $munged_name = file_munge_filename($name, 'php txt');
  2467. $this->assertIdentical($munged_name, "$prefix.php_.txt", format_string('The filename (%munged) has been modified from the original (%original) if the allowed extension is also on the unsafe list.', array('%munged' => $munged_name, '%original' => $name)));
  2468. }
  2469. /**
  2470. * Ensure that unmunge gets your name back.
  2471. */
  2472. function testUnMunge() {
  2473. $munged_name = file_munge_filename($this->name, '', FALSE);
  2474. $unmunged_name = file_unmunge_filename($munged_name);
  2475. $this->assertIdentical($unmunged_name, $this->name, format_string('The unmunged (%unmunged) filename matches the original (%original)', array('%unmunged' => $unmunged_name, '%original' => $this->name)));
  2476. }
  2477. }
  2478. /**
  2479. * Tests for file_get_mimetype().
  2480. */
  2481. class FileMimeTypeTest extends DrupalWebTestCase {
  2482. function setUp() {
  2483. parent::setUp('file_test');
  2484. }
  2485. public static function getInfo() {
  2486. return array(
  2487. 'name' => 'File mimetypes',
  2488. 'description' => 'Test filename mimetype detection.',
  2489. 'group' => 'File API',
  2490. );
  2491. }
  2492. /**
  2493. * Test mapping of mimetypes from filenames.
  2494. */
  2495. public function testFileMimeTypeDetection() {
  2496. $prefix = 'public://';
  2497. $test_case = array(
  2498. 'test.jar' => 'application/java-archive',
  2499. 'test.jpeg' => 'image/jpeg',
  2500. 'test.JPEG' => 'image/jpeg',
  2501. 'test.jpg' => 'image/jpeg',
  2502. 'test.jar.jpg' => 'image/jpeg',
  2503. 'test.jpg.jar' => 'application/java-archive',
  2504. 'test.pcf.Z' => 'application/x-font',
  2505. 'pcf.z' => 'application/octet-stream',
  2506. 'jar' => 'application/octet-stream',
  2507. 'some.junk' => 'application/octet-stream',
  2508. 'foo.file_test_1' => 'madeup/file_test_1',
  2509. 'foo.file_test_2' => 'madeup/file_test_2',
  2510. 'foo.doc' => 'madeup/doc',
  2511. 'test.ogg' => 'audio/ogg',
  2512. );
  2513. // Test using default mappings.
  2514. foreach ($test_case as $input => $expected) {
  2515. // Test stream [URI].
  2516. $output = file_get_mimetype($prefix . $input);
  2517. $this->assertIdentical($output, $expected, format_string('Mimetype for %input is %output (expected: %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
  2518. // Test normal path equivalent
  2519. $output = file_get_mimetype($input);
  2520. $this->assertIdentical($output, $expected, format_string('Mimetype (using default mappings) for %input is %output (expected: %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
  2521. }
  2522. // Now test passing in the map.
  2523. $mapping = array(
  2524. 'mimetypes' => array(
  2525. 0 => 'application/java-archive',
  2526. 1 => 'image/jpeg',
  2527. ),
  2528. 'extensions' => array(
  2529. 'jar' => 0,
  2530. 'jpg' => 1,
  2531. )
  2532. );
  2533. $test_case = array(
  2534. 'test.jar' => 'application/java-archive',
  2535. 'test.jpeg' => 'application/octet-stream',
  2536. 'test.jpg' => 'image/jpeg',
  2537. 'test.jar.jpg' => 'image/jpeg',
  2538. 'test.jpg.jar' => 'application/java-archive',
  2539. 'test.pcf.z' => 'application/octet-stream',
  2540. 'pcf.z' => 'application/octet-stream',
  2541. 'jar' => 'application/octet-stream',
  2542. 'some.junk' => 'application/octet-stream',
  2543. 'foo.file_test_1' => 'application/octet-stream',
  2544. 'foo.file_test_2' => 'application/octet-stream',
  2545. 'foo.doc' => 'application/octet-stream',
  2546. 'test.ogg' => 'application/octet-stream',
  2547. );
  2548. foreach ($test_case as $input => $expected) {
  2549. $output = file_get_mimetype($input, $mapping);
  2550. $this->assertIdentical($output, $expected, format_string('Mimetype (using passed-in mappings) for %input is %output (expected: %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
  2551. }
  2552. }
  2553. }
  2554. /**
  2555. * Tests stream wrapper functions.
  2556. */
  2557. class StreamWrapperTest extends DrupalWebTestCase {
  2558. protected $scheme = 'dummy';
  2559. protected $classname = 'DrupalDummyStreamWrapper';
  2560. public static function getInfo() {
  2561. return array(
  2562. 'name' => 'Stream wrappers',
  2563. 'description' => 'Tests stream wrapper functions.',
  2564. 'group' => 'File API',
  2565. );
  2566. }
  2567. function setUp() {
  2568. parent::setUp('file_test');
  2569. drupal_static_reset('file_get_stream_wrappers');
  2570. }
  2571. function tearDown() {
  2572. parent::tearDown();
  2573. stream_wrapper_unregister($this->scheme);
  2574. }
  2575. /**
  2576. * Test the getClassName() function.
  2577. */
  2578. function testGetClassName() {
  2579. // Check the dummy scheme.
  2580. $this->assertEqual($this->classname, file_stream_wrapper_get_class($this->scheme), 'Got correct class name for dummy scheme.');
  2581. // Check core's scheme.
  2582. $this->assertEqual('DrupalPublicStreamWrapper', file_stream_wrapper_get_class('public'), 'Got correct class name for public scheme.');
  2583. }
  2584. /**
  2585. * Test the file_stream_wrapper_get_instance_by_scheme() function.
  2586. */
  2587. function testGetInstanceByScheme() {
  2588. $instance = file_stream_wrapper_get_instance_by_scheme($this->scheme);
  2589. $this->assertEqual($this->classname, get_class($instance), 'Got correct class type for dummy scheme.');
  2590. $instance = file_stream_wrapper_get_instance_by_scheme('public');
  2591. $this->assertEqual('DrupalPublicStreamWrapper', get_class($instance), 'Got correct class type for public scheme.');
  2592. }
  2593. /**
  2594. * Test the URI and target functions.
  2595. */
  2596. function testUriFunctions() {
  2597. $instance = file_stream_wrapper_get_instance_by_uri($this->scheme . '://foo');
  2598. $this->assertEqual($this->classname, get_class($instance), 'Got correct class type for dummy URI.');
  2599. $instance = file_stream_wrapper_get_instance_by_uri('public://foo');
  2600. $this->assertEqual('DrupalPublicStreamWrapper', get_class($instance), 'Got correct class type for public URI.');
  2601. // Test file_uri_target().
  2602. $this->assertEqual(file_uri_target('public://foo/bar.txt'), 'foo/bar.txt', 'Got a valid stream target from public://foo/bar.txt.');
  2603. $this->assertFalse(file_uri_target('foo/bar.txt'), 'foo/bar.txt is not a valid stream.');
  2604. // Test file_build_uri() and DrupalLocalStreamWrapper::getDirectoryPath().
  2605. $this->assertEqual(file_build_uri('foo/bar.txt'), 'public://foo/bar.txt', 'Expected scheme was added.');
  2606. $this->assertEqual(file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath(), variable_get('file_public_path'), 'Expected default directory path was returned.');
  2607. $this->assertEqual(file_stream_wrapper_get_instance_by_scheme('temporary')->getDirectoryPath(), variable_get('file_temporary_path'), 'Expected temporary directory path was returned.');
  2608. variable_set('file_default_scheme', 'private');
  2609. $this->assertEqual(file_build_uri('foo/bar.txt'), 'private://foo/bar.txt', 'Got a valid URI from foo/bar.txt.');
  2610. }
  2611. /**
  2612. * Test the scheme functions.
  2613. */
  2614. function testGetValidStreamScheme() {
  2615. $this->assertEqual('foo', file_uri_scheme('foo://pork//chops'), 'Got the correct scheme from foo://asdf');
  2616. $this->assertTrue(file_stream_wrapper_valid_scheme(file_uri_scheme('public://asdf')), 'Got a valid stream scheme from public://asdf');
  2617. $this->assertFalse(file_stream_wrapper_valid_scheme(file_uri_scheme('foo://asdf')), 'Did not get a valid stream scheme from foo://asdf');
  2618. }
  2619. /**
  2620. * Tests that phar stream wrapper is registered as expected.
  2621. *
  2622. * @see file_get_stream_wrappers()
  2623. */
  2624. public function testPharStreamWrapperRegistration() {
  2625. if (!class_exists('Phar', FALSE)) {
  2626. $this->assertFalse(in_array('phar', stream_get_wrappers(), TRUE), 'PHP is compiled without phar support. Therefore, no phar stream wrapper is registered.');
  2627. }
  2628. elseif (version_compare(PHP_VERSION, '5.3.3', '<')) {
  2629. $this->assertFalse(in_array('phar', stream_get_wrappers(), TRUE), 'The PHP version is <5.3.3. The built-in phar stream wrapper has been unregistered and not replaced.');
  2630. }
  2631. else {
  2632. $this->assertTrue(in_array('phar', stream_get_wrappers(), TRUE), 'A phar stream wrapper is registered.');
  2633. $this->assertFalse(file_stream_wrapper_valid_scheme('phar'), 'The phar scheme is not a valid scheme for Drupal File API usage.');
  2634. }
  2635. // Ensure that calling file_get_stream_wrappers() multiple times, both
  2636. // without and with a drupal_static_reset() in between, does not create
  2637. // errors due to the PharStreamWrapperManager singleton.
  2638. file_get_stream_wrappers();
  2639. file_get_stream_wrappers();
  2640. drupal_static_reset('file_get_stream_wrappers');
  2641. file_get_stream_wrappers();
  2642. }
  2643. /**
  2644. * Tests that only valid phar files can be used.
  2645. */
  2646. public function testPharFile() {
  2647. if (!in_array('phar', stream_get_wrappers(), TRUE)) {
  2648. $this->pass('There is no phar stream wrapper registered.');
  2649. // Nothing else in this test is relevant when there's no phar stream
  2650. // wrapper. testPharStreamWrapperRegistration() is sufficient for testing
  2651. // the conditions of when the stream wrapper should or should not be
  2652. // registered.
  2653. return;
  2654. }
  2655. $base = dirname(dirname(__FILE__)) . '/files';
  2656. // Ensure that file operations via the phar:// stream wrapper work for phar
  2657. // files with the .phar extension.
  2658. $this->assertFalse(file_exists("phar://$base/phar-1.phar/no-such-file.php"));
  2659. $this->assertTrue(file_exists("phar://$base/phar-1.phar/index.php"));
  2660. $file_contents = file_get_contents("phar://$base/phar-1.phar/index.php");
  2661. $expected_hash = 'c7e7904ea573c5ebea3ef00bb08c1f86af1a45961fbfbeb1892ff4a98fd73ad5';
  2662. $this->assertIdentical($expected_hash, hash('sha256', $file_contents));
  2663. // Ensure that file operations via the phar:// stream wrapper throw an
  2664. // exception for files without the .phar extension.
  2665. try {
  2666. file_exists("phar://$base/image-2.jpg/index.php");
  2667. $this->fail('Expected exception failed to be thrown when accessing an invalid phar file.');
  2668. }
  2669. catch (Exception $e) {
  2670. $this->assertEqual(get_class($e), 'TYPO3\PharStreamWrapper\Exception', 'Expected exception thrown when accessing an invalid phar file.');
  2671. }
  2672. }
  2673. }