file.inc 89 KB

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