file.inc 89 KB

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