file.inc 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796
  1. <?php
  2. /**
  3. * @file
  4. * API for handling file uploads and server file management.
  5. */
  6. /**
  7. * Manually include stream wrapper code.
  8. *
  9. * Stream wrapper code is included here because there are cases where
  10. * File API is needed before a bootstrap, or in an alternate order (e.g.
  11. * maintenance theme).
  12. */
  13. require_once DRUPAL_ROOT . '/includes/stream_wrappers.inc';
  14. /**
  15. * @defgroup file File interface
  16. * @{
  17. * Common file handling functions.
  18. *
  19. * Fields on the file object:
  20. * - fid: File ID
  21. * - uid: The {users}.uid of the user who is associated with the file.
  22. * - filename: Name of the file with no path components. This may differ from
  23. * the basename of the filepath if the file is renamed to avoid overwriting
  24. * an existing file.
  25. * - uri: URI of the file.
  26. * - filemime: The file's MIME type.
  27. * - filesize: The size of the file in bytes.
  28. * - status: A bitmapped field indicating the status of the file. The first 8
  29. * bits are reserved for Drupal core. The least significant bit indicates
  30. * temporary (0) or permanent (1). Temporary files older than
  31. * DRUPAL_MAXIMUM_TEMP_FILE_AGE will be removed during cron runs.
  32. * - timestamp: UNIX timestamp for the date the file was added to the database.
  33. */
  34. /**
  35. * Flag used by file_prepare_directory() -- create directory if not present.
  36. */
  37. define('FILE_CREATE_DIRECTORY', 1);
  38. /**
  39. * Flag used by file_prepare_directory() -- file permissions may be changed.
  40. */
  41. define('FILE_MODIFY_PERMISSIONS', 2);
  42. /**
  43. * Flag for dealing with existing files: Appends number until name is unique.
  44. */
  45. define('FILE_EXISTS_RENAME', 0);
  46. /**
  47. * Flag for dealing with existing files: Replace the existing file.
  48. */
  49. define('FILE_EXISTS_REPLACE', 1);
  50. /**
  51. * Flag for dealing with existing files: Do nothing and return FALSE.
  52. */
  53. define('FILE_EXISTS_ERROR', 2);
  54. /**
  55. * Indicates that the file is permanent and should not be deleted.
  56. *
  57. * Temporary files older than DRUPAL_MAXIMUM_TEMP_FILE_AGE will be removed
  58. * during cron runs, but permanent files will not be removed during the file
  59. * garbage collection process.
  60. */
  61. define('FILE_STATUS_PERMANENT', 1);
  62. /**
  63. * A pipe-separated list of insecure extensions.
  64. *
  65. * @see file_munge_filename(), file_save_upload()
  66. */
  67. define('FILE_INSECURE_EXTENSIONS', 'php|phar|pl|py|cgi|asp|js|phtml');
  68. /**
  69. * Provides Drupal stream wrapper registry.
  70. *
  71. * A stream wrapper is an abstraction of a file system that allows Drupal to
  72. * use the same set of methods to access both local files and remote resources.
  73. *
  74. * Provide a facility for managing and querying user-defined stream wrappers
  75. * in PHP. PHP's internal stream_get_wrappers() doesn't return the class
  76. * registered to handle a stream, which we need to be able to find the handler
  77. * for class instantiation.
  78. *
  79. * If a module registers a scheme that is already registered with PHP, the
  80. * existing scheme will be unregistered and replaced with the specified class.
  81. *
  82. * A stream is referenced as "scheme://target".
  83. *
  84. * The optional $filter parameter can be used to retrieve only the stream
  85. * wrappers that are appropriate for particular usage. For example, this returns
  86. * only stream wrappers that use local file storage:
  87. * @code
  88. * $local_stream_wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL);
  89. * @endcode
  90. *
  91. * The $filter parameter can only filter to types containing a particular flag.
  92. * In some cases, you may want to filter to types that do not contain a
  93. * particular flag. For example, you may want to retrieve all stream wrappers
  94. * that are not writable, or all stream wrappers that are not local. PHP's
  95. * array_diff_key() function can be used to help with this. For example, this
  96. * returns only stream wrappers that do not use local file storage:
  97. * @code
  98. * $remote_stream_wrappers = array_diff_key(file_get_stream_wrappers(STREAM_WRAPPERS_ALL), file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL));
  99. * @endcode
  100. *
  101. * @param $filter
  102. * (Optional) Filters out all types except those with an on bit for each on
  103. * bit in $filter. For example, if $filter is STREAM_WRAPPERS_WRITE_VISIBLE,
  104. * which is equal to (STREAM_WRAPPERS_READ | STREAM_WRAPPERS_WRITE |
  105. * STREAM_WRAPPERS_VISIBLE), then only stream wrappers with all three of these
  106. * bits set are returned. Defaults to STREAM_WRAPPERS_ALL, which returns all
  107. * registered stream wrappers.
  108. *
  109. * @return
  110. * An array keyed by scheme, with values containing an array of information
  111. * about the stream wrapper, as returned by hook_stream_wrappers(). If $filter
  112. * is omitted or set to STREAM_WRAPPERS_ALL, the entire Drupal stream wrapper
  113. * registry is returned. Otherwise only the stream wrappers whose 'type'
  114. * bitmask has an on bit for each bit specified in $filter are returned.
  115. *
  116. * @see hook_stream_wrappers()
  117. * @see hook_stream_wrappers_alter()
  118. */
  119. function file_get_stream_wrappers($filter = STREAM_WRAPPERS_ALL) {
  120. $wrappers_storage = &drupal_static(__FUNCTION__);
  121. if (!isset($wrappers_storage)) {
  122. $wrappers = module_invoke_all('stream_wrappers');
  123. foreach ($wrappers as $scheme => $info) {
  124. // Add defaults.
  125. $wrappers[$scheme] += array('type' => STREAM_WRAPPERS_NORMAL);
  126. }
  127. drupal_alter('stream_wrappers', $wrappers);
  128. $existing = stream_get_wrappers();
  129. foreach ($wrappers as $scheme => $info) {
  130. // We only register classes that implement our interface.
  131. if (in_array('DrupalStreamWrapperInterface', class_implements($info['class']), TRUE)) {
  132. // Record whether we are overriding an existing scheme.
  133. if (in_array($scheme, $existing, TRUE)) {
  134. $wrappers[$scheme]['override'] = TRUE;
  135. stream_wrapper_unregister($scheme);
  136. }
  137. else {
  138. $wrappers[$scheme]['override'] = FALSE;
  139. }
  140. if (($info['type'] & STREAM_WRAPPERS_LOCAL) == STREAM_WRAPPERS_LOCAL) {
  141. stream_wrapper_register($scheme, $info['class']);
  142. }
  143. else {
  144. stream_wrapper_register($scheme, $info['class'], STREAM_IS_URL);
  145. }
  146. }
  147. // Pre-populate the static cache with the filters most typically used.
  148. $wrappers_storage[STREAM_WRAPPERS_ALL][$scheme] = $wrappers[$scheme];
  149. if (($info['type'] & STREAM_WRAPPERS_WRITE_VISIBLE) == STREAM_WRAPPERS_WRITE_VISIBLE) {
  150. $wrappers_storage[STREAM_WRAPPERS_WRITE_VISIBLE][$scheme] = $wrappers[$scheme];
  151. }
  152. }
  153. }
  154. if (!isset($wrappers_storage[$filter])) {
  155. $wrappers_storage[$filter] = array();
  156. foreach ($wrappers_storage[STREAM_WRAPPERS_ALL] as $scheme => $info) {
  157. // Bit-wise filter.
  158. if (($info['type'] & $filter) == $filter) {
  159. $wrappers_storage[$filter][$scheme] = $info;
  160. }
  161. }
  162. }
  163. return $wrappers_storage[$filter];
  164. }
  165. /**
  166. * Returns the stream wrapper class name for a given scheme.
  167. *
  168. * @param $scheme
  169. * Stream scheme.
  170. *
  171. * @return
  172. * Return string if a scheme has a registered handler, or FALSE.
  173. */
  174. function file_stream_wrapper_get_class($scheme) {
  175. $wrappers = file_get_stream_wrappers();
  176. return empty($wrappers[$scheme]) ? FALSE : $wrappers[$scheme]['class'];
  177. }
  178. /**
  179. * Returns the scheme of a URI (e.g. a stream).
  180. *
  181. * @param $uri
  182. * A stream, referenced as "scheme://target".
  183. *
  184. * @return
  185. * A string containing the name of the scheme, or FALSE if none. For example,
  186. * the URI "public://example.txt" would return "public".
  187. *
  188. * @see file_uri_target()
  189. */
  190. function file_uri_scheme($uri) {
  191. $position = strpos((string) $uri, '://');
  192. return $position ? substr($uri, 0, $position) : FALSE;
  193. }
  194. /**
  195. * Checks that the scheme of a stream URI is valid.
  196. *
  197. * Confirms that there is a registered stream handler for the provided scheme
  198. * and that it is callable. This is useful if you want to confirm a valid
  199. * scheme without creating a new instance of the registered handler.
  200. *
  201. * @param $scheme
  202. * A URI scheme, a stream is referenced as "scheme://target".
  203. *
  204. * @return
  205. * Returns TRUE if the string is the name of a validated stream,
  206. * or FALSE if the scheme does not have a registered handler.
  207. */
  208. function file_stream_wrapper_valid_scheme($scheme) {
  209. // Does the scheme have a registered handler that is callable?
  210. $class = file_stream_wrapper_get_class($scheme);
  211. if (class_exists($class)) {
  212. return TRUE;
  213. }
  214. else {
  215. return FALSE;
  216. }
  217. }
  218. /**
  219. * Returns the part of a URI after the schema.
  220. *
  221. * @param $uri
  222. * A stream, referenced as "scheme://target".
  223. *
  224. * @return
  225. * A string containing the target (path), or FALSE if none.
  226. * For example, the URI "public://sample/test.txt" would return
  227. * "sample/test.txt".
  228. *
  229. * @see file_uri_scheme()
  230. */
  231. function file_uri_target($uri) {
  232. $data = explode('://', $uri, 2);
  233. // Remove erroneous leading or trailing, forward-slashes and backslashes.
  234. return count($data) == 2 ? trim($data[1], '\/') : FALSE;
  235. }
  236. /**
  237. * Gets the default file stream implementation.
  238. *
  239. * @return
  240. * 'public', 'private' or any other file scheme defined as the default.
  241. */
  242. function file_default_scheme() {
  243. return variable_get('file_default_scheme', 'public');
  244. }
  245. /**
  246. * Normalizes a URI by making it syntactically correct.
  247. *
  248. * A stream is referenced as "scheme://target".
  249. *
  250. * The following actions are taken:
  251. * - Remove trailing slashes from target
  252. * - Trim erroneous leading slashes from target. e.g. ":///" becomes "://".
  253. *
  254. * @param $uri
  255. * String reference containing the URI to normalize.
  256. *
  257. * @return
  258. * The normalized URI.
  259. */
  260. function file_stream_wrapper_uri_normalize($uri) {
  261. // Inline file_uri_scheme() function call for performance reasons.
  262. $position = strpos($uri, '://');
  263. $scheme = $position ? substr($uri, 0, $position) : FALSE;
  264. if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
  265. $target = file_uri_target($uri);
  266. if ($target !== FALSE) {
  267. $uri = $scheme . '://' . $target;
  268. }
  269. }
  270. return $uri;
  271. }
  272. /**
  273. * Returns a reference to the stream wrapper class responsible for a given URI.
  274. *
  275. * The scheme determines the stream wrapper class that should be
  276. * used by consulting the stream wrapper registry.
  277. *
  278. * @param $uri
  279. * A stream, referenced as "scheme://target".
  280. *
  281. * @return
  282. * Returns a new stream wrapper object appropriate for the given URI or FALSE
  283. * if no registered handler could be found. For example, a URI of
  284. * "private://example.txt" would return a new private stream wrapper object
  285. * (DrupalPrivateStreamWrapper).
  286. */
  287. function file_stream_wrapper_get_instance_by_uri($uri) {
  288. $scheme = file_uri_scheme($uri);
  289. $class = file_stream_wrapper_get_class($scheme);
  290. if (class_exists($class)) {
  291. $instance = new $class();
  292. $instance->setUri($uri);
  293. return $instance;
  294. }
  295. else {
  296. return FALSE;
  297. }
  298. }
  299. /**
  300. * Returns a reference to the stream wrapper class responsible for a scheme.
  301. *
  302. * This helper method returns a stream instance using a scheme. That is, the
  303. * passed string does not contain a "://". For example, "public" is a scheme
  304. * but "public://" is a URI (stream). This is because the later contains both
  305. * a scheme and target despite target being empty.
  306. *
  307. * Note: the instance URI will be initialized to "scheme://" so that you can
  308. * make the customary method calls as if you had retrieved an instance by URI.
  309. *
  310. * @param $scheme
  311. * If the stream was "public://target", "public" would be the scheme.
  312. *
  313. * @return
  314. * Returns a new stream wrapper object appropriate for the given $scheme.
  315. * For example, for the public scheme a stream wrapper object
  316. * (DrupalPublicStreamWrapper).
  317. * FALSE is returned if no registered handler could be found.
  318. */
  319. function file_stream_wrapper_get_instance_by_scheme($scheme) {
  320. $class = file_stream_wrapper_get_class($scheme);
  321. if (class_exists($class)) {
  322. $instance = new $class();
  323. $instance->setUri($scheme . '://');
  324. return $instance;
  325. }
  326. else {
  327. return FALSE;
  328. }
  329. }
  330. /**
  331. * Creates a web-accessible URL for a stream to an external or local file.
  332. *
  333. * Compatibility: normal paths and stream wrappers.
  334. *
  335. * There are two kinds of local files:
  336. * - "managed files", i.e. those stored by a Drupal-compatible stream wrapper.
  337. * These are files that have either been uploaded by users or were generated
  338. * automatically (for example through CSS aggregation).
  339. * - "shipped files", i.e. those outside of the files directory, which ship as
  340. * part of Drupal core or contributed modules or themes.
  341. *
  342. * @param $uri
  343. * The URI to a file for which we need an external URL, or the path to a
  344. * shipped file.
  345. *
  346. * @return
  347. * A string containing a URL that may be used to access the file.
  348. * If the provided string already contains a preceding 'http', 'https', or
  349. * '/', nothing is done and the same string is returned. If a stream wrapper
  350. * could not be found to generate an external URL, then FALSE is returned.
  351. *
  352. * @see http://drupal.org/node/515192
  353. */
  354. function file_create_url($uri) {
  355. // Allow the URI to be altered, e.g. to serve a file from a CDN or static
  356. // file server.
  357. drupal_alter('file_url', $uri);
  358. $scheme = file_uri_scheme($uri);
  359. if (!$scheme) {
  360. // Allow for:
  361. // - root-relative URIs (e.g. /foo.jpg in http://example.com/foo.jpg)
  362. // - protocol-relative URIs (e.g. //bar.jpg, which is expanded to
  363. // http://example.com/bar.jpg by the browser when viewing a page over
  364. // HTTP and to https://example.com/bar.jpg when viewing a HTTPS page)
  365. // Both types of relative URIs are characterized by a leading slash, hence
  366. // we can use a single check.
  367. if (drupal_substr($uri, 0, 1) == '/') {
  368. return $uri;
  369. }
  370. else {
  371. // If this is not a properly formatted stream, then it is a shipped file.
  372. // Therefore, return the urlencoded URI with the base URL prepended.
  373. return $GLOBALS['base_url'] . '/' . drupal_encode_path($uri);
  374. }
  375. }
  376. elseif ($scheme == 'http' || $scheme == 'https') {
  377. // Check for HTTP so that we don't have to implement getExternalUrl() for
  378. // the HTTP wrapper.
  379. return $uri;
  380. }
  381. else {
  382. // Attempt to return an external URL using the appropriate wrapper.
  383. if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
  384. return $wrapper->getExternalUrl();
  385. }
  386. else {
  387. return FALSE;
  388. }
  389. }
  390. }
  391. /**
  392. * Checks that the directory exists and is writable.
  393. *
  394. * Directories need to have execute permissions to be considered a directory by
  395. * FTP servers, etc.
  396. *
  397. * @param $directory
  398. * A string reference containing the name of a directory path or URI. A
  399. * trailing slash will be trimmed from a path.
  400. * @param $options
  401. * A bitmask to indicate if the directory should be created if it does
  402. * not exist (FILE_CREATE_DIRECTORY) or made writable if it is read-only
  403. * (FILE_MODIFY_PERMISSIONS).
  404. *
  405. * @return
  406. * TRUE if the directory exists (or was created) and is writable. FALSE
  407. * otherwise.
  408. */
  409. function file_prepare_directory(&$directory, $options = FILE_MODIFY_PERMISSIONS) {
  410. if (!file_stream_wrapper_valid_scheme(file_uri_scheme($directory))) {
  411. // Only trim if we're not dealing with a stream.
  412. $directory = rtrim($directory, '/\\');
  413. }
  414. // Check if directory exists.
  415. if (!is_dir($directory)) {
  416. // Let drupal_mkdir() recursively create directories and use the default
  417. // directory permissions.
  418. if ($options & FILE_CREATE_DIRECTORY) {
  419. return @drupal_mkdir($directory, NULL, TRUE);
  420. }
  421. return FALSE;
  422. }
  423. // The directory exists, so check to see if it is writable.
  424. $writable = is_writable($directory);
  425. if (!$writable && ($options & FILE_MODIFY_PERMISSIONS)) {
  426. return drupal_chmod($directory);
  427. }
  428. return $writable;
  429. }
  430. /**
  431. * Creates a .htaccess file in each Drupal files directory if it is missing.
  432. */
  433. function file_ensure_htaccess() {
  434. file_create_htaccess('public://', FALSE);
  435. if (variable_get('file_private_path', FALSE)) {
  436. file_create_htaccess('private://', TRUE);
  437. }
  438. file_create_htaccess('temporary://', TRUE);
  439. }
  440. /**
  441. * Creates a .htaccess file in the given directory.
  442. *
  443. * @param $directory
  444. * The directory.
  445. * @param $private
  446. * FALSE indicates that $directory should be an open and public directory.
  447. * The default is TRUE which indicates a private and protected directory.
  448. * @param $force_overwrite
  449. * Set to TRUE to attempt to overwrite the existing .htaccess file if one is
  450. * already present. Defaults to FALSE.
  451. */
  452. function file_create_htaccess($directory, $private = TRUE, $force_overwrite = FALSE) {
  453. if (file_uri_scheme($directory)) {
  454. $directory = file_stream_wrapper_uri_normalize($directory);
  455. }
  456. else {
  457. $directory = rtrim($directory, '/\\');
  458. }
  459. $htaccess_path = $directory . '/.htaccess';
  460. if (file_exists($htaccess_path) && !$force_overwrite) {
  461. // Short circuit if the .htaccess file already exists.
  462. return;
  463. }
  464. $htaccess_lines = file_htaccess_lines($private);
  465. // Write the .htaccess file.
  466. if (file_put_contents($htaccess_path, $htaccess_lines)) {
  467. drupal_chmod($htaccess_path, 0444);
  468. }
  469. else {
  470. $variables = array('%directory' => $directory, '!htaccess' => '<br />' . nl2br(check_plain($htaccess_lines)));
  471. watchdog('security', "Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your %directory directory which contains the following lines: <code>!htaccess</code>", $variables, WATCHDOG_ERROR);
  472. }
  473. }
  474. /**
  475. * Returns the standard .htaccess lines that Drupal writes to file directories.
  476. *
  477. * @param $private
  478. * (Optional) Set to FALSE to return the .htaccess lines for an open and
  479. * public directory. The default is TRUE, which returns the .htaccess lines
  480. * for a private and protected directory.
  481. *
  482. * @return
  483. * A string representing the desired contents of the .htaccess file.
  484. *
  485. * @see file_create_htaccess()
  486. */
  487. function file_htaccess_lines($private = TRUE) {
  488. $lines = <<<EOF
  489. # Turn off all options we don't need.
  490. Options None
  491. Options +FollowSymLinks
  492. # Set the catch-all handler to prevent scripts from being executed.
  493. SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
  494. <Files *>
  495. # Override the handler again if we're run later in the evaluation list.
  496. SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
  497. </Files>
  498. # If we know how to do it safely, disable the PHP engine entirely.
  499. <IfModule mod_php5.c>
  500. php_flag engine off
  501. </IfModule>
  502. <IfModule mod_php7.c>
  503. php_flag engine off
  504. </IfModule>
  505. # From PHP 8 there is no number in the module name.
  506. <IfModule mod_php.c>
  507. php_flag engine off
  508. </IfModule>
  509. EOF;
  510. if ($private) {
  511. $lines = <<<EOF
  512. # Deny all requests from Apache 2.4+.
  513. <IfModule mod_authz_core.c>
  514. Require all denied
  515. </IfModule>
  516. # Deny all requests from Apache 2.0-2.2.
  517. <IfModule !mod_authz_core.c>
  518. Deny from all
  519. </IfModule>
  520. EOF
  521. . "\n\n" . $lines;
  522. }
  523. return $lines;
  524. }
  525. /**
  526. * Loads file objects from the database.
  527. *
  528. * @param $fids
  529. * An array of file IDs.
  530. * @param $conditions
  531. * (deprecated) An associative array of conditions on the {file_managed}
  532. * table, where the keys are the database fields and the values are the
  533. * values those fields must have. Instead, it is preferable to use
  534. * EntityFieldQuery to retrieve a list of entity IDs loadable by
  535. * this function.
  536. *
  537. * @return
  538. * An array of file objects, indexed by fid.
  539. *
  540. * @todo Remove $conditions in Drupal 8.
  541. *
  542. * @see hook_file_load()
  543. * @see file_load()
  544. * @see entity_load()
  545. * @see EntityFieldQuery
  546. */
  547. function file_load_multiple($fids = array(), $conditions = array()) {
  548. return entity_load('file', $fids, $conditions);
  549. }
  550. /**
  551. * Loads a single file object from the database.
  552. *
  553. * @param $fid
  554. * A file ID.
  555. *
  556. * @return
  557. * An object representing the file, or FALSE if the file was not found.
  558. *
  559. * @see hook_file_load()
  560. * @see file_load_multiple()
  561. */
  562. function file_load($fid) {
  563. $files = file_load_multiple(array($fid), array());
  564. return reset($files);
  565. }
  566. /**
  567. * Saves a file object to the database.
  568. *
  569. * If the $file->fid is not set a new record will be added.
  570. *
  571. * @param $file
  572. * A file object returned by file_load().
  573. *
  574. * @return
  575. * The updated file object.
  576. *
  577. * @see hook_file_insert()
  578. * @see hook_file_update()
  579. */
  580. function file_save(stdClass $file) {
  581. $file->timestamp = REQUEST_TIME;
  582. $file->filesize = filesize($file->uri);
  583. // Load the stored entity, if any.
  584. if (!empty($file->fid) && !isset($file->original)) {
  585. $file->original = entity_load_unchanged('file', $file->fid);
  586. }
  587. module_invoke_all('file_presave', $file);
  588. module_invoke_all('entity_presave', $file, 'file');
  589. if (empty($file->fid)) {
  590. drupal_write_record('file_managed', $file);
  591. // Inform modules about the newly added file.
  592. module_invoke_all('file_insert', $file);
  593. module_invoke_all('entity_insert', $file, 'file');
  594. }
  595. else {
  596. drupal_write_record('file_managed', $file, 'fid');
  597. // Inform modules that the file has been updated.
  598. module_invoke_all('file_update', $file);
  599. module_invoke_all('entity_update', $file, 'file');
  600. }
  601. // Clear internal properties.
  602. unset($file->original);
  603. // Clear the static loading cache.
  604. entity_get_controller('file')->resetCache(array($file->fid));
  605. return $file;
  606. }
  607. /**
  608. * Determines where a file is used.
  609. *
  610. * @param $file
  611. * A file object.
  612. *
  613. * @return
  614. * A nested array with usage data. The first level is keyed by module name,
  615. * the second by object type and the third by the object id. The value
  616. * of the third level contains the usage count.
  617. *
  618. * @see file_usage_add()
  619. * @see file_usage_delete()
  620. */
  621. function file_usage_list(stdClass $file) {
  622. $result = db_select('file_usage', 'f')
  623. ->fields('f', array('module', 'type', 'id', 'count'))
  624. ->condition('fid', $file->fid)
  625. ->condition('count', 0, '>')
  626. ->execute();
  627. $references = array();
  628. foreach ($result as $usage) {
  629. $references[$usage->module][$usage->type][$usage->id] = $usage->count;
  630. }
  631. return $references;
  632. }
  633. /**
  634. * Records that a module is using a file.
  635. *
  636. * This usage information will be queried during file_delete() to ensure that
  637. * a file is not in use before it is physically removed from disk.
  638. *
  639. * Examples:
  640. * - A module that associates files with nodes, so $type would be
  641. * 'node' and $id would be the node's nid. Files for all revisions are stored
  642. * within a single nid.
  643. * - The User module associates an image with a user, so $type would be 'user'
  644. * and the $id would be the user's uid.
  645. *
  646. * @param $file
  647. * A file object.
  648. * @param $module
  649. * The name of the module using the file.
  650. * @param $type
  651. * The type of the object that contains the referenced file.
  652. * @param $id
  653. * The unique, numeric ID of the object containing the referenced file.
  654. * @param $count
  655. * (optional) The number of references to add to the object. Defaults to 1.
  656. *
  657. * @see file_usage_list()
  658. * @see file_usage_delete()
  659. */
  660. function file_usage_add(stdClass $file, $module, $type, $id, $count = 1) {
  661. db_merge('file_usage')
  662. ->key(array(
  663. 'fid' => $file->fid,
  664. 'module' => $module,
  665. 'type' => $type,
  666. 'id' => $id,
  667. ))
  668. ->fields(array('count' => $count))
  669. ->expression('count', 'count + :count', array(':count' => $count))
  670. ->execute();
  671. }
  672. /**
  673. * Removes a record to indicate that a module is no longer using a file.
  674. *
  675. * The file_delete() function is typically called after removing a file usage
  676. * to remove the record from the file_managed table and delete the file itself.
  677. *
  678. * @param $file
  679. * A file object.
  680. * @param $module
  681. * The name of the module using the file.
  682. * @param $type
  683. * (optional) The type of the object that contains the referenced file. May
  684. * be omitted if all module references to a file are being deleted.
  685. * @param $id
  686. * (optional) The unique, numeric ID of the object containing the referenced
  687. * file. May be omitted if all module references to a file are being deleted.
  688. * @param $count
  689. * (optional) The number of references to delete from the object. Defaults to
  690. * 1. 0 may be specified to delete all references to the file within a
  691. * specific object.
  692. *
  693. * @see file_usage_add()
  694. * @see file_usage_list()
  695. * @see file_delete()
  696. */
  697. function file_usage_delete(stdClass $file, $module, $type = NULL, $id = NULL, $count = 1) {
  698. // Delete rows that have a exact or less value to prevent empty rows.
  699. $query = db_delete('file_usage')
  700. ->condition('module', $module)
  701. ->condition('fid', $file->fid);
  702. if ($type && $id) {
  703. $query
  704. ->condition('type', $type)
  705. ->condition('id', $id);
  706. }
  707. if ($count) {
  708. $query->condition('count', $count, '<=');
  709. }
  710. $result = $query->execute();
  711. // If the row has more than the specified count decrement it by that number.
  712. if (!$result && $count > 0) {
  713. $query = db_update('file_usage')
  714. ->condition('module', $module)
  715. ->condition('fid', $file->fid);
  716. if ($type && $id) {
  717. $query
  718. ->condition('type', $type)
  719. ->condition('id', $id);
  720. }
  721. $query->expression('count', 'count - :count', array(':count' => $count));
  722. $query->execute();
  723. }
  724. }
  725. /**
  726. * Copies a file to a new location and adds a file record to the database.
  727. *
  728. * This function should be used when manipulating files that have records
  729. * stored in the database. This is a powerful function that in many ways
  730. * performs like an advanced version of copy().
  731. * - Checks if $source and $destination are valid and readable/writable.
  732. * - If file already exists in $destination either the call will error out,
  733. * replace the file or rename the file based on the $replace parameter.
  734. * - If the $source and $destination are equal, the behavior depends on the
  735. * $replace parameter. FILE_EXISTS_REPLACE will error out. FILE_EXISTS_RENAME
  736. * will rename the file until the $destination is unique.
  737. * - Adds the new file to the files database. If the source file is a
  738. * temporary file, the resulting file will also be a temporary file. See
  739. * file_save_upload() for details on temporary files.
  740. *
  741. * @param $source
  742. * A file object.
  743. * @param $destination
  744. * A string containing the destination that $source should be copied to.
  745. * This must be a stream wrapper URI.
  746. * @param $replace
  747. * Replace behavior when the destination file already exists:
  748. * - FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with
  749. * the destination name exists then its database entry will be updated. If
  750. * no database entry is found then a new one will be created.
  751. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  752. * unique.
  753. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  754. *
  755. * @return
  756. * File object if the copy is successful, or FALSE in the event of an error.
  757. *
  758. * @see file_unmanaged_copy()
  759. * @see hook_file_copy()
  760. */
  761. function file_copy(stdClass $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  762. if (!file_valid_uri($destination)) {
  763. if (($realpath = drupal_realpath($source->uri)) !== FALSE) {
  764. watchdog('file', 'File %file (%realpath) could not be copied, because the destination %destination is invalid. This is often caused by improper use of file_copy() or a missing stream wrapper.', array('%file' => $source->uri, '%realpath' => $realpath, '%destination' => $destination));
  765. }
  766. else {
  767. watchdog('file', 'File %file could not be copied, because the destination %destination is invalid. This is often caused by improper use of file_copy() or a missing stream wrapper.', array('%file' => $source->uri, '%destination' => $destination));
  768. }
  769. drupal_set_message(t('The specified file %file could not be copied, because the destination is invalid. More information is available in the system log.', array('%file' => $source->uri)), 'error');
  770. return FALSE;
  771. }
  772. if ($uri = file_unmanaged_copy($source->uri, $destination, $replace)) {
  773. $file = clone $source;
  774. $file->fid = NULL;
  775. $file->uri = $uri;
  776. $file->filename = drupal_basename($uri);
  777. // If we are replacing an existing file re-use its database record.
  778. if ($replace == FILE_EXISTS_REPLACE) {
  779. $existing_files = file_load_multiple(array(), array('uri' => $uri));
  780. if (count($existing_files)) {
  781. $existing = reset($existing_files);
  782. $file->fid = $existing->fid;
  783. $file->filename = $existing->filename;
  784. }
  785. }
  786. // If we are renaming around an existing file (rather than a directory),
  787. // use its basename for the filename.
  788. elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
  789. $file->filename = drupal_basename($destination);
  790. }
  791. $file = file_save($file);
  792. // Inform modules that the file has been copied.
  793. module_invoke_all('file_copy', $file, $source);
  794. return $file;
  795. }
  796. return FALSE;
  797. }
  798. /**
  799. * Determines whether the URI has a valid scheme for file API operations.
  800. *
  801. * There must be a scheme and it must be a Drupal-provided scheme like
  802. * 'public', 'private', 'temporary', or an extension provided with
  803. * hook_stream_wrappers().
  804. *
  805. * @param $uri
  806. * The URI to be tested.
  807. *
  808. * @return
  809. * TRUE if the URI is allowed.
  810. */
  811. function file_valid_uri($uri) {
  812. // Assert that the URI has an allowed scheme. Barepaths are not allowed.
  813. $uri_scheme = file_uri_scheme($uri);
  814. if (empty($uri_scheme) || !file_stream_wrapper_valid_scheme($uri_scheme)) {
  815. return FALSE;
  816. }
  817. return TRUE;
  818. }
  819. /**
  820. * Copies a file to a new location without invoking the file API.
  821. *
  822. * This is a powerful function that in many ways performs like an advanced
  823. * version of copy().
  824. * - Checks if $source and $destination are valid and readable/writable.
  825. * - If file already exists in $destination either the call will error out,
  826. * replace the file or rename the file based on the $replace parameter.
  827. * - If the $source and $destination are equal, the behavior depends on the
  828. * $replace parameter. FILE_EXISTS_REPLACE will error out. FILE_EXISTS_RENAME
  829. * will rename the file until the $destination is unique.
  830. * - Provides a fallback using realpaths if the move fails using stream
  831. * wrappers. This can occur because PHP's copy() function does not properly
  832. * support streams if safe_mode or open_basedir are enabled. See
  833. * https://bugs.php.net/bug.php?id=60456
  834. *
  835. * @param $source
  836. * A string specifying the filepath or URI of the source file.
  837. * @param $destination
  838. * A URI containing the destination that $source should be copied to. The
  839. * URI may be a bare filepath (without a scheme). If this value is omitted,
  840. * Drupal's default files scheme will be used, usually "public://".
  841. * @param $replace
  842. * Replace behavior when the destination file already exists:
  843. * - FILE_EXISTS_REPLACE - Replace the existing file.
  844. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  845. * unique.
  846. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  847. *
  848. * @return
  849. * The path to the new file, or FALSE in the event of an error.
  850. *
  851. * @see file_copy()
  852. */
  853. function file_unmanaged_copy($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  854. $original_source = $source;
  855. // Assert that the source file actually exists.
  856. if (!file_exists($source)) {
  857. // @todo Replace drupal_set_message() calls with exceptions instead.
  858. drupal_set_message(t('The specified file %file could not be copied, because no file by that name exists. Please check that you supplied the correct filename.', array('%file' => $original_source)), 'error');
  859. if (($realpath = drupal_realpath($original_source)) !== FALSE) {
  860. watchdog('file', 'File %file (%realpath) could not be copied because it does not exist.', array('%file' => $original_source, '%realpath' => $realpath));
  861. }
  862. else {
  863. watchdog('file', 'File %file could not be copied because it does not exist.', array('%file' => $original_source));
  864. }
  865. return FALSE;
  866. }
  867. // Build a destination URI if necessary.
  868. if (!isset($destination)) {
  869. $destination = file_build_uri(drupal_basename($source));
  870. }
  871. // Prepare the destination directory.
  872. if (file_prepare_directory($destination)) {
  873. // The destination is already a directory, so append the source basename.
  874. $destination = file_stream_wrapper_uri_normalize($destination . '/' . drupal_basename($source));
  875. }
  876. else {
  877. // Perhaps $destination is a dir/file?
  878. $dirname = drupal_dirname($destination);
  879. if (!file_prepare_directory($dirname)) {
  880. // The destination is not valid.
  881. watchdog('file', 'File %file could not be copied, because the destination directory %destination is not configured correctly.', array('%file' => $original_source, '%destination' => $dirname));
  882. drupal_set_message(t('The specified file %file could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.', array('%file' => $original_source)), 'error');
  883. return FALSE;
  884. }
  885. }
  886. // Determine whether we can perform this operation based on overwrite rules.
  887. $destination = file_destination($destination, $replace);
  888. if ($destination === FALSE) {
  889. drupal_set_message(t('The file %file could not be copied because a file by that name already exists in the destination directory.', array('%file' => $original_source)), 'error');
  890. watchdog('file', 'File %file could not be copied because a file by that name already exists in the destination directory (%directory)', array('%file' => $original_source, '%directory' => $destination));
  891. return FALSE;
  892. }
  893. // Assert that the source and destination filenames are not the same.
  894. $real_source = drupal_realpath($source);
  895. $real_destination = drupal_realpath($destination);
  896. if ($source == $destination || ($real_source !== FALSE) && ($real_source == $real_destination)) {
  897. drupal_set_message(t('The specified file %file was not copied because it would overwrite itself.', array('%file' => $source)), 'error');
  898. watchdog('file', 'File %file could not be copied because it would overwrite itself.', array('%file' => $source));
  899. return FALSE;
  900. }
  901. // Make sure the .htaccess files are present.
  902. file_ensure_htaccess();
  903. // Perform the copy operation.
  904. if (!@copy($source, $destination)) {
  905. // If the copy failed and realpaths exist, retry the operation using them
  906. // instead.
  907. if ($real_source === FALSE || $real_destination === FALSE || !@copy($real_source, $real_destination)) {
  908. watchdog('file', 'The specified file %file could not be copied to %destination.', array('%file' => $source, '%destination' => $destination), WATCHDOG_ERROR);
  909. return FALSE;
  910. }
  911. }
  912. // Set the permissions on the new file.
  913. drupal_chmod($destination);
  914. return $destination;
  915. }
  916. /**
  917. * Constructs a URI to Drupal's default files location given a relative path.
  918. */
  919. function file_build_uri($path) {
  920. $uri = file_default_scheme() . '://' . $path;
  921. return file_stream_wrapper_uri_normalize($uri);
  922. }
  923. /**
  924. * Determines the destination path for a file.
  925. *
  926. * @param $destination
  927. * A string specifying the desired final URI or filepath.
  928. * @param $replace
  929. * Replace behavior when the destination file already exists.
  930. * - FILE_EXISTS_REPLACE - Replace the existing file.
  931. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  932. * unique.
  933. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  934. *
  935. * @return
  936. * The destination filepath, or FALSE if the file already exists
  937. * and FILE_EXISTS_ERROR is specified.
  938. *
  939. * @throws RuntimeException
  940. * Thrown if the filename contains invalid UTF-8.
  941. */
  942. function file_destination($destination, $replace) {
  943. $basename = drupal_basename($destination);
  944. if (!drupal_validate_utf8($basename)) {
  945. throw new RuntimeException(sprintf("Invalid filename '%s'", $basename));
  946. }
  947. if (file_exists($destination)) {
  948. switch ($replace) {
  949. case FILE_EXISTS_REPLACE:
  950. // Do nothing here, we want to overwrite the existing file.
  951. break;
  952. case FILE_EXISTS_RENAME:
  953. $directory = drupal_dirname($destination);
  954. $destination = file_create_filename($basename, $directory);
  955. break;
  956. case FILE_EXISTS_ERROR:
  957. // Error reporting handled by calling function.
  958. return FALSE;
  959. }
  960. }
  961. return $destination;
  962. }
  963. /**
  964. * Moves a file to a new location and update the file's database entry.
  965. *
  966. * Moving a file is performed by copying the file to the new location and then
  967. * deleting the original.
  968. * - Checks if $source and $destination are valid and readable/writable.
  969. * - Performs a file move if $source is not equal to $destination.
  970. * - If file already exists in $destination either the call will error out,
  971. * replace the file or rename the file based on the $replace parameter.
  972. * - Adds the new file to the files database.
  973. *
  974. * @param $source
  975. * A file object.
  976. * @param $destination
  977. * A string containing the destination that $source should be moved to.
  978. * This must be a stream wrapper URI.
  979. * @param $replace
  980. * Replace behavior when the destination file already exists:
  981. * - FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with
  982. * the destination name exists then its database entry will be updated and
  983. * file_delete() called on the source file after hook_file_move is called.
  984. * If no database entry is found then the source files record will be
  985. * updated.
  986. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  987. * unique.
  988. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  989. *
  990. * @return
  991. * Resulting file object for success, or FALSE in the event of an error.
  992. *
  993. * @see file_unmanaged_move()
  994. * @see hook_file_move()
  995. */
  996. function file_move(stdClass $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  997. if (!file_valid_uri($destination)) {
  998. if (($realpath = drupal_realpath($source->uri)) !== FALSE) {
  999. watchdog('file', 'File %file (%realpath) could not be moved, because the destination %destination is invalid. This may be caused by improper use of file_move() or a missing stream wrapper.', array('%file' => $source->uri, '%realpath' => $realpath, '%destination' => $destination));
  1000. }
  1001. else {
  1002. watchdog('file', 'File %file could not be moved, because the destination %destination is invalid. This may be caused by improper use of file_move() or a missing stream wrapper.', array('%file' => $source->uri, '%destination' => $destination));
  1003. }
  1004. drupal_set_message(t('The specified file %file could not be moved, because the destination is invalid. More information is available in the system log.', array('%file' => $source->uri)), 'error');
  1005. return FALSE;
  1006. }
  1007. if ($uri = file_unmanaged_move($source->uri, $destination, $replace)) {
  1008. $delete_source = FALSE;
  1009. $file = clone $source;
  1010. $file->uri = $uri;
  1011. // If we are replacing an existing file re-use its database record.
  1012. if ($replace == FILE_EXISTS_REPLACE) {
  1013. $existing_files = file_load_multiple(array(), array('uri' => $uri));
  1014. if (count($existing_files)) {
  1015. $existing = reset($existing_files);
  1016. $delete_source = TRUE;
  1017. $file->fid = $existing->fid;
  1018. }
  1019. }
  1020. // If we are renaming around an existing file (rather than a directory),
  1021. // use its basename for the filename.
  1022. elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
  1023. $file->filename = drupal_basename($destination);
  1024. }
  1025. $file = file_save($file);
  1026. // Inform modules that the file has been moved.
  1027. module_invoke_all('file_move', $file, $source);
  1028. if ($delete_source) {
  1029. // Try a soft delete to remove original if it's not in use elsewhere.
  1030. file_delete($source);
  1031. }
  1032. return $file;
  1033. }
  1034. return FALSE;
  1035. }
  1036. /**
  1037. * Moves a file to a new location without database changes or hook invocation.
  1038. *
  1039. * @param $source
  1040. * A string specifying the filepath or URI of the original file.
  1041. * @param $destination
  1042. * A string containing the destination that $source should be moved to.
  1043. * This must be a stream wrapper URI. If this value is omitted, Drupal's
  1044. * default files scheme will be used, usually "public://".
  1045. * @param $replace
  1046. * Replace behavior when the destination file already exists:
  1047. * - FILE_EXISTS_REPLACE - Replace the existing file.
  1048. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  1049. * unique.
  1050. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  1051. *
  1052. * @return
  1053. * The URI of the moved file, or FALSE in the event of an error.
  1054. *
  1055. * @see file_move()
  1056. */
  1057. function file_unmanaged_move($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  1058. $filepath = file_unmanaged_copy($source, $destination, $replace);
  1059. if ($filepath == FALSE || file_unmanaged_delete($source) == FALSE) {
  1060. return FALSE;
  1061. }
  1062. return $filepath;
  1063. }
  1064. /**
  1065. * Modifies a filename as needed for security purposes.
  1066. *
  1067. * Munging a file name prevents unknown file extensions from masking exploit
  1068. * files. When web servers such as Apache decide how to process a URL request,
  1069. * they use the file extension. If the extension is not recognized, Apache
  1070. * skips that extension and uses the previous file extension. For example, if
  1071. * the file being requested is exploit.php.pps, and Apache does not recognize
  1072. * the '.pps' extension, it treats the file as PHP and executes it. To make
  1073. * this file name safe for Apache and prevent it from executing as PHP, the
  1074. * .php extension is "munged" into .php_, making the safe file name
  1075. * exploit.php_.pps.
  1076. *
  1077. * Specifically, this function adds an underscore to all extensions that are
  1078. * between 2 and 5 characters in length, internal to the file name, and either
  1079. * included in the list of unsafe extensions, or not included in $extensions.
  1080. *
  1081. * Function behavior is also controlled by the Drupal variable
  1082. * 'allow_insecure_uploads'. If 'allow_insecure_uploads' evaluates to TRUE, no
  1083. * alterations will be made, if it evaluates to FALSE, the filename is 'munged'.
  1084. *
  1085. * @param $filename
  1086. * File name to modify.
  1087. * @param $extensions
  1088. * A space-separated list of extensions that should not be altered. Note that
  1089. * extensions that are unsafe will be altered regardless of this parameter.
  1090. * @param $alerts
  1091. * If TRUE, drupal_set_message() will be called to display a message if the
  1092. * file name was changed.
  1093. *
  1094. * @return
  1095. * The potentially modified $filename.
  1096. */
  1097. function file_munge_filename($filename, $extensions, $alerts = TRUE) {
  1098. $original = $filename;
  1099. // Allow potentially insecure uploads for very savvy users and admin
  1100. if (!variable_get('allow_insecure_uploads', 0)) {
  1101. // Remove any null bytes. See http://php.net/manual/security.filesystem.nullbytes.php
  1102. $filename = str_replace(chr(0), '', $filename);
  1103. $whitelist = array_unique(explode(' ', strtolower(trim($extensions))));
  1104. // Remove unsafe extensions from the list of allowed extensions.
  1105. $whitelist = array_diff($whitelist, explode('|', FILE_INSECURE_EXTENSIONS));
  1106. // Split the filename up by periods. The first part becomes the basename
  1107. // the last part the final extension.
  1108. $filename_parts = explode('.', $filename);
  1109. $new_filename = array_shift($filename_parts); // Remove file basename.
  1110. $final_extension = array_pop($filename_parts); // Remove final extension.
  1111. // Loop through the middle parts of the name and add an underscore to the
  1112. // end of each section that could be a file extension but isn't in the list
  1113. // of allowed extensions.
  1114. foreach ($filename_parts as $filename_part) {
  1115. $new_filename .= '.' . $filename_part;
  1116. if (!in_array(strtolower($filename_part), $whitelist) && preg_match("/^[a-zA-Z]{2,5}\d?$/", $filename_part)) {
  1117. $new_filename .= '_';
  1118. }
  1119. }
  1120. $filename = $new_filename . '.' . $final_extension;
  1121. if ($alerts && $original != $filename) {
  1122. drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $filename)));
  1123. }
  1124. }
  1125. return $filename;
  1126. }
  1127. /**
  1128. * Undoes the effect of file_munge_filename().
  1129. *
  1130. * @param $filename
  1131. * String with the filename to be unmunged.
  1132. *
  1133. * @return
  1134. * An unmunged filename string.
  1135. */
  1136. function file_unmunge_filename($filename) {
  1137. return str_replace('_.', '.', $filename);
  1138. }
  1139. /**
  1140. * Creates a full file path from a directory and filename.
  1141. *
  1142. * If a file with the specified name already exists, an alternative will be
  1143. * used.
  1144. *
  1145. * @param $basename
  1146. * String filename
  1147. * @param $directory
  1148. * String containing the directory or parent URI.
  1149. *
  1150. * @return
  1151. * File path consisting of $directory and a unique filename based off
  1152. * of $basename.
  1153. *
  1154. * @throws RuntimeException
  1155. * Thrown if the $basename is not valid UTF-8 or another error occurs
  1156. * stripping control characters.
  1157. */
  1158. function file_create_filename($basename, $directory) {
  1159. $original = $basename;
  1160. // Strip control characters (ASCII value < 32). Though these are allowed in
  1161. // some filesystems, not many applications handle them well.
  1162. $basename = preg_replace('/[\x00-\x1F]/u', '_', $basename);
  1163. if (preg_last_error() !== PREG_NO_ERROR) {
  1164. throw new RuntimeException(sprintf("Invalid filename '%s'", $original));
  1165. }
  1166. if (substr(PHP_OS, 0, 3) == 'WIN') {
  1167. // These characters are not allowed in Windows filenames
  1168. $basename = str_replace(array(':', '*', '?', '"', '<', '>', '|'), '_', $basename);
  1169. }
  1170. // A URI or path may already have a trailing slash or look like "public://".
  1171. if (substr($directory, -1) == '/') {
  1172. $separator = '';
  1173. }
  1174. else {
  1175. $separator = '/';
  1176. }
  1177. $destination = $directory . $separator . $basename;
  1178. if (file_exists($destination)) {
  1179. // Destination file already exists, generate an alternative.
  1180. $pos = strrpos($basename, '.');
  1181. if ($pos !== FALSE) {
  1182. $name = substr($basename, 0, $pos);
  1183. $ext = substr($basename, $pos);
  1184. }
  1185. else {
  1186. $name = $basename;
  1187. $ext = '';
  1188. }
  1189. $counter = 0;
  1190. do {
  1191. $destination = $directory . $separator . $name . '_' . $counter++ . $ext;
  1192. } while (file_exists($destination));
  1193. }
  1194. return $destination;
  1195. }
  1196. /**
  1197. * Deletes a file and its database record.
  1198. *
  1199. * If the $force parameter is not TRUE, file_usage_list() will be called to
  1200. * determine if the file is being used by any modules. If the file is being
  1201. * used the delete will be canceled.
  1202. *
  1203. * @param $file
  1204. * A file object.
  1205. * @param $force
  1206. * Boolean indicating that the file should be deleted even if the file is
  1207. * reported as in use by the file_usage table.
  1208. *
  1209. * @return mixed
  1210. * TRUE for success, FALSE in the event of an error, or an array if the file
  1211. * is being used by any modules.
  1212. *
  1213. * @see file_unmanaged_delete()
  1214. * @see file_usage_list()
  1215. * @see file_usage_delete()
  1216. * @see hook_file_delete()
  1217. */
  1218. function file_delete(stdClass $file, $force = FALSE) {
  1219. if (!file_valid_uri($file->uri)) {
  1220. if (($realpath = drupal_realpath($file->uri)) !== FALSE) {
  1221. watchdog('file', 'File %file (%realpath) could not be deleted because it is not a valid URI. This may be caused by improper use of file_delete() or a missing stream wrapper.', array('%file' => $file->uri, '%realpath' => $realpath));
  1222. }
  1223. else {
  1224. watchdog('file', 'File %file could not be deleted because it is not a valid URI. This may be caused by improper use of file_delete() or a missing stream wrapper.', array('%file' => $file->uri));
  1225. }
  1226. drupal_set_message(t('The specified file %file could not be deleted, because it is not a valid URI. More information is available in the system log.', array('%file' => $file->uri)), 'error');
  1227. return FALSE;
  1228. }
  1229. // If any module still has a usage entry in the file_usage table, the file
  1230. // will not be deleted, but file_delete() will return a populated array
  1231. // that tests as TRUE.
  1232. if (!$force && ($references = file_usage_list($file))) {
  1233. return $references;
  1234. }
  1235. // Let other modules clean up any references to the deleted file.
  1236. module_invoke_all('file_delete', $file);
  1237. module_invoke_all('entity_delete', $file, 'file');
  1238. // Make sure the file is deleted before removing its row from the
  1239. // database, so UIs can still find the file in the database.
  1240. if (file_unmanaged_delete($file->uri)) {
  1241. db_delete('file_managed')->condition('fid', $file->fid)->execute();
  1242. db_delete('file_usage')->condition('fid', $file->fid)->execute();
  1243. entity_get_controller('file')->resetCache();
  1244. return TRUE;
  1245. }
  1246. return FALSE;
  1247. }
  1248. /**
  1249. * Deletes a file without database changes or hook invocations.
  1250. *
  1251. * This function should be used when the file to be deleted does not have an
  1252. * entry recorded in the files table.
  1253. *
  1254. * @param $path
  1255. * A string containing a file path or (streamwrapper) URI.
  1256. *
  1257. * @return
  1258. * TRUE for success or path does not exist, or FALSE in the event of an
  1259. * error.
  1260. *
  1261. * @see file_delete()
  1262. * @see file_unmanaged_delete_recursive()
  1263. */
  1264. function file_unmanaged_delete($path) {
  1265. if (is_dir($path)) {
  1266. watchdog('file', '%path is a directory and cannot be removed using file_unmanaged_delete().', array('%path' => $path), WATCHDOG_ERROR);
  1267. return FALSE;
  1268. }
  1269. if (is_file($path)) {
  1270. return drupal_unlink($path);
  1271. }
  1272. // Return TRUE for non-existent file, but log that nothing was actually
  1273. // deleted, as the current state is the intended result.
  1274. if (!file_exists($path)) {
  1275. watchdog('file', 'The file %path was not deleted, because it does not exist.', array('%path' => $path), WATCHDOG_NOTICE);
  1276. return TRUE;
  1277. }
  1278. // We cannot handle anything other than files and directories. Log an error
  1279. // for everything else (sockets, symbolic links, etc).
  1280. watchdog('file', 'The file %path is not of a recognized type so it was not deleted.', array('%path' => $path), WATCHDOG_ERROR);
  1281. return FALSE;
  1282. }
  1283. /**
  1284. * Deletes all files and directories in the specified filepath recursively.
  1285. *
  1286. * If the specified path is a directory then the function will call itself
  1287. * recursively to process the contents. Once the contents have been removed the
  1288. * directory will also be removed.
  1289. *
  1290. * If the specified path is a file then it will be passed to
  1291. * file_unmanaged_delete().
  1292. *
  1293. * Note that this only deletes visible files with write permission.
  1294. *
  1295. * @param $path
  1296. * A string containing either an URI or a file or directory path.
  1297. *
  1298. * @return
  1299. * TRUE for success or if path does not exist, FALSE in the event of an
  1300. * error.
  1301. *
  1302. * @see file_unmanaged_delete()
  1303. */
  1304. function file_unmanaged_delete_recursive($path) {
  1305. if (is_dir($path)) {
  1306. $dir = dir($path);
  1307. while (($entry = $dir->read()) !== FALSE) {
  1308. if ($entry == '.' || $entry == '..') {
  1309. continue;
  1310. }
  1311. $entry_path = $path . '/' . $entry;
  1312. file_unmanaged_delete_recursive($entry_path);
  1313. }
  1314. $dir->close();
  1315. return drupal_rmdir($path);
  1316. }
  1317. return file_unmanaged_delete($path);
  1318. }
  1319. /**
  1320. * Determines total disk space used by a single user or the whole filesystem.
  1321. *
  1322. * @param $uid
  1323. * Optional. A user id, specifying NULL returns the total space used by all
  1324. * non-temporary files.
  1325. * @param $status
  1326. * Optional. The file status to consider. The default is to only
  1327. * consider files in status FILE_STATUS_PERMANENT.
  1328. *
  1329. * @return
  1330. * An integer containing the number of bytes used.
  1331. */
  1332. function file_space_used($uid = NULL, $status = FILE_STATUS_PERMANENT) {
  1333. $query = db_select('file_managed', 'f');
  1334. $query->condition('f.status', $status);
  1335. $query->addExpression('SUM(f.filesize)', 'filesize');
  1336. if (isset($uid)) {
  1337. $query->condition('f.uid', $uid);
  1338. }
  1339. return $query->execute()->fetchField();
  1340. }
  1341. /**
  1342. * Saves a file upload to a new location.
  1343. *
  1344. * The file will be added to the {file_managed} table as a temporary file.
  1345. * Temporary files are periodically cleaned. To make the file a permanent file,
  1346. * assign the status and use file_save() to save the changes.
  1347. *
  1348. * @param $form_field_name
  1349. * A string that is the associative array key of the upload form element in
  1350. * the form array.
  1351. * @param $validators
  1352. * An optional, associative array of callback functions used to validate the
  1353. * file. See file_validate() for a full discussion of the array format.
  1354. * If no extension validator is provided it will default to a limited safe
  1355. * list of extensions which is as follows: "jpg jpeg gif png txt
  1356. * doc xls pdf ppt pps odt ods odp". To allow all extensions you must
  1357. * explicitly set the 'file_validate_extensions' validator to an empty array
  1358. * (Beware: this is not safe and should only be allowed for trusted users, if
  1359. * at all).
  1360. * @param $destination
  1361. * A string containing the URI that the file should be copied to. This must
  1362. * be a stream wrapper URI. If this value is omitted, Drupal's temporary
  1363. * files scheme will be used ("temporary://").
  1364. * @param $replace
  1365. * Replace behavior when the destination file already exists:
  1366. * - FILE_EXISTS_REPLACE: Replace the existing file.
  1367. * - FILE_EXISTS_RENAME: Append _{incrementing number} until the filename is
  1368. * unique.
  1369. * - FILE_EXISTS_ERROR: Do nothing and return FALSE.
  1370. *
  1371. * @return
  1372. * An object containing the file information if the upload succeeded, FALSE
  1373. * in the event of an error, or NULL if no file was uploaded. The
  1374. * documentation for the "File interface" group, which you can find under
  1375. * Related topics, or the header at the top of this file, documents the
  1376. * components of a file object. In addition to the standard components,
  1377. * this function adds:
  1378. * - source: Path to the file before it is moved.
  1379. * - destination: Path to the file after it is moved (same as 'uri').
  1380. */
  1381. function file_save_upload($form_field_name, $validators = array(), $destination = FALSE, $replace = FILE_EXISTS_RENAME) {
  1382. global $user;
  1383. static $upload_cache;
  1384. // Return cached objects without processing since the file will have
  1385. // already been processed and the paths in _FILES will be invalid.
  1386. if (isset($upload_cache[$form_field_name])) {
  1387. return $upload_cache[$form_field_name];
  1388. }
  1389. // Make sure there's an upload to process.
  1390. if (empty($_FILES['files']['name'][$form_field_name])) {
  1391. return NULL;
  1392. }
  1393. // Check for file upload errors and return FALSE if a lower level system
  1394. // error occurred. For a complete list of errors:
  1395. // See http://php.net/manual/features.file-upload.errors.php.
  1396. switch ($_FILES['files']['error'][$form_field_name]) {
  1397. case UPLOAD_ERR_INI_SIZE:
  1398. case UPLOAD_ERR_FORM_SIZE:
  1399. drupal_set_message(t('The file %file could not be saved, because it exceeds %maxsize, the maximum allowed size for uploads.', array('%file' => $_FILES['files']['name'][$form_field_name], '%maxsize' => format_size(file_upload_max_size()))), 'error');
  1400. return FALSE;
  1401. case UPLOAD_ERR_PARTIAL:
  1402. case UPLOAD_ERR_NO_FILE:
  1403. drupal_set_message(t('The file %file could not be saved, because the upload did not complete.', array('%file' => $_FILES['files']['name'][$form_field_name])), 'error');
  1404. return FALSE;
  1405. case UPLOAD_ERR_OK:
  1406. // Final check that this is a valid upload, if it isn't, use the
  1407. // default error handler.
  1408. if (is_uploaded_file($_FILES['files']['tmp_name'][$form_field_name])) {
  1409. break;
  1410. }
  1411. // Unknown error
  1412. default:
  1413. drupal_set_message(t('The file %file could not be saved. An unknown error has occurred.', array('%file' => $_FILES['files']['name'][$form_field_name])), 'error');
  1414. return FALSE;
  1415. }
  1416. // Begin building file object.
  1417. $file = new stdClass();
  1418. $file->uid = $user->uid;
  1419. $file->status = 0;
  1420. $file->filename = trim(drupal_basename($_FILES['files']['name'][$form_field_name]), '.');
  1421. $file->uri = $_FILES['files']['tmp_name'][$form_field_name];
  1422. $file->filemime = file_get_mimetype($file->filename);
  1423. $file->filesize = $_FILES['files']['size'][$form_field_name];
  1424. $extensions = '';
  1425. if (isset($validators['file_validate_extensions'])) {
  1426. if (isset($validators['file_validate_extensions'][0])) {
  1427. // Build the list of non-munged extensions if the caller provided them.
  1428. $extensions = $validators['file_validate_extensions'][0];
  1429. }
  1430. else {
  1431. // If 'file_validate_extensions' is set and the list is empty then the
  1432. // caller wants to allow any extension. In this case we have to remove the
  1433. // validator or else it will reject all extensions.
  1434. unset($validators['file_validate_extensions']);
  1435. }
  1436. }
  1437. else {
  1438. // No validator was provided, so add one using the default list.
  1439. // Build a default non-munged safe list for file_munge_filename().
  1440. $extensions = 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp';
  1441. $validators['file_validate_extensions'] = array();
  1442. $validators['file_validate_extensions'][0] = $extensions;
  1443. }
  1444. if (!variable_get('allow_insecure_uploads', 0)) {
  1445. if (!empty($extensions)) {
  1446. // Munge the filename to protect against possible malicious extension hiding
  1447. // within an unknown file type (ie: filename.html.foo).
  1448. $file->filename = file_munge_filename($file->filename, $extensions);
  1449. }
  1450. // Rename potentially executable files, to help prevent exploits (i.e. will
  1451. // rename filename.php.foo and filename.php to filename.php_.foo_.txt and
  1452. // filename.php_.txt, respectively). Don't rename if 'allow_insecure_uploads'
  1453. // evaluates to TRUE.
  1454. if (preg_match('/\.(' . FILE_INSECURE_EXTENSIONS . ')(\.|$)/i', $file->filename)) {
  1455. // If the file will be rejected anyway due to a disallowed extension, it
  1456. // should not be renamed; rather, we'll let file_validate_extensions()
  1457. // reject it below.
  1458. if (!isset($validators['file_validate_extensions']) || !file_validate_extensions($file, $extensions)) {
  1459. $file->filemime = 'text/plain';
  1460. if (substr($file->filename, -4) != '.txt') {
  1461. // The destination filename will also later be used to create the URI.
  1462. $file->filename .= '.txt';
  1463. }
  1464. $file->filename = file_munge_filename($file->filename, $extensions, FALSE);
  1465. drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $file->filename)));
  1466. // The .txt extension may not be in the allowed list of extensions. We have
  1467. // to add it here or else the file upload will fail.
  1468. if (!empty($validators['file_validate_extensions'][0])) {
  1469. $validators['file_validate_extensions'][0] .= ' txt';
  1470. }
  1471. }
  1472. }
  1473. }
  1474. // If the destination is not provided, use the temporary directory.
  1475. if (empty($destination)) {
  1476. $destination = 'temporary://';
  1477. }
  1478. // Assert that the destination contains a valid stream.
  1479. $destination_scheme = file_uri_scheme($destination);
  1480. if (!$destination_scheme || !file_stream_wrapper_valid_scheme($destination_scheme)) {
  1481. drupal_set_message(t('The file could not be uploaded, because the destination %destination is invalid.', array('%destination' => $destination)), 'error');
  1482. return FALSE;
  1483. }
  1484. $file->source = $form_field_name;
  1485. // A URI may already have a trailing slash or look like "public://".
  1486. if (substr($destination, -1) != '/') {
  1487. $destination .= '/';
  1488. }
  1489. try {
  1490. $file->destination = file_destination($destination . $file->filename, $replace);
  1491. }
  1492. catch (RuntimeException $e) {
  1493. drupal_set_message(t('The file %source could not be uploaded because the name is invalid.', array('%source' => $form_field_name)), 'error');
  1494. return FALSE;
  1495. }
  1496. // If file_destination() returns FALSE then $replace == FILE_EXISTS_ERROR and
  1497. // there's an existing file so we need to bail.
  1498. if ($file->destination === FALSE) {
  1499. drupal_set_message(t('The file %source could not be uploaded because a file by that name already exists in the destination %directory.', array('%source' => $form_field_name, '%directory' => $destination)), 'error');
  1500. return FALSE;
  1501. }
  1502. // Add in our check of the file name length.
  1503. $validators['file_validate_name_length'] = array();
  1504. // Call the validation functions specified by this function's caller.
  1505. $errors = file_validate($file, $validators);
  1506. // Check for errors.
  1507. if (!empty($errors)) {
  1508. $message = t('The specified file %name could not be uploaded.', array('%name' => $file->filename));
  1509. if (count($errors) > 1) {
  1510. $message .= theme('item_list', array('items' => $errors));
  1511. }
  1512. else {
  1513. $message .= ' ' . array_pop($errors);
  1514. }
  1515. form_set_error($form_field_name, $message);
  1516. return FALSE;
  1517. }
  1518. // Move uploaded files from PHP's upload_tmp_dir to Drupal's temporary
  1519. // directory. This overcomes open_basedir restrictions for future file
  1520. // operations.
  1521. $file->uri = $file->destination;
  1522. if (!drupal_move_uploaded_file($_FILES['files']['tmp_name'][$form_field_name], $file->uri)) {
  1523. form_set_error($form_field_name, t('File upload error. Could not move uploaded file.'));
  1524. watchdog('file', 'Upload error. Could not move uploaded file %file to destination %destination.', array('%file' => $file->filename, '%destination' => $file->uri));
  1525. return FALSE;
  1526. }
  1527. // Set the permissions on the new file.
  1528. drupal_chmod($file->uri);
  1529. // If we are replacing an existing file re-use its database record.
  1530. if ($replace == FILE_EXISTS_REPLACE) {
  1531. $existing_files = file_load_multiple(array(), array('uri' => $file->uri));
  1532. if (count($existing_files)) {
  1533. $existing = reset($existing_files);
  1534. $file->fid = $existing->fid;
  1535. }
  1536. }
  1537. // If we made it this far it's safe to record this file in the database.
  1538. if ($file = file_save($file)) {
  1539. // Track non-public files in the session if they were uploaded by an
  1540. // anonymous user. This allows modules such as the File module to only
  1541. // grant view access to the specific anonymous user who uploaded the file.
  1542. // See file_file_download().
  1543. // The 'file_public_schema' variable is used to allow other publicly
  1544. // accessible file schemes to be treated the same as the public:// scheme
  1545. // provided by Drupal core and to avoid adding unnecessary data to the
  1546. // session (and the resulting bypass of the page cache) in those cases. For
  1547. // security reasons, only schemes that are completely publicly accessible,
  1548. // with no download restrictions, should be added to this variable. See
  1549. // file_managed_file_value().
  1550. if (!$user->uid && !in_array($destination_scheme, variable_get('file_public_schema', array('public')))) {
  1551. $_SESSION['anonymous_allowed_file_ids'][$file->fid] = $file->fid;
  1552. }
  1553. // Add file to the cache.
  1554. $upload_cache[$form_field_name] = $file;
  1555. return $file;
  1556. }
  1557. return FALSE;
  1558. }
  1559. /**
  1560. * Moves an uploaded file to a new location.
  1561. *
  1562. * PHP's move_uploaded_file() does not properly support streams if safe_mode
  1563. * or open_basedir are enabled, so this function fills that gap.
  1564. *
  1565. * Compatibility: normal paths and stream wrappers.
  1566. *
  1567. * @param $filename
  1568. * The filename of the uploaded file.
  1569. * @param $uri
  1570. * A string containing the destination URI of the file.
  1571. *
  1572. * @return
  1573. * TRUE on success, or FALSE on failure.
  1574. *
  1575. * @see move_uploaded_file()
  1576. * @see http://drupal.org/node/515192
  1577. * @ingroup php_wrappers
  1578. */
  1579. function drupal_move_uploaded_file($filename, $uri) {
  1580. $result = @move_uploaded_file($filename, $uri);
  1581. // PHP's move_uploaded_file() does not properly support streams if safe_mode
  1582. // or open_basedir are enabled so if the move failed, try finding a real path
  1583. // and retry the move operation.
  1584. if (!$result) {
  1585. if ($realpath = drupal_realpath($uri)) {
  1586. $result = move_uploaded_file($filename, $realpath);
  1587. }
  1588. else {
  1589. $result = move_uploaded_file($filename, $uri);
  1590. }
  1591. }
  1592. return $result;
  1593. }
  1594. /**
  1595. * Checks that a file meets the criteria specified by the validators.
  1596. *
  1597. * After executing the validator callbacks specified hook_file_validate() will
  1598. * also be called to allow other modules to report errors about the file.
  1599. *
  1600. * @param $file
  1601. * A Drupal file object.
  1602. * @param $validators
  1603. * An optional, associative array of callback functions used to validate the
  1604. * file. The keys are function names and the values arrays of callback
  1605. * parameters which will be passed in after the file object. The
  1606. * functions should return an array of error messages; an empty array
  1607. * indicates that the file passed validation. The functions will be called in
  1608. * the order specified.
  1609. *
  1610. * @return
  1611. * An array containing validation error messages.
  1612. *
  1613. * @see hook_file_validate()
  1614. */
  1615. function file_validate(stdClass &$file, $validators = array()) {
  1616. // Call the validation functions specified by this function's caller.
  1617. $errors = array();
  1618. foreach ($validators as $function => $args) {
  1619. if (function_exists($function)) {
  1620. array_unshift($args, $file);
  1621. $errors = array_merge($errors, call_user_func_array($function, $args));
  1622. }
  1623. }
  1624. // Let other modules perform validation on the new file.
  1625. $errors = array_merge($errors, module_invoke_all('file_validate', $file));
  1626. // Ensure the file does not contain a malicious extension. At this point
  1627. // file_save_upload() will have munged the file so it does not contain a
  1628. // malicious extension. Contributed and custom code that calls this method
  1629. // needs to take similar steps if they need to permit files with malicious
  1630. // extensions to be uploaded.
  1631. if (empty($errors) && !variable_get('allow_insecure_uploads', 0) && preg_match('/\.(' . FILE_INSECURE_EXTENSIONS . ')(\.|$)/i', $file->filename)) {
  1632. $errors[] = t('For security reasons, your upload has been rejected.');
  1633. }
  1634. return $errors;
  1635. }
  1636. /**
  1637. * Checks for files with names longer than we can store in the database.
  1638. *
  1639. * @param $file
  1640. * A Drupal file object.
  1641. *
  1642. * @return
  1643. * An array. If the file name is too long, it will contain an error message.
  1644. */
  1645. function file_validate_name_length(stdClass $file) {
  1646. $errors = array();
  1647. if (empty($file->filename)) {
  1648. $errors[] = t("The file's name is empty. Please give a name to the file.");
  1649. }
  1650. if (strlen($file->filename) > 240) {
  1651. $errors[] = t("The file's name exceeds the 240 characters limit. Please rename the file and try again.");
  1652. }
  1653. return $errors;
  1654. }
  1655. /**
  1656. * Checks that the filename ends with an allowed extension.
  1657. *
  1658. * @param $file
  1659. * A Drupal file object.
  1660. * @param $extensions
  1661. * A string with a space separated list of allowed extensions.
  1662. *
  1663. * @return
  1664. * An array. If the file extension is not allowed, it will contain an error
  1665. * message.
  1666. *
  1667. * @see hook_file_validate()
  1668. */
  1669. function file_validate_extensions(stdClass $file, $extensions) {
  1670. $errors = array();
  1671. $regex = '/\.(' . preg_replace('/ +/', '|', preg_quote($extensions)) . ')$/i';
  1672. if (!preg_match($regex, $file->filename)) {
  1673. $errors[] = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => $extensions));
  1674. }
  1675. return $errors;
  1676. }
  1677. /**
  1678. * Checks that the file's size is below certain limits.
  1679. *
  1680. * @param $file
  1681. * A Drupal file object.
  1682. * @param $file_limit
  1683. * An integer specifying the maximum file size in bytes. Zero indicates that
  1684. * no limit should be enforced.
  1685. * @param $user_limit
  1686. * An integer specifying the maximum number of bytes the user is allowed.
  1687. * Zero indicates that no limit should be enforced.
  1688. *
  1689. * @return
  1690. * An array. If the file size exceeds limits, it will contain an error
  1691. * message.
  1692. *
  1693. * @see hook_file_validate()
  1694. */
  1695. function file_validate_size(stdClass $file, $file_limit = 0, $user_limit = 0) {
  1696. global $user;
  1697. $errors = array();
  1698. if ($file_limit && $file->filesize > $file_limit) {
  1699. $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($file->filesize), '%maxsize' => format_size($file_limit)));
  1700. }
  1701. // Save a query by only calling file_space_used() when a limit is provided.
  1702. if ($user_limit && (file_space_used($user->uid) + $file->filesize) > $user_limit) {
  1703. $errors[] = t('The file is %filesize which would exceed your disk quota of %quota.', array('%filesize' => format_size($file->filesize), '%quota' => format_size($user_limit)));
  1704. }
  1705. return $errors;
  1706. }
  1707. /**
  1708. * Checks that the file is recognized by image_get_info() as an image.
  1709. *
  1710. * @param $file
  1711. * A Drupal file object.
  1712. *
  1713. * @return
  1714. * An array. If the file is not an image, it will contain an error message.
  1715. *
  1716. * @see hook_file_validate()
  1717. */
  1718. function file_validate_is_image(stdClass $file) {
  1719. $errors = array();
  1720. $info = image_get_info($file->uri);
  1721. if (!$info || empty($info['extension'])) {
  1722. $errors[] = t('The image file is invalid or the image type is not allowed. Allowed types: %allowed_types', array('%allowed_types' => t('Only JPEG, PNG and GIF images are allowed.')));
  1723. }
  1724. return $errors;
  1725. }
  1726. /**
  1727. * Verifies that image dimensions are within the specified maximum and minimum.
  1728. *
  1729. * Non-image files will be ignored. If an image toolkit is available the image
  1730. * will be scaled to fit within the desired maximum dimensions.
  1731. *
  1732. * @param $file
  1733. * A Drupal file object. This function may resize the file affecting its
  1734. * size.
  1735. * @param $maximum_dimensions
  1736. * An optional string in the form WIDTHxHEIGHT e.g. '640x480' or '85x85'. If
  1737. * an image toolkit is installed the image will be resized down to these
  1738. * dimensions. A value of 0 indicates no restriction on size, so resizing
  1739. * will be attempted.
  1740. * @param $minimum_dimensions
  1741. * An optional string in the form WIDTHxHEIGHT. This will check that the
  1742. * image meets a minimum size. A value of 0 indicates no restriction.
  1743. *
  1744. * @return
  1745. * An array. If the file is an image and did not meet the requirements, it
  1746. * will contain an error message.
  1747. *
  1748. * @see hook_file_validate()
  1749. */
  1750. function file_validate_image_resolution(stdClass $file, $maximum_dimensions = 0, $minimum_dimensions = 0) {
  1751. $errors = array();
  1752. // Check first that the file is an image.
  1753. if ($info = image_get_info($file->uri)) {
  1754. if ($maximum_dimensions) {
  1755. // Check that it is smaller than the given dimensions.
  1756. list($width, $height) = explode('x', $maximum_dimensions);
  1757. if ($info['width'] > $width || $info['height'] > $height) {
  1758. // Try to resize the image to fit the dimensions.
  1759. if ($image = image_load($file->uri)) {
  1760. image_scale($image, $width, $height);
  1761. image_save($image);
  1762. // Update the image info since we have resized it.
  1763. $info = $image->info;
  1764. $file->filesize = $image->info['file_size'];
  1765. drupal_set_message(t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $maximum_dimensions)));
  1766. }
  1767. else {
  1768. $errors[] = t('The image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => $maximum_dimensions));
  1769. }
  1770. }
  1771. }
  1772. if ($minimum_dimensions) {
  1773. // Check that it is larger than the given dimensions.
  1774. list($width, $height) = explode('x', $minimum_dimensions);
  1775. if ($info['width'] < $width || $info['height'] < $height) {
  1776. $errors[] = t('The image is too small; the minimum dimensions are %dimensions pixels.', array('%dimensions' => $minimum_dimensions));
  1777. }
  1778. }
  1779. }
  1780. return $errors;
  1781. }
  1782. /**
  1783. * Saves a file to the specified destination and creates a database entry.
  1784. *
  1785. * @param $data
  1786. * A string containing the contents of the file.
  1787. * @param $destination
  1788. * A string containing the destination URI. This must be a stream wrapper URI.
  1789. * If no value is provided, a randomized name will be generated and the file
  1790. * will be saved using Drupal's default files scheme, usually "public://".
  1791. * @param $replace
  1792. * Replace behavior when the destination file already exists:
  1793. * - FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with
  1794. * the destination name exists then its database entry will be updated. If
  1795. * no database entry is found then a new one will be created.
  1796. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  1797. * unique.
  1798. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  1799. *
  1800. * @return
  1801. * A file object, or FALSE on error.
  1802. *
  1803. * @see file_unmanaged_save_data()
  1804. */
  1805. function file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  1806. global $user;
  1807. if (empty($destination)) {
  1808. $destination = file_default_scheme() . '://';
  1809. }
  1810. if (!file_valid_uri($destination)) {
  1811. watchdog('file', 'The data could not be saved because the destination %destination is invalid. This may be caused by improper use of file_save_data() or a missing stream wrapper.', array('%destination' => $destination));
  1812. drupal_set_message(t('The data could not be saved, because the destination is invalid. More information is available in the system log.'), 'error');
  1813. return FALSE;
  1814. }
  1815. if ($uri = file_unmanaged_save_data($data, $destination, $replace)) {
  1816. // Create a file object.
  1817. $file = new stdClass();
  1818. $file->fid = NULL;
  1819. $file->uri = $uri;
  1820. $file->filename = drupal_basename($uri);
  1821. $file->filemime = file_get_mimetype($file->uri);
  1822. $file->uid = $user->uid;
  1823. $file->status = FILE_STATUS_PERMANENT;
  1824. // If we are replacing an existing file re-use its database record.
  1825. if ($replace == FILE_EXISTS_REPLACE) {
  1826. $existing_files = file_load_multiple(array(), array('uri' => $uri));
  1827. if (count($existing_files)) {
  1828. $existing = reset($existing_files);
  1829. $file->fid = $existing->fid;
  1830. $file->filename = $existing->filename;
  1831. }
  1832. }
  1833. // If we are renaming around an existing file (rather than a directory),
  1834. // use its basename for the filename.
  1835. elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
  1836. $file->filename = drupal_basename($destination);
  1837. }
  1838. return file_save($file);
  1839. }
  1840. return FALSE;
  1841. }
  1842. /**
  1843. * Saves a string to the specified destination without invoking file API.
  1844. *
  1845. * This function is identical to file_save_data() except the file will not be
  1846. * saved to the {file_managed} table and none of the file_* hooks will be
  1847. * called.
  1848. *
  1849. * @param $data
  1850. * A string containing the contents of the file.
  1851. * @param $destination
  1852. * A string containing the destination location. This must be a stream wrapper
  1853. * URI. If no value is provided, a randomized name will be generated and the
  1854. * file will be saved using Drupal's default files scheme, usually
  1855. * "public://".
  1856. * @param $replace
  1857. * Replace behavior when the destination file already exists:
  1858. * - FILE_EXISTS_REPLACE - Replace the existing file.
  1859. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  1860. * unique.
  1861. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  1862. *
  1863. * @return
  1864. * A string with the path of the resulting file, or FALSE on error.
  1865. *
  1866. * @see file_save_data()
  1867. */
  1868. function file_unmanaged_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  1869. // Write the data to a temporary file.
  1870. $temp_name = drupal_tempnam('temporary://', 'file');
  1871. if (file_put_contents($temp_name, $data) === FALSE) {
  1872. drupal_set_message(t('The file could not be created.'), 'error');
  1873. return FALSE;
  1874. }
  1875. // Move the file to its final destination.
  1876. return file_unmanaged_move($temp_name, $destination, $replace);
  1877. }
  1878. /**
  1879. * Transfers a file to the client using HTTP.
  1880. *
  1881. * Pipes a file through Drupal to the client.
  1882. *
  1883. * @param $uri
  1884. * String specifying the file URI to transfer.
  1885. * @param $headers
  1886. * An array of HTTP headers to send along with file.
  1887. */
  1888. function file_transfer($uri, $headers) {
  1889. if (ob_get_level()) {
  1890. ob_end_clean();
  1891. }
  1892. foreach ($headers as $name => $value) {
  1893. drupal_add_http_header($name, $value);
  1894. }
  1895. drupal_send_headers();
  1896. $scheme = file_uri_scheme($uri);
  1897. // Transfer file in 1024 byte chunks to save memory usage.
  1898. if ($scheme && file_stream_wrapper_valid_scheme($scheme) && $fd = fopen($uri, 'rb')) {
  1899. while (!feof($fd)) {
  1900. print fread($fd, 1024);
  1901. }
  1902. fclose($fd);
  1903. }
  1904. else {
  1905. drupal_not_found();
  1906. }
  1907. drupal_exit();
  1908. }
  1909. /**
  1910. * Menu handler for private file transfers.
  1911. *
  1912. * Call modules that implement hook_file_download() to find out if a file is
  1913. * accessible and what headers it should be transferred with. If one or more
  1914. * modules returned headers the download will start with the returned headers.
  1915. * If a module returns -1 drupal_access_denied() will be returned. If the file
  1916. * exists but no modules responded drupal_access_denied() will be returned.
  1917. * If the file does not exist drupal_not_found() will be returned.
  1918. *
  1919. * @see system_menu()
  1920. */
  1921. function file_download() {
  1922. // Merge remainder of arguments from GET['q'], into relative file path.
  1923. $args = func_get_args();
  1924. $scheme = array_shift($args);
  1925. $target = implode('/', $args);
  1926. $uri = $scheme . '://' . $target;
  1927. $uri = file_uri_normalize_dot_segments($uri);
  1928. if (file_stream_wrapper_valid_scheme($scheme) && is_file($uri)) {
  1929. $headers = file_download_headers($uri);
  1930. if (count($headers)) {
  1931. file_transfer($uri, $headers);
  1932. }
  1933. drupal_access_denied();
  1934. }
  1935. else {
  1936. drupal_not_found();
  1937. }
  1938. drupal_exit();
  1939. }
  1940. /**
  1941. * Retrieves headers for a private file download.
  1942. *
  1943. * Calls all module implementations of hook_file_download() to retrieve headers
  1944. * for files by the module that originally provided the file. The presence of
  1945. * returned headers indicates the current user has access to the file.
  1946. *
  1947. * @param $uri
  1948. * The URI for the file whose headers should be retrieved.
  1949. *
  1950. * @return
  1951. * If access is allowed, headers for the file, suitable for passing to
  1952. * file_transfer(). If access is not allowed, an empty array will be returned.
  1953. *
  1954. * @see file_transfer()
  1955. * @see file_download_access()
  1956. * @see hook_file_download()
  1957. */
  1958. function file_download_headers($uri) {
  1959. // Let other modules provide headers and control access to the file.
  1960. // module_invoke_all() uses array_merge_recursive() which merges header
  1961. // values into a new array. To avoid that and allow modules to override
  1962. // headers instead, use array_merge() to merge the returned arrays.
  1963. $headers = array();
  1964. foreach (module_implements('file_download') as $module) {
  1965. $function = $module . '_file_download';
  1966. $result = $function($uri);
  1967. if ($result == -1) {
  1968. // Throw away the headers received so far.
  1969. $headers = array();
  1970. break;
  1971. }
  1972. if (isset($result) && is_array($result)) {
  1973. $headers = array_merge($headers, $result);
  1974. }
  1975. }
  1976. return $headers;
  1977. }
  1978. /**
  1979. * Checks that the current user has access to a particular file.
  1980. *
  1981. * The return value of this function hinges on the return value from
  1982. * file_download_headers(), which is the function responsible for collecting
  1983. * access information through hook_file_download().
  1984. *
  1985. * If immediately transferring the file to the browser and the headers will
  1986. * need to be retrieved, the return value of file_download_headers() should be
  1987. * used to determine access directly, so that access checks will not be run
  1988. * twice.
  1989. *
  1990. * @param $uri
  1991. * The URI for the file whose access should be retrieved.
  1992. *
  1993. * @return
  1994. * Boolean TRUE if access is allowed. FALSE if access is not allowed.
  1995. *
  1996. * @see file_download_headers()
  1997. * @see hook_file_download()
  1998. */
  1999. function file_download_access($uri) {
  2000. return count(file_download_headers($uri)) > 0;
  2001. }
  2002. /**
  2003. * Finds all files that match a given mask in a given directory.
  2004. *
  2005. * Directories and files beginning with a period are excluded; this
  2006. * prevents hidden files and directories (such as SVN working directories)
  2007. * from being scanned.
  2008. *
  2009. * @param $dir
  2010. * The base directory or URI to scan, without trailing slash.
  2011. * @param $mask
  2012. * The preg_match() regular expression of the files to find.
  2013. * @param $options
  2014. * An associative array of additional options, with the following elements:
  2015. * - 'nomask': The preg_match() regular expression of the files to ignore.
  2016. * Defaults to '/(\.\.?|CVS)$/'.
  2017. * - 'callback': The callback function to call for each match. There is no
  2018. * default callback.
  2019. * - 'recurse': When TRUE, the directory scan will recurse the entire tree
  2020. * starting at the provided directory. Defaults to TRUE.
  2021. * - 'key': The key to be used for the returned associative array of files.
  2022. * Possible values are 'uri', for the file's URI; 'filename', for the
  2023. * basename of the file; and 'name' for the name of the file without the
  2024. * extension. Defaults to 'uri'.
  2025. * - 'min_depth': Minimum depth of directories to return files from. Defaults
  2026. * to 0.
  2027. * @param $depth
  2028. * Current depth of recursion. This parameter is only used internally and
  2029. * should not be passed in.
  2030. *
  2031. * @return
  2032. * An associative array (keyed on the chosen key) of objects with 'uri',
  2033. * 'filename', and 'name' members corresponding to the matching files.
  2034. */
  2035. function file_scan_directory($dir, $mask, $options = array(), $depth = 0) {
  2036. // Default nomask option.
  2037. $nomask = '/(\.\.?|CVS)$/';
  2038. // Overrides the $nomask variable accordingly if $options['nomask'] is set.
  2039. //
  2040. // Allow directories specified in settings.php to be ignored. You can use this
  2041. // to not check for files in common special-purpose directories. For example,
  2042. // node_modules and bower_components. Ignoring irrelevant directories is a
  2043. // performance boost.
  2044. if (!isset($options['nomask'])) {
  2045. $ignore_directories = variable_get(
  2046. 'file_scan_ignore_directories',
  2047. array()
  2048. );
  2049. foreach ($ignore_directories as $index => $ignore_directory) {
  2050. $ignore_directories[$index] = preg_quote($ignore_directory, '/');
  2051. }
  2052. if (!empty($ignore_directories)) {
  2053. $nomask = '/^(\.\.?)|CVS|' . implode('|', $ignore_directories) . '$/';
  2054. }
  2055. }
  2056. // Merge in defaults.
  2057. $options += array(
  2058. 'nomask' => $nomask,
  2059. 'callback' => 0,
  2060. 'recurse' => TRUE,
  2061. 'key' => 'uri',
  2062. 'min_depth' => 0,
  2063. );
  2064. $options['key'] = in_array($options['key'], array('uri', 'filename', 'name')) ? $options['key'] : 'uri';
  2065. $files = array();
  2066. if (is_dir($dir) && $handle = opendir($dir)) {
  2067. while (FALSE !== ($filename = readdir($handle))) {
  2068. if (!preg_match($options['nomask'], $filename) && $filename[0] != '.') {
  2069. $uri = "$dir/$filename";
  2070. $uri = file_stream_wrapper_uri_normalize($uri);
  2071. if (is_dir($uri) && $options['recurse']) {
  2072. // Give priority to files in this folder by merging them in after any subdirectory files.
  2073. $files = array_merge(file_scan_directory($uri, $mask, $options, $depth + 1), $files);
  2074. }
  2075. elseif ($depth >= $options['min_depth'] && preg_match($mask, $filename)) {
  2076. // Always use this match over anything already set in $files with the
  2077. // same $$options['key'].
  2078. $file = new stdClass();
  2079. $file->uri = $uri;
  2080. $file->filename = $filename;
  2081. $file->name = pathinfo($filename, PATHINFO_FILENAME);
  2082. $key = $options['key'];
  2083. $files[$file->$key] = $file;
  2084. if ($options['callback']) {
  2085. $options['callback']($uri);
  2086. }
  2087. }
  2088. }
  2089. }
  2090. closedir($handle);
  2091. }
  2092. return $files;
  2093. }
  2094. /**
  2095. * Determines the maximum file upload size by querying the PHP settings.
  2096. *
  2097. * @return
  2098. * A file size limit in bytes based on the PHP upload_max_filesize and
  2099. * post_max_size
  2100. */
  2101. function file_upload_max_size() {
  2102. static $max_size = -1;
  2103. if ($max_size < 0) {
  2104. // Start with post_max_size.
  2105. $max_size = parse_size(ini_get('post_max_size'));
  2106. // If upload_max_size is less, then reduce. Except if upload_max_size is
  2107. // zero, which indicates no limit.
  2108. $upload_max = parse_size(ini_get('upload_max_filesize'));
  2109. if ($upload_max > 0 && $upload_max < $max_size) {
  2110. $max_size = $upload_max;
  2111. }
  2112. }
  2113. return $max_size;
  2114. }
  2115. /**
  2116. * Determines an Internet Media Type or MIME type from a filename.
  2117. *
  2118. * @param $uri
  2119. * A string containing the URI, path, or filename.
  2120. * @param $mapping
  2121. * An optional map of extensions to their mimetypes, in the form:
  2122. * - 'mimetypes': a list of mimetypes, keyed by an identifier,
  2123. * - 'extensions': the mapping itself, an associative array in which
  2124. * the key is the extension (lowercase) and the value is the mimetype
  2125. * identifier. If $mapping is NULL file_mimetype_mapping() is called.
  2126. *
  2127. * @return
  2128. * The internet media type registered for the extension or
  2129. * application/octet-stream for unknown extensions.
  2130. *
  2131. * @see file_default_mimetype_mapping()
  2132. */
  2133. function file_get_mimetype($uri, $mapping = NULL) {
  2134. if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
  2135. return $wrapper->getMimeType($uri, $mapping);
  2136. }
  2137. else {
  2138. // getMimeType() is not implementation specific, so we can directly
  2139. // call it without an instance.
  2140. return DrupalLocalStreamWrapper::getMimeType($uri, $mapping);
  2141. }
  2142. }
  2143. /**
  2144. * Sets the permissions on a file or directory.
  2145. *
  2146. * This function will use the 'file_chmod_directory' and 'file_chmod_file'
  2147. * variables for the default modes for directories and uploaded/generated
  2148. * files. By default these will give everyone read access so that users
  2149. * accessing the files with a user account without the webserver group (e.g.
  2150. * via FTP) can read these files, and give group write permissions so webserver
  2151. * group members (e.g. a vhost account) can alter files uploaded and owned by
  2152. * the webserver.
  2153. *
  2154. * PHP's chmod does not support stream wrappers so we use our wrapper
  2155. * implementation which interfaces with chmod() by default. Contrib wrappers
  2156. * may override this behavior in their implementations as needed.
  2157. *
  2158. * @param $uri
  2159. * A string containing a URI file, or directory path.
  2160. * @param $mode
  2161. * Integer value for the permissions. Consult PHP chmod() documentation for
  2162. * more information.
  2163. *
  2164. * @return
  2165. * TRUE for success, FALSE in the event of an error.
  2166. *
  2167. * @ingroup php_wrappers
  2168. */
  2169. function drupal_chmod($uri, $mode = NULL) {
  2170. if (!isset($mode)) {
  2171. if (is_dir($uri)) {
  2172. $mode = variable_get('file_chmod_directory', 0775);
  2173. }
  2174. else {
  2175. $mode = variable_get('file_chmod_file', 0664);
  2176. }
  2177. }
  2178. // If this URI is a stream, pass it off to the appropriate stream wrapper.
  2179. // Otherwise, attempt PHP's chmod. This allows use of drupal_chmod even
  2180. // for unmanaged files outside of the stream wrapper interface.
  2181. if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
  2182. if ($wrapper->chmod($mode)) {
  2183. return TRUE;
  2184. }
  2185. }
  2186. else {
  2187. if (@chmod($uri, $mode)) {
  2188. return TRUE;
  2189. }
  2190. }
  2191. watchdog('file', 'The file permissions could not be set on %uri.', array('%uri' => $uri), WATCHDOG_ERROR);
  2192. return FALSE;
  2193. }
  2194. /**
  2195. * Deletes a file.
  2196. *
  2197. * PHP's unlink() is broken on Windows, as it can fail to remove a file
  2198. * when it has a read-only flag set.
  2199. *
  2200. * @param $uri
  2201. * A URI or pathname.
  2202. * @param $context
  2203. * Refer to http://php.net/manual/ref.stream.php
  2204. *
  2205. * @return
  2206. * Boolean TRUE on success, or FALSE on failure.
  2207. *
  2208. * @see unlink()
  2209. * @ingroup php_wrappers
  2210. */
  2211. function drupal_unlink($uri, $context = NULL) {
  2212. $scheme = file_uri_scheme($uri);
  2213. if ((!$scheme || !file_stream_wrapper_valid_scheme($scheme)) && (substr(PHP_OS, 0, 3) == 'WIN')) {
  2214. chmod($uri, 0600);
  2215. }
  2216. if ($context) {
  2217. return unlink($uri, $context);
  2218. }
  2219. else {
  2220. return unlink($uri);
  2221. }
  2222. }
  2223. /**
  2224. * Resolves the absolute filepath of a local URI or filepath.
  2225. *
  2226. * The use of drupal_realpath() is discouraged, because it does not work for
  2227. * remote URIs. Except in rare cases, URIs should not be manually resolved.
  2228. *
  2229. * Only use this function if you know that the stream wrapper in the URI uses
  2230. * the local file system, and you need to pass an absolute path to a function
  2231. * that is incompatible with stream URIs.
  2232. *
  2233. * @param string $uri
  2234. * A stream wrapper URI or a filepath, possibly including one or more symbolic
  2235. * links.
  2236. *
  2237. * @return string|false
  2238. * The absolute local filepath (with no symbolic links), or FALSE on failure.
  2239. *
  2240. * @see DrupalStreamWrapperInterface::realpath()
  2241. * @see http://php.net/manual/function.realpath.php
  2242. * @ingroup php_wrappers
  2243. */
  2244. function drupal_realpath($uri) {
  2245. // If this URI is a stream, pass it off to the appropriate stream wrapper.
  2246. // Otherwise, attempt PHP's realpath. This allows use of drupal_realpath even
  2247. // for unmanaged files outside of the stream wrapper interface.
  2248. if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
  2249. return $wrapper->realpath();
  2250. }
  2251. // Check that the URI has a value. There is a bug in PHP 5.2 on *BSD systems
  2252. // that makes realpath not return FALSE as expected when passing an empty
  2253. // variable.
  2254. // @todo Remove when Drupal drops support for PHP 5.2.
  2255. elseif (!empty($uri)) {
  2256. return realpath($uri);
  2257. }
  2258. return FALSE;
  2259. }
  2260. /**
  2261. * Gets the name of the directory from a given path.
  2262. *
  2263. * PHP's dirname() does not properly pass streams, so this function fills
  2264. * that gap. It is backwards compatible with normal paths and will use
  2265. * PHP's dirname() as a fallback.
  2266. *
  2267. * Compatibility: normal paths and stream wrappers.
  2268. *
  2269. * @param $uri
  2270. * A URI or path.
  2271. *
  2272. * @return
  2273. * A string containing the directory name.
  2274. *
  2275. * @see dirname()
  2276. * @see http://drupal.org/node/515192
  2277. * @ingroup php_wrappers
  2278. */
  2279. function drupal_dirname($uri) {
  2280. $scheme = file_uri_scheme($uri);
  2281. if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
  2282. return file_stream_wrapper_get_instance_by_scheme($scheme)->dirname($uri);
  2283. }
  2284. else {
  2285. return dirname($uri);
  2286. }
  2287. }
  2288. /**
  2289. * Gets the filename from a given path.
  2290. *
  2291. * PHP's basename() does not properly support streams or filenames beginning
  2292. * with a non-US-ASCII character.
  2293. *
  2294. * @see http://bugs.php.net/bug.php?id=37738
  2295. * @see basename()
  2296. *
  2297. * @ingroup php_wrappers
  2298. */
  2299. function drupal_basename($uri, $suffix = NULL) {
  2300. $separators = '/';
  2301. if (DIRECTORY_SEPARATOR != '/') {
  2302. // For Windows OS add special separator.
  2303. $separators .= DIRECTORY_SEPARATOR;
  2304. }
  2305. // Remove right-most slashes when $uri points to directory.
  2306. $uri = rtrim($uri, $separators);
  2307. // Returns the trailing part of the $uri starting after one of the directory
  2308. // separators.
  2309. $filename = preg_match('@[^' . preg_quote($separators, '@') . ']+$@', $uri, $matches) ? $matches[0] : '';
  2310. // Cuts off a suffix from the filename.
  2311. if ($suffix) {
  2312. $filename = preg_replace('@' . preg_quote($suffix, '@') . '$@', '', $filename);
  2313. }
  2314. return $filename;
  2315. }
  2316. /**
  2317. * Creates a directory, optionally creating missing components in the path to
  2318. * the directory.
  2319. *
  2320. * When PHP's mkdir() creates a directory, the requested mode is affected by the
  2321. * process's umask. This function overrides the umask and sets the mode
  2322. * explicitly for all directory components created.
  2323. *
  2324. * @param $uri
  2325. * A URI or pathname.
  2326. * @param $mode
  2327. * Mode given to created directories. Defaults to the directory mode
  2328. * configured in the Drupal installation. It must have a leading zero.
  2329. * @param $recursive
  2330. * Create directories recursively, defaults to FALSE. Cannot work with a mode
  2331. * which denies writing or execution to the owner of the process.
  2332. * @param $context
  2333. * Refer to http://php.net/manual/ref.stream.php
  2334. *
  2335. * @return
  2336. * Boolean TRUE on success, or FALSE on failure.
  2337. *
  2338. * @see mkdir()
  2339. * @see http://drupal.org/node/515192
  2340. * @ingroup php_wrappers
  2341. */
  2342. function drupal_mkdir($uri, $mode = NULL, $recursive = FALSE, $context = NULL) {
  2343. if (!isset($mode)) {
  2344. $mode = variable_get('file_chmod_directory', 0775);
  2345. }
  2346. // If the URI has a scheme, don't override the umask - schemes can handle this
  2347. // issue in their own implementation.
  2348. if (file_uri_scheme($uri)) {
  2349. return _drupal_mkdir_call($uri, $mode, $recursive, $context);
  2350. }
  2351. // If recursive, create each missing component of the parent directory
  2352. // individually and set the mode explicitly to override the umask.
  2353. if ($recursive) {
  2354. // Ensure the path is using DIRECTORY_SEPARATOR, and trim off any trailing
  2355. // slashes because they can throw off the loop when creating the parent
  2356. // directories.
  2357. $uri = rtrim(str_replace('/', DIRECTORY_SEPARATOR, $uri), DIRECTORY_SEPARATOR);
  2358. // Determine the components of the path.
  2359. $components = explode(DIRECTORY_SEPARATOR, $uri);
  2360. // If the filepath is absolute the first component will be empty as there
  2361. // will be nothing before the first slash.
  2362. if ($components[0] == '') {
  2363. $recursive_path = DIRECTORY_SEPARATOR;
  2364. // Get rid of the empty first component.
  2365. array_shift($components);
  2366. }
  2367. else {
  2368. $recursive_path = '';
  2369. }
  2370. // Don't handle the top-level directory in this loop.
  2371. array_pop($components);
  2372. // Create each component if necessary.
  2373. foreach ($components as $component) {
  2374. $recursive_path .= $component;
  2375. if (!file_exists($recursive_path)) {
  2376. $success = _drupal_mkdir_call($recursive_path, $mode, FALSE, $context);
  2377. // If the operation failed, check again if the directory was created
  2378. // by another process/server, only report a failure if not.
  2379. if (!$success && !file_exists($recursive_path)) {
  2380. return FALSE;
  2381. }
  2382. // Not necessary to use self::chmod() as there is no scheme.
  2383. if (!chmod($recursive_path, $mode)) {
  2384. return FALSE;
  2385. }
  2386. }
  2387. $recursive_path .= DIRECTORY_SEPARATOR;
  2388. }
  2389. }
  2390. // Do not check if the top-level directory already exists, as this condition
  2391. // must cause this function to fail.
  2392. if (!_drupal_mkdir_call($uri, $mode, FALSE, $context)) {
  2393. return FALSE;
  2394. }
  2395. // Not necessary to use drupal_chmod() as there is no scheme.
  2396. return chmod($uri, $mode);
  2397. }
  2398. /**
  2399. * Helper function. Ensures we don't pass a NULL as a context resource to
  2400. * mkdir().
  2401. *
  2402. * @see drupal_mkdir()
  2403. */
  2404. function _drupal_mkdir_call($uri, $mode, $recursive, $context) {
  2405. if (is_null($context)) {
  2406. return mkdir($uri, $mode, $recursive);
  2407. }
  2408. else {
  2409. return mkdir($uri, $mode, $recursive, $context);
  2410. }
  2411. }
  2412. /**
  2413. * Removes a directory.
  2414. *
  2415. * PHP's rmdir() is broken on Windows, as it can fail to remove a directory
  2416. * when it has a read-only flag set.
  2417. *
  2418. * @param $uri
  2419. * A URI or pathname.
  2420. * @param $context
  2421. * Refer to http://php.net/manual/ref.stream.php
  2422. *
  2423. * @return
  2424. * Boolean TRUE on success, or FALSE on failure.
  2425. *
  2426. * @see rmdir()
  2427. * @ingroup php_wrappers
  2428. */
  2429. function drupal_rmdir($uri, $context = NULL) {
  2430. $scheme = file_uri_scheme($uri);
  2431. if ((!$scheme || !file_stream_wrapper_valid_scheme($scheme)) && (substr(PHP_OS, 0, 3) == 'WIN')) {
  2432. chmod($uri, 0700);
  2433. }
  2434. if ($context) {
  2435. return rmdir($uri, $context);
  2436. }
  2437. else {
  2438. return rmdir($uri);
  2439. }
  2440. }
  2441. /**
  2442. * Creates a file with a unique filename in the specified directory.
  2443. *
  2444. * PHP's tempnam() does not return a URI like we want. This function
  2445. * will return a URI if given a URI, or it will return a filepath if
  2446. * given a filepath.
  2447. *
  2448. * Compatibility: normal paths and stream wrappers.
  2449. *
  2450. * @param $directory
  2451. * The directory where the temporary filename will be created.
  2452. * @param $prefix
  2453. * The prefix of the generated temporary filename.
  2454. * Note: Windows uses only the first three characters of prefix.
  2455. *
  2456. * @return
  2457. * The new temporary filename, or FALSE on failure.
  2458. *
  2459. * @see tempnam()
  2460. * @see http://drupal.org/node/515192
  2461. * @ingroup php_wrappers
  2462. */
  2463. function drupal_tempnam($directory, $prefix) {
  2464. $scheme = file_uri_scheme($directory);
  2465. if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
  2466. $wrapper = file_stream_wrapper_get_instance_by_scheme($scheme);
  2467. if ($filename = tempnam($wrapper->getDirectoryPath(), $prefix)) {
  2468. return $scheme . '://' . drupal_basename($filename);
  2469. }
  2470. else {
  2471. return FALSE;
  2472. }
  2473. }
  2474. else {
  2475. // Handle as a normal tempnam() call.
  2476. return tempnam($directory, $prefix);
  2477. }
  2478. }
  2479. /**
  2480. * Gets the path of system-appropriate temporary directory.
  2481. */
  2482. function file_directory_temp() {
  2483. $temporary_directory = variable_get('file_temporary_path', NULL);
  2484. if (empty($temporary_directory)) {
  2485. $directories = array();
  2486. // Has PHP been set with an upload_tmp_dir?
  2487. if (ini_get('upload_tmp_dir')) {
  2488. $directories[] = ini_get('upload_tmp_dir');
  2489. }
  2490. // Operating system specific dirs.
  2491. if (substr(PHP_OS, 0, 3) == 'WIN') {
  2492. $directories[] = 'c:\\windows\\temp';
  2493. $directories[] = 'c:\\winnt\\temp';
  2494. }
  2495. else {
  2496. $directories[] = '/tmp';
  2497. }
  2498. // PHP may be able to find an alternative tmp directory.
  2499. // This function exists in PHP 5 >= 5.2.1, but Drupal
  2500. // requires PHP 5 >= 5.2.0, so we check for it.
  2501. if (function_exists('sys_get_temp_dir')) {
  2502. $directories[] = sys_get_temp_dir();
  2503. }
  2504. foreach ($directories as $directory) {
  2505. if (is_dir($directory) && is_writable($directory)) {
  2506. $temporary_directory = $directory;
  2507. break;
  2508. }
  2509. }
  2510. if (empty($temporary_directory)) {
  2511. // If no directory has been found default to 'files/tmp'.
  2512. $temporary_directory = variable_get('file_public_path', conf_path() . '/files') . '/tmp';
  2513. // Windows accepts paths with either slash (/) or backslash (\), but will
  2514. // not accept a path which contains both a slash and a backslash. Since
  2515. // the 'file_public_path' variable may have either format, we sanitize
  2516. // everything to use slash which is supported on all platforms.
  2517. $temporary_directory = str_replace('\\', '/', $temporary_directory);
  2518. }
  2519. // Save the path of the discovered directory.
  2520. variable_set('file_temporary_path', $temporary_directory);
  2521. }
  2522. return $temporary_directory;
  2523. }
  2524. /**
  2525. * Examines a file object and returns appropriate content headers for download.
  2526. *
  2527. * @param $file
  2528. * A file object.
  2529. *
  2530. * @return
  2531. * An associative array of headers, as expected by file_transfer().
  2532. */
  2533. function file_get_content_headers($file) {
  2534. $type = mime_header_encode($file->filemime);
  2535. return array(
  2536. 'Content-Type' => $type,
  2537. 'Content-Length' => $file->filesize,
  2538. 'Cache-Control' => 'private',
  2539. );
  2540. }
  2541. /**
  2542. * Normalize dot segments in a URI.
  2543. *
  2544. * @param $uri
  2545. * A stream, referenced as "scheme://target".
  2546. *
  2547. * @return string
  2548. * The URI with dot segments removed and slashes as directory separator.
  2549. */
  2550. function file_uri_normalize_dot_segments($uri) {
  2551. $scheme = file_uri_scheme($uri);
  2552. if (file_stream_wrapper_valid_scheme($scheme)) {
  2553. $target = file_uri_target($uri);
  2554. if ($target !== FALSE) {
  2555. if (!in_array($scheme, variable_get('file_sa_core_2023_005_schemes', array()))) {
  2556. $class = file_stream_wrapper_get_class($scheme);
  2557. $is_local = is_subclass_of($class, 'DrupalLocalStreamWrapper');
  2558. if ($is_local) {
  2559. $target = str_replace(DIRECTORY_SEPARATOR, '/', $target);
  2560. }
  2561. $parts = explode('/', $target);
  2562. $normalized_parts = array();
  2563. while ($parts) {
  2564. $part = array_shift($parts);
  2565. if ($part === '' || $part === '.') {
  2566. continue;
  2567. }
  2568. elseif ($part === '..' && $is_local && $normalized_parts === array()) {
  2569. $normalized_parts[] = $part;
  2570. break;
  2571. }
  2572. elseif ($part === '..') {
  2573. array_pop($normalized_parts);
  2574. }
  2575. else {
  2576. $normalized_parts[] = $part;
  2577. }
  2578. }
  2579. $target = implode('/', array_merge($normalized_parts, $parts));
  2580. }
  2581. $uri = $scheme . '://' . $target;
  2582. }
  2583. }
  2584. return $uri;
  2585. }
  2586. /**
  2587. * @} End of "defgroup file".
  2588. */