file.inc 86 KB

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