file.inc

  1. drupal
    1. 4.6 includes/file.inc
    2. 4.7 includes/file.inc
    3. 5 includes/file.inc
    4. 6 includes/file.inc
    5. 7 includes/file.inc
    6. 8 core/includes/file.inc

API for handling file uploads and server file management.

Functions & methods

NameDescription
drupal_basenameGets the filename from a given path.
drupal_chmodSets the permissions on a file or directory.
drupal_dirnameGets the name of the directory from a given path.
drupal_mkdirCreates a directory using Drupal's default mode.
drupal_move_uploaded_fileMoves an uploaded file to a new location.
drupal_realpathReturns the absolute local filesystem path of a stream URI.
drupal_rmdirRemoves a directory.
drupal_tempnamCreates a file with a unique filename in the specified directory.
drupal_unlinkDeletes a file.
file_build_uriConstructs a URI to Drupal's default files location given a relative path.
file_copyCopies a file to a new location and adds a file record to the database.
file_create_filenameCreates a full file path from a directory and filename.
file_create_urlCreates a web-accessible URL for a stream to an external or local file.
file_default_schemeGets the default file stream implementation.
file_deleteDeletes a file and its database record.
file_destinationDetermines the destination path for a file.
file_directory_tempGets the path of system-appropriate temporary directory.
file_downloadPage callback: Handles private file transfers.
file_ensure_htaccessCreates a .htaccess file in each Drupal files directory if it is missing.
file_get_content_headersExamines a file object and returns appropriate content headers for download.
file_get_mimetypeDetermines an Internet Media Type or MIME type from a filename.
file_get_stream_wrappersProvides Drupal stream wrapper registry.
file_loadLoads a single file object from the database.
file_load_multipleLoads file objects from the database.
file_moveMoves a file to a new location and update the file's database entry.
file_munge_filenameModifies a filename as needed for security purposes.
file_prepare_directoryChecks that the directory exists and is writable.
file_saveSaves a file object to the database.
file_save_dataSaves a file to the specified destination and creates a database entry.
file_save_htaccessCreates a .htaccess file in the given directory.
file_save_uploadSaves a file upload to a new location.
file_scan_directoryFinds all files that match a given mask in a given directory.
file_space_usedDetermines total disk space used by a single user or the whole filesystem.
file_stream_wrapper_get_classReturns the stream wrapper class name for a given scheme.
file_stream_wrapper_get_instance_by_schemeReturns a reference to the stream wrapper class responsible for a scheme.
file_stream_wrapper_get_instance_by_uriReturns a reference to the stream wrapper class responsible for a given URI.
file_stream_wrapper_uri_normalizeNormalizes a URI by making it syntactically correct.
file_stream_wrapper_valid_schemeChecks that the scheme of a stream URI is valid.
file_transferTransfers a file to the client using HTTP.
file_unmanaged_copyCopies a file to a new location without invoking the file API.
file_unmanaged_deleteDeletes a file without database changes or hook invocations.
file_unmanaged_delete_recursiveDeletes all files and directories in the specified filepath recursively.
file_unmanaged_moveMoves a file to a new location without database changes or hook invocation.
file_unmanaged_save_dataSaves a file to the specified destination without invoking file API.
file_unmunge_filenameUndoes the effect of file_munge_filename().
file_upload_max_sizeDetermines the maximum file upload size by querying the PHP settings.
file_uri_schemeReturns the scheme of a URI (e.g. a stream).
file_uri_targetReturns the part of a URI after the schema.
file_usage_addRecords that a module is using a file.
file_usage_deleteRemoves a record to indicate that a module is no longer using a file.
file_usage_listDetermines where a file is used.
file_validateChecks that a file meets the criteria specified by the validators.
file_validate_extensionsChecks that the filename ends with an allowed extension.
file_validate_image_resolutionVerifies that image dimensions are within the specified maximum and minimum.
file_validate_is_imageChecks that the file is recognized by image_get_info() as an image.
file_validate_name_lengthChecks for files with names longer than can be stored in the database.
file_validate_sizeChecks that the file's size is below certain limits.
file_valid_uriDetermines whether the URI has a valid scheme for file API operations.

Constants

NameDescription
FILE_CREATE_DIRECTORYFlag used by file_prepare_directory() -- create directory if not present.
FILE_EXISTS_ERRORFlag for dealing with existing files: Do nothing and return FALSE.
FILE_EXISTS_RENAMEFlag for dealing with existing files: Appends number until name is unique.
FILE_EXISTS_REPLACEFlag for dealing with existing files: Replace the existing file.
FILE_MODIFY_PERMISSIONSFlag used by file_prepare_directory() -- file permissions may be changed.
FILE_STATUS_PERMANENTIndicates that the file is permanent and should not be deleted.
STREAM_WRAPPERS_ALLStream wrapper bit flag -- a filter that matches all wrappers.
STREAM_WRAPPERS_HIDDENStream wrapper type flag -- not visible in the UI or accessible via web, but readable and writable. E.g. the temporary directory for uploads.
STREAM_WRAPPERS_LOCALStream wrapper bit flag -- refers to a local file system location.
STREAM_WRAPPERS_LOCAL_HIDDENStream wrapper type flag -- hidden, readable and writeable using local files.
STREAM_WRAPPERS_LOCAL_NORMALStream wrapper type flag -- visible, readable and writeable using local files.
STREAM_WRAPPERS_NORMALStream wrapper type flag -- the default when 'type' is omitted from hook_stream_wrappers(). This does not include STREAM_WRAPPERS_LOCAL, because PHP grants a greater trust level to local files (for example, they can be used in an…
STREAM_WRAPPERS_READStream wrapper bit flag -- wrapper is readable (almost always true).
STREAM_WRAPPERS_READ_VISIBLEStream wrapper type flag -- visible and read-only.
STREAM_WRAPPERS_VISIBLEStream wrapper bit flag -- exposed in the UI and potentially web accessible.
STREAM_WRAPPERS_WRITEStream wrapper bit flag -- wrapper is writeable.
STREAM_WRAPPERS_WRITE_VISIBLEStream wrapper type flag -- visible, readable and writeable.

File

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