file.test 122 KB

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