file.inc 90 KB

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