file.inc

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

API for handling file uploads and server file management.

Functions

Namesort descending Description
drupal_basename Gets the filename from a given path.
drupal_chmod Sets the permissions on a file or directory.
drupal_dirname Gets the name of the directory from a given path.
drupal_mkdir Creates a directory, optionally creating missing components in the path to the directory.
drupal_move_uploaded_file Moves an uploaded file to a new location.
drupal_realpath Resolves the absolute filepath of a local URI or filepath.
drupal_rmdir Removes a directory.
drupal_tempnam Creates a file with a unique filename in the specified directory.
drupal_unlink Deletes a file.
file_build_uri Constructs a URI to Drupal's default files location given a relative path.
file_create_filename Creates a full file path from a directory and filename.
file_create_url Creates a web-accessible URL for a stream to an external or local file.
file_default_scheme Gets the default file stream implementation.
file_delete Deletes a file and its database record.
file_delete_multiple Deletes files.
file_destination Determines the destination path for a file.
file_directory_os_temp Discovers a writable system-appropriate temporary directory.
file_directory_temp Gets and sets the path of the configured temporary directory.
file_ensure_htaccess Creates a .htaccess file in each Drupal files directory if it is missing.
file_get_mimetype Deprecated Determines an Internet Media Type or MIME type from a filename.
file_get_stream_wrappers Provides Drupal stream wrapper registry.
file_htaccess_lines Returns the standard .htaccess lines that Drupal writes to file directories.
file_munge_filename Modifies a filename as needed for security purposes.
file_prepare_directory Checks that the directory exists and is writable.
file_save_htaccess Creates a .htaccess file in the given directory.
file_scan_directory Finds all files that match a given mask in a given directory.
file_stream_wrapper_get_class Returns the stream wrapper class name for a given scheme.
file_stream_wrapper_get_instance_by_scheme Returns a reference to the stream wrapper class responsible for a scheme.
file_stream_wrapper_get_instance_by_uri Returns a reference to the stream wrapper class responsible for a given URI.
file_stream_wrapper_uri_normalize Normalizes a URI by making it syntactically correct.
file_stream_wrapper_valid_scheme Checks that the scheme of a stream URI is valid.
file_unmanaged_copy Copies a file to a new location without invoking the file API.
file_unmanaged_delete Deletes a file without database changes or hook invocations.
file_unmanaged_delete_recursive Deletes all files and directories in the specified filepath recursively.
file_unmanaged_move Moves a file to a new location without database changes or hook invocation.
file_unmanaged_save_data Saves a file to the specified destination without invoking file API.
file_unmunge_filename Undoes the effect of file_munge_filename().
file_upload_max_size Determines the maximum file upload size by querying the PHP settings.
file_uri_scheme Returns the scheme of a URI (e.g. a stream).
file_uri_target Returns the part of a URI after the schema.
file_url_transform_relative Transforms an absolute URL of a local file to a relative URL.
file_valid_uri Determines whether the URI has a valid scheme for file API operations.
_drupal_mkdir_call Helper function. Ensures we don't pass a NULL as a context resource to mkdir().

Constants

Namesort descending Description
FILE_CHMOD_DIRECTORY Default mode for new directories. See drupal_chmod().
FILE_CHMOD_FILE Default mode for new files. See drupal_chmod().
FILE_CREATE_DIRECTORY Flag used by file_prepare_directory() -- create directory if not present.
FILE_EXISTS_ERROR Flag for dealing with existing files: Do nothing and return FALSE.
FILE_EXISTS_RENAME Flag for dealing with existing files: Appends number until name is unique.
FILE_EXISTS_REPLACE Flag for dealing with existing files: Replace the existing file.
FILE_MODIFY_PERMISSIONS Flag used by file_prepare_directory() -- file permissions may be changed.
FILE_STATUS_PERMANENT Indicates that the file is permanent and should not be deleted.
STREAM_WRAPPERS_ALL Stream wrapper bit flag -- a filter that matches all wrappers.
STREAM_WRAPPERS_HIDDEN Stream 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_LOCAL Stream wrapper bit flag -- refers to a local file system location.
STREAM_WRAPPERS_LOCAL_HIDDEN Stream wrapper type flag -- hidden, readable and writeable using local files.
STREAM_WRAPPERS_LOCAL_NORMAL Stream wrapper type flag -- visible, readable and writeable using local files.
STREAM_WRAPPERS_NORMAL Stream 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_READ Stream wrapper bit flag -- wrapper is readable (almost always true).
STREAM_WRAPPERS_READ_VISIBLE Stream wrapper type flag -- visible and read-only.
STREAM_WRAPPERS_VISIBLE Stream wrapper bit flag -- exposed in the UI and potentially web accessible.
STREAM_WRAPPERS_WRITE Stream wrapper bit flag -- wrapper is writeable.
STREAM_WRAPPERS_WRITE_VISIBLE Stream wrapper type flag -- visible, readable and writeable.

File

drupal/core/includes/file.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * API for handling file uploads and server file management.
  5. */
  6. use Drupal\Component\Utility\UrlHelper;
  7. use Drupal\Component\PhpStorage\FileStorage;
  8. use Drupal\Component\Utility\Bytes;
  9. use Drupal\Component\Utility\String;
  10. use Drupal\Core\Site\Settings;
  11. use Drupal\Core\StreamWrapper\PublicStream;
  12. /**
  13. * Stream wrapper bit flags that are the basis for composite types.
  14. *
  15. * Note that 0x0002 is skipped, because it was the value of a constant that has
  16. * since been removed.
  17. */
  18. /**
  19. * Stream wrapper bit flag -- a filter that matches all wrappers.
  20. */
  21. const STREAM_WRAPPERS_ALL = 0x0000;
  22. /**
  23. * Stream wrapper bit flag -- refers to a local file system location.
  24. */
  25. const STREAM_WRAPPERS_LOCAL = 0x0001;
  26. /**
  27. * Stream wrapper bit flag -- wrapper is readable (almost always true).
  28. */
  29. const STREAM_WRAPPERS_READ = 0x0004;
  30. /**
  31. * Stream wrapper bit flag -- wrapper is writeable.
  32. */
  33. const STREAM_WRAPPERS_WRITE = 0x0008;
  34. /**
  35. * Stream wrapper bit flag -- exposed in the UI and potentially web accessible.
  36. */
  37. const STREAM_WRAPPERS_VISIBLE = 0x0010;
  38. /**
  39. * Default mode for new directories. See drupal_chmod().
  40. */
  41. const FILE_CHMOD_DIRECTORY = 0775;
  42. /**
  43. * Default mode for new files. See drupal_chmod().
  44. */
  45. const FILE_CHMOD_FILE = 0664;
  46. /**
  47. * Composite stream wrapper bit flags that are usually used as the types.
  48. */
  49. /**
  50. * Stream wrapper type flag -- not visible in the UI or accessible via web,
  51. * but readable and writable. E.g. the temporary directory for uploads.
  52. */
  53. define('STREAM_WRAPPERS_HIDDEN', STREAM_WRAPPERS_READ | STREAM_WRAPPERS_WRITE);
  54. /**
  55. * Stream wrapper type flag -- hidden, readable and writeable using local files.
  56. */
  57. define('STREAM_WRAPPERS_LOCAL_HIDDEN', STREAM_WRAPPERS_LOCAL | STREAM_WRAPPERS_HIDDEN);
  58. /**
  59. * Stream wrapper type flag -- visible, readable and writeable.
  60. */
  61. define('STREAM_WRAPPERS_WRITE_VISIBLE', STREAM_WRAPPERS_READ | STREAM_WRAPPERS_WRITE | STREAM_WRAPPERS_VISIBLE);
  62. /**
  63. * Stream wrapper type flag -- visible and read-only.
  64. */
  65. define('STREAM_WRAPPERS_READ_VISIBLE', STREAM_WRAPPERS_READ | STREAM_WRAPPERS_VISIBLE);
  66. /**
  67. * Stream wrapper type flag -- the default when 'type' is omitted from
  68. * hook_stream_wrappers(). This does not include STREAM_WRAPPERS_LOCAL,
  69. * because PHP grants a greater trust level to local files (for example, they
  70. * can be used in an "include" statement, regardless of the "allow_url_include"
  71. * setting), so stream wrappers need to explicitly opt-in to this.
  72. */
  73. define('STREAM_WRAPPERS_NORMAL', STREAM_WRAPPERS_WRITE_VISIBLE);
  74. /**
  75. * Stream wrapper type flag -- visible, readable and writeable using local files.
  76. */
  77. define('STREAM_WRAPPERS_LOCAL_NORMAL', STREAM_WRAPPERS_LOCAL | STREAM_WRAPPERS_NORMAL);
  78. /**
  79. * @defgroup file File interface
  80. * @{
  81. * Common file handling functions.
  82. *
  83. * Fields on the file entity:
  84. * - fid: File ID
  85. * - uid: The {users}.uid of the user who is associated with the file.
  86. * - filename: Name of the file with no path components. This may differ from
  87. * the basename of the filepath if the file is renamed to avoid overwriting
  88. * an existing file.
  89. * - uri: URI of the file.
  90. * - filemime: The file's MIME type.
  91. * - filesize: The size of the file in bytes.
  92. * - status: A bitmapped field indicating the status of the file. The first 8
  93. * bits are reserved for Drupal core. The least significant bit indicates
  94. * temporary (0) or permanent (1). Temporary files will be removed during
  95. * cron runs if they are older than the configuration value
  96. * "system.file.temporary_maximum_age", and if clean-up is enabled. Permanent
  97. * files will not be removed.
  98. * - timestamp: UNIX timestamp for the date the file was added to the database.
  99. */
  100. /**
  101. * Flag used by file_prepare_directory() -- create directory if not present.
  102. */
  103. const FILE_CREATE_DIRECTORY = 1;
  104. /**
  105. * Flag used by file_prepare_directory() -- file permissions may be changed.
  106. */
  107. const FILE_MODIFY_PERMISSIONS = 2;
  108. /**
  109. * Flag for dealing with existing files: Appends number until name is unique.
  110. */
  111. const FILE_EXISTS_RENAME = 0;
  112. /**
  113. * Flag for dealing with existing files: Replace the existing file.
  114. */
  115. const FILE_EXISTS_REPLACE = 1;
  116. /**
  117. * Flag for dealing with existing files: Do nothing and return FALSE.
  118. */
  119. const FILE_EXISTS_ERROR = 2;
  120. /**
  121. * Indicates that the file is permanent and should not be deleted.
  122. *
  123. * Temporary files older than the system.file.temporary_maximum_age
  124. * configuration value will be, if clean-up not disabled, removed during cron
  125. * runs, but permanent files will not be removed during the file garbage
  126. * collection process.
  127. */
  128. const FILE_STATUS_PERMANENT = 1;
  129. /**
  130. * Provides Drupal stream wrapper registry.
  131. *
  132. * A stream wrapper is an abstraction of a file system that allows Drupal to
  133. * use the same set of methods to access both local files and remote resources.
  134. *
  135. * Provide a facility for managing and querying user-defined stream wrappers
  136. * in PHP. PHP's internal stream_get_wrappers() doesn't return the class
  137. * registered to handle a stream, which we need to be able to find the handler
  138. * for class instantiation.
  139. *
  140. * If a module registers a scheme that is already registered with PHP, the
  141. * existing scheme will be unregistered and replaced with the specified class.
  142. *
  143. * A stream is referenced as "scheme://target".
  144. *
  145. * The optional $filter parameter can be used to retrieve only the stream
  146. * wrappers that are appropriate for particular usage. For example, this returns
  147. * only stream wrappers that use local file storage:
  148. * @code
  149. * $local_stream_wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL);
  150. * @endcode
  151. *
  152. * The $filter parameter can only filter to types containing a particular flag.
  153. * In some cases, you may want to filter to types that do not contain a
  154. * particular flag. For example, you may want to retrieve all stream wrappers
  155. * that are not writable, or all stream wrappers that are not local. PHP's
  156. * array_diff_key() function can be used to help with this. For example, this
  157. * returns only stream wrappers that do not use local file storage:
  158. * @code
  159. * $remote_stream_wrappers = array_diff_key(file_get_stream_wrappers(STREAM_WRAPPERS_ALL), file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL));
  160. * @endcode
  161. *
  162. * @param $filter
  163. * (Optional) Filters out all types except those with an on bit for each on
  164. * bit in $filter. For example, if $filter is STREAM_WRAPPERS_WRITE_VISIBLE,
  165. * which is equal to (STREAM_WRAPPERS_READ | STREAM_WRAPPERS_WRITE |
  166. * STREAM_WRAPPERS_VISIBLE), then only stream wrappers with all three of these
  167. * bits set are returned. Defaults to STREAM_WRAPPERS_ALL, which returns all
  168. * registered stream wrappers.
  169. *
  170. * @return
  171. * An array keyed by scheme, with values containing an array of information
  172. * about the stream wrapper, as returned by hook_stream_wrappers(). If $filter
  173. * is omitted or set to STREAM_WRAPPERS_ALL, the entire Drupal stream wrapper
  174. * registry is returned. Otherwise only the stream wrappers whose 'type'
  175. * bitmask has an on bit for each bit specified in $filter are returned.
  176. *
  177. * @see hook_stream_wrappers()
  178. * @see hook_stream_wrappers_alter()
  179. */
  180. function file_get_stream_wrappers($filter = STREAM_WRAPPERS_ALL) {
  181. $wrappers_storage = &drupal_static(__FUNCTION__, array());
  182. if (empty($wrappers_storage)) {
  183. // Initialize $wrappers_storage, so that we are not calling this method
  184. // repeatedly if no stream wrappers exist.
  185. $wrappers_storage[STREAM_WRAPPERS_ALL] = array();
  186. $wrappers = array();
  187. if (\Drupal::hasService('module_handler')) {
  188. $wrappers = \Drupal::moduleHandler()->invokeAll('stream_wrappers');
  189. foreach ($wrappers as $scheme => $info) {
  190. // Add defaults.
  191. $wrappers[$scheme] += array('type' => STREAM_WRAPPERS_NORMAL);
  192. }
  193. \Drupal::moduleHandler()->alter('stream_wrappers', $wrappers);
  194. }
  195. $existing = stream_get_wrappers();
  196. foreach ($wrappers as $scheme => $info) {
  197. // We only register classes that implement our interface.
  198. if (in_array('Drupal\Core\StreamWrapper\StreamWrapperInterface', class_implements($info['class']), TRUE)) {
  199. // Record whether we are overriding an existing scheme.
  200. if (in_array($scheme, $existing, TRUE)) {
  201. $wrappers[$scheme]['override'] = TRUE;
  202. stream_wrapper_unregister($scheme);
  203. }
  204. else {
  205. $wrappers[$scheme]['override'] = FALSE;
  206. }
  207. if (($info['type'] & STREAM_WRAPPERS_LOCAL) == STREAM_WRAPPERS_LOCAL) {
  208. stream_wrapper_register($scheme, $info['class']);
  209. }
  210. else {
  211. stream_wrapper_register($scheme, $info['class'], STREAM_IS_URL);
  212. }
  213. }
  214. // Pre-populate the static cache with the filters most typically used.
  215. $wrappers_storage[STREAM_WRAPPERS_ALL][$scheme] = $wrappers[$scheme];
  216. if (($info['type'] & STREAM_WRAPPERS_WRITE_VISIBLE) == STREAM_WRAPPERS_WRITE_VISIBLE) {
  217. $wrappers_storage[STREAM_WRAPPERS_WRITE_VISIBLE][$scheme] = $wrappers[$scheme];
  218. }
  219. }
  220. }
  221. if (!isset($wrappers_storage[$filter])) {
  222. $wrappers_storage[$filter] = array();
  223. foreach ($wrappers_storage[STREAM_WRAPPERS_ALL] as $scheme => $info) {
  224. // Bit-wise filter.
  225. if (($info['type'] & $filter) == $filter) {
  226. $wrappers_storage[$filter][$scheme] = $info;
  227. }
  228. }
  229. }
  230. return $wrappers_storage[$filter];
  231. }
  232. /**
  233. * Returns the stream wrapper class name for a given scheme.
  234. *
  235. * @param $scheme
  236. * Stream scheme.
  237. *
  238. * @return
  239. * Return string if a scheme has a registered handler, or FALSE.
  240. */
  241. function file_stream_wrapper_get_class($scheme) {
  242. $wrappers = file_get_stream_wrappers();
  243. return empty($wrappers[$scheme]) ? FALSE : $wrappers[$scheme]['class'];
  244. }
  245. /**
  246. * Returns the scheme of a URI (e.g. a stream).
  247. *
  248. * @param $uri
  249. * A stream, referenced as "scheme://target".
  250. *
  251. * @return
  252. * A string containing the name of the scheme, or FALSE if none. For example,
  253. * the URI "public://example.txt" would return "public".
  254. *
  255. * @see file_uri_target()
  256. */
  257. function file_uri_scheme($uri) {
  258. $position = strpos($uri, '://');
  259. return $position ? substr($uri, 0, $position) : FALSE;
  260. }
  261. /**
  262. * Checks that the scheme of a stream URI is valid.
  263. *
  264. * Confirms that there is a registered stream handler for the provided scheme
  265. * and that it is callable. This is useful if you want to confirm a valid
  266. * scheme without creating a new instance of the registered handler.
  267. *
  268. * @param $scheme
  269. * A URI scheme, a stream is referenced as "scheme://target".
  270. *
  271. * @return
  272. * Returns TRUE if the string is the name of a validated stream,
  273. * or FALSE if the scheme does not have a registered handler.
  274. */
  275. function file_stream_wrapper_valid_scheme($scheme) {
  276. return $scheme && class_exists(file_stream_wrapper_get_class($scheme));
  277. }
  278. /**
  279. * Returns the part of a URI after the schema.
  280. *
  281. * @param $uri
  282. * A stream, referenced as "scheme://target".
  283. *
  284. * @return
  285. * A string containing the target (path), or FALSE if none.
  286. * For example, the URI "public://sample/test.txt" would return
  287. * "sample/test.txt".
  288. *
  289. * @see file_uri_scheme()
  290. */
  291. function file_uri_target($uri) {
  292. $data = explode('://', $uri, 2);
  293. // Remove erroneous leading or trailing, forward-slashes and backslashes.
  294. return count($data) == 2 ? trim($data[1], '\/') : FALSE;
  295. }
  296. /**
  297. * Gets the default file stream implementation.
  298. *
  299. * @return
  300. * 'public', 'private' or any other file scheme defined as the default.
  301. */
  302. function file_default_scheme() {
  303. return \Drupal::config('system.file')->get('default_scheme');
  304. }
  305. /**
  306. * Normalizes a URI by making it syntactically correct.
  307. *
  308. * A stream is referenced as "scheme://target".
  309. *
  310. * The following actions are taken:
  311. * - Remove trailing slashes from target
  312. * - Trim erroneous leading slashes from target. e.g. ":///" becomes "://".
  313. *
  314. * @param $uri
  315. * String reference containing the URI to normalize.
  316. *
  317. * @return
  318. * The normalized URI.
  319. */
  320. function file_stream_wrapper_uri_normalize($uri) {
  321. $scheme = file_uri_scheme($uri);
  322. if (file_stream_wrapper_valid_scheme($scheme)) {
  323. $target = file_uri_target($uri);
  324. if ($target !== FALSE) {
  325. $uri = $scheme . '://' . $target;
  326. }
  327. }
  328. return $uri;
  329. }
  330. /**
  331. * Returns a reference to the stream wrapper class responsible for a given URI.
  332. *
  333. * The scheme determines the stream wrapper class that should be
  334. * used by consulting the stream wrapper registry.
  335. *
  336. * @param $uri
  337. * A stream, referenced as "scheme://target".
  338. *
  339. * @return
  340. * Returns a new stream wrapper object appropriate for the given URI or FALSE
  341. * if no registered handler could be found. For example, a URI of
  342. * "private://example.txt" would return a new private stream wrapper object
  343. * (Drupal\Core\StreamWrapper\PrivateStream).
  344. */
  345. function file_stream_wrapper_get_instance_by_uri($uri) {
  346. if ($scheme = file_uri_scheme($uri)) {
  347. $class = file_stream_wrapper_get_class($scheme);
  348. if (class_exists($class)) {
  349. $instance = new $class();
  350. $instance->setUri($uri);
  351. return $instance;
  352. }
  353. }
  354. return FALSE;
  355. }
  356. /**
  357. * Returns a reference to the stream wrapper class responsible for a scheme.
  358. *
  359. * This helper method returns a stream instance using a scheme. That is, the
  360. * passed string does not contain a "://". For example, "public" is a scheme
  361. * but "public://" is a URI (stream). This is because the later contains both
  362. * a scheme and target despite target being empty.
  363. *
  364. * Note: the instance URI will be initialized to "scheme://" so that you can
  365. * make the customary method calls as if you had retrieved an instance by URI.
  366. *
  367. * @param $scheme
  368. * If the stream was "public://target", "public" would be the scheme.
  369. *
  370. * @return \Drupal\Core\StreamWrapper\StreamWrapperInterface
  371. * Returns a new stream wrapper object appropriate for the given $scheme.
  372. * For example, for the public scheme a stream wrapper object
  373. * (Drupal\Core\StreamWrapper\PublicStream).
  374. * FALSE is returned if no registered handler could be found.
  375. */
  376. function file_stream_wrapper_get_instance_by_scheme($scheme) {
  377. $class = file_stream_wrapper_get_class($scheme);
  378. if (class_exists($class)) {
  379. $instance = new $class();
  380. $instance->setUri($scheme . '://');
  381. return $instance;
  382. }
  383. else {
  384. return FALSE;
  385. }
  386. }
  387. /**
  388. * Creates a web-accessible URL for a stream to an external or local file.
  389. *
  390. * Compatibility: normal paths and stream wrappers.
  391. *
  392. * There are two kinds of local files:
  393. * - "managed files", i.e. those stored by a Drupal-compatible stream wrapper.
  394. * These are files that have either been uploaded by users or were generated
  395. * automatically (for example through CSS aggregation).
  396. * - "shipped files", i.e. those outside of the files directory, which ship as
  397. * part of Drupal core or contributed modules or themes.
  398. *
  399. * @param $uri
  400. * The URI to a file for which we need an external URL, or the path to a
  401. * shipped file.
  402. *
  403. * @return
  404. * A string containing a URL that may be used to access the file.
  405. * If the provided string already contains a preceding 'http', 'https', or
  406. * '/', nothing is done and the same string is returned. If a stream wrapper
  407. * could not be found to generate an external URL, then FALSE is returned.
  408. *
  409. * @see http://drupal.org/node/515192
  410. * @see file_url_transform_relative()
  411. */
  412. function file_create_url($uri) {
  413. // Allow the URI to be altered, e.g. to serve a file from a CDN or static
  414. // file server.
  415. \Drupal::moduleHandler()->alter('file_url', $uri);
  416. $scheme = file_uri_scheme($uri);
  417. if (!$scheme) {
  418. // Allow for:
  419. // - root-relative URIs (e.g. /foo.jpg in http://example.com/foo.jpg)
  420. // - protocol-relative URIs (e.g. //bar.jpg, which is expanded to
  421. // http://example.com/bar.jpg by the browser when viewing a page over
  422. // HTTP and to https://example.com/bar.jpg when viewing a HTTPS page)
  423. // Both types of relative URIs are characterized by a leading slash, hence
  424. // we can use a single check.
  425. if (drupal_substr($uri, 0, 1) == '/') {
  426. return $uri;
  427. }
  428. else {
  429. // If this is not a properly formatted stream, then it is a shipped file.
  430. // Therefore, return the urlencoded URI with the base URL prepended.
  431. return $GLOBALS['base_url'] . '/' . UrlHelper::encodePath($uri);
  432. }
  433. }
  434. elseif ($scheme == 'http' || $scheme == 'https') {
  435. // Check for HTTP so that we don't have to implement getExternalUrl() for
  436. // the HTTP wrapper.
  437. return $uri;
  438. }
  439. else {
  440. // Attempt to return an external URL using the appropriate wrapper.
  441. if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
  442. return $wrapper->getExternalUrl();
  443. }
  444. else {
  445. return FALSE;
  446. }
  447. }
  448. }
  449. /**
  450. * Transforms an absolute URL of a local file to a relative URL.
  451. *
  452. * May be useful to prevent problems on multisite set-ups and prevent mixed
  453. * content errors when using HTTPS + HTTP.
  454. *
  455. * @param string $file_url
  456. * A file URL of a local file as generated by file_create_url().
  457. *
  458. * @return string
  459. * If the file URL indeed pointed to a local file and was indeed absolute,
  460. * then the transformed, relative URL to the local file. Otherwise: the
  461. * original value of $file_url.
  462. *
  463. * @see file_create_url()
  464. */
  465. function file_url_transform_relative($file_url) {
  466. // Unfortunately, we pretty much have to duplicate Symfony's
  467. // Request::getHttpHost() method because Request::getPort() may return NULL
  468. // instead of a port number.
  469. $http_host = '';
  470. $request = \Drupal::request();
  471. $host = $request->getHost();
  472. $scheme = $request->getScheme();
  473. $port = $request->getPort() ?: 80;
  474. if (('http' == $scheme && $port == 80) || ('https' == $scheme && $port == 443)) {
  475. $http_host = $host;
  476. }
  477. else {
  478. $http_host = $host . ':' . $port;
  479. }
  480. return preg_replace('|^https?://' . $http_host . '|', '', $file_url);
  481. }
  482. /**
  483. * Checks that the directory exists and is writable.
  484. *
  485. * Directories need to have execute permissions to be considered a directory by
  486. * FTP servers, etc.
  487. *
  488. * @param $directory
  489. * A string reference containing the name of a directory path or URI. A
  490. * trailing slash will be trimmed from a path.
  491. * @param $options
  492. * A bitmask to indicate if the directory should be created if it does
  493. * not exist (FILE_CREATE_DIRECTORY) or made writable if it is read-only
  494. * (FILE_MODIFY_PERMISSIONS).
  495. *
  496. * @return
  497. * TRUE if the directory exists (or was created) and is writable. FALSE
  498. * otherwise.
  499. */
  500. function file_prepare_directory(&$directory, $options = FILE_MODIFY_PERMISSIONS) {
  501. if (!file_stream_wrapper_valid_scheme(file_uri_scheme($directory))) {
  502. // Only trim if we're not dealing with a stream.
  503. $directory = rtrim($directory, '/\\');
  504. }
  505. // Check if directory exists.
  506. if (!is_dir($directory)) {
  507. // Let mkdir() recursively create directories and use the default directory
  508. // permissions.
  509. if ($options & FILE_CREATE_DIRECTORY) {
  510. return @drupal_mkdir($directory, NULL, TRUE);
  511. }
  512. return FALSE;
  513. }
  514. // The directory exists, so check to see if it is writable.
  515. $writable = is_writable($directory);
  516. if (!$writable && ($options & FILE_MODIFY_PERMISSIONS)) {
  517. return drupal_chmod($directory);
  518. }
  519. return $writable;
  520. }
  521. /**
  522. * Creates a .htaccess file in each Drupal files directory if it is missing.
  523. */
  524. function file_ensure_htaccess() {
  525. file_save_htaccess('public://', FALSE);
  526. $private_path = \Drupal::config('system.file')->get('path.private');
  527. if (!empty($private_path)) {
  528. file_save_htaccess('private://', TRUE);
  529. }
  530. file_save_htaccess('temporary://', TRUE);
  531. file_save_htaccess(config_get_config_directory(), TRUE);
  532. file_save_htaccess(config_get_config_directory(CONFIG_STAGING_DIRECTORY), TRUE);
  533. }
  534. /**
  535. * Creates a .htaccess file in the given directory.
  536. *
  537. * @param string $directory
  538. * The directory.
  539. * @param bool $private
  540. * (Optional) FALSE indicates that $directory should be a web-accessible
  541. * directory. Defaults to TRUE which indicates a private directory.
  542. * @param bool $force_overwrite
  543. * (Optional) Set to TRUE to attempt to overwrite the existing .htaccess file
  544. * if one is already present. Defaults to FALSE.
  545. */
  546. function file_save_htaccess($directory, $private = TRUE, $force_overwrite = FALSE) {
  547. if (file_uri_scheme($directory)) {
  548. $htaccess_path = file_stream_wrapper_uri_normalize($directory . '/.htaccess');
  549. }
  550. else {
  551. $directory = rtrim($directory, '/\\');
  552. $htaccess_path = $directory . '/.htaccess';
  553. }
  554. if (file_exists($htaccess_path) && !$force_overwrite) {
  555. // Short circuit if the .htaccess file already exists.
  556. return TRUE;
  557. }
  558. $htaccess_lines = file_htaccess_lines($private);
  559. // Write the .htaccess file.
  560. if (file_exists($directory) && is_writable($directory) && file_put_contents($htaccess_path, $htaccess_lines)) {
  561. return drupal_chmod($htaccess_path, 0444);
  562. }
  563. else {
  564. $variables = array('%directory' => $directory, '!htaccess' => '<br />' . nl2br(String::checkPlain($htaccess_lines)));
  565. \Drupal::logger('security')->error("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);
  566. return FALSE;
  567. }
  568. }
  569. /**
  570. * Returns the standard .htaccess lines that Drupal writes to file directories.
  571. *
  572. * @param bool $private
  573. * (Optional) Set to FALSE to return the .htaccess lines for a web-accessible
  574. * public directory. The default is TRUE, which returns the .htaccess lines
  575. * for a private directory that should not be web-accessible.
  576. *
  577. * @return string
  578. * The desired contents of the .htaccess file.
  579. *
  580. * @see file_create_htaccess()
  581. */
  582. function file_htaccess_lines($private = TRUE) {
  583. return FileStorage::htaccessLines($private);
  584. }
  585. /**
  586. * Determines whether the URI has a valid scheme for file API operations.
  587. *
  588. * There must be a scheme and it must be a Drupal-provided scheme like
  589. * 'public', 'private', 'temporary', or an extension provided with
  590. * hook_stream_wrappers().
  591. *
  592. * @param $uri
  593. * The URI to be tested.
  594. *
  595. * @return
  596. * TRUE if the URI is allowed.
  597. */
  598. function file_valid_uri($uri) {
  599. // Assert that the URI has an allowed scheme. Barepaths are not allowed.
  600. $uri_scheme = file_uri_scheme($uri);
  601. if (!file_stream_wrapper_valid_scheme($uri_scheme)) {
  602. return FALSE;
  603. }
  604. return TRUE;
  605. }
  606. /**
  607. * Copies a file to a new location without invoking the file API.
  608. *
  609. * This is a powerful function that in many ways performs like an advanced
  610. * version of copy().
  611. * - Checks if $source and $destination are valid and readable/writable.
  612. * - If file already exists in $destination either the call will error out,
  613. * replace the file or rename the file based on the $replace parameter.
  614. * - If the $source and $destination are equal, the behavior depends on the
  615. * $replace parameter. FILE_EXISTS_REPLACE will error out. FILE_EXISTS_RENAME
  616. * will rename the file until the $destination is unique.
  617. * - Provides a fallback using realpaths if the move fails using stream
  618. * wrappers. This can occur because PHP's copy() function does not properly
  619. * support streams if open_basedir is enabled. See
  620. * https://bugs.php.net/bug.php?id=60456
  621. *
  622. * @param $source
  623. * A string specifying the filepath or URI of the source file.
  624. * @param $destination
  625. * A URI containing the destination that $source should be copied to. The
  626. * URI may be a bare filepath (without a scheme). If this value is omitted,
  627. * Drupal's default files scheme will be used, usually "public://".
  628. * @param $replace
  629. * Replace behavior when the destination file already exists:
  630. * - FILE_EXISTS_REPLACE - Replace the existing file.
  631. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  632. * unique.
  633. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  634. *
  635. * @return
  636. * The path to the new file, or FALSE in the event of an error.
  637. *
  638. * @see file_copy()
  639. */
  640. function file_unmanaged_copy($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  641. $original_source = $source;
  642. $logger = \Drupal::logger('file');
  643. // Assert that the source file actually exists.
  644. if (!file_exists($source)) {
  645. // @todo Replace drupal_set_message() calls with exceptions instead.
  646. 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');
  647. if (($realpath = drupal_realpath($original_source)) !== FALSE) {
  648. $logger->notice('File %file (%realpath) could not be copied because it does not exist.', array('%file' => $original_source, '%realpath' => $realpath));
  649. }
  650. else {
  651. $logger->notice('File %file could not be copied because it does not exist.', array('%file' => $original_source));
  652. }
  653. return FALSE;
  654. }
  655. // Build a destination URI if necessary.
  656. if (!isset($destination)) {
  657. $destination = file_build_uri(drupal_basename($source));
  658. }
  659. // Prepare the destination directory.
  660. if (file_prepare_directory($destination)) {
  661. // The destination is already a directory, so append the source basename.
  662. $destination = file_stream_wrapper_uri_normalize($destination . '/' . drupal_basename($source));
  663. }
  664. else {
  665. // Perhaps $destination is a dir/file?
  666. $dirname = drupal_dirname($destination);
  667. if (!file_prepare_directory($dirname)) {
  668. // The destination is not valid.
  669. $logger->notice('File %file could not be copied because the destination directory %destination is not configured correctly.', array('%file' => $original_source, '%destination' => $dirname));
  670. 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');
  671. return FALSE;
  672. }
  673. }
  674. // Determine whether we can perform this operation based on overwrite rules.
  675. $destination = file_destination($destination, $replace);
  676. if ($destination === FALSE) {
  677. 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');
  678. $logger->notice('File %file could not be copied because a file by that name already exists in the destination directory (%destination)', array('%file' => $original_source, '%destination' => $destination));
  679. return FALSE;
  680. }
  681. // Assert that the source and destination filenames are not the same.
  682. $real_source = drupal_realpath($source);
  683. $real_destination = drupal_realpath($destination);
  684. if ($source == $destination || ($real_source !== FALSE) && ($real_source == $real_destination)) {
  685. drupal_set_message(t('The specified file %file was not copied because it would overwrite itself.', array('%file' => $source)), 'error');
  686. $logger->notice('File %file could not be copied because it would overwrite itself.', array('%file' => $source));
  687. return FALSE;
  688. }
  689. // Make sure the .htaccess files are present.
  690. file_ensure_htaccess();
  691. // Perform the copy operation.
  692. if (!@copy($source, $destination)) {
  693. // If the copy failed and realpaths exist, retry the operation using them
  694. // instead.
  695. if ($real_source === FALSE || $real_destination === FALSE || !@copy($real_source, $real_destination)) {
  696. $logger->error('file', 'The specified file %file could not be copied to %destination.', array('%file' => $source, '%destination' => $destination));
  697. return FALSE;
  698. }
  699. }
  700. // Set the permissions on the new file.
  701. drupal_chmod($destination);
  702. return $destination;
  703. }
  704. /**
  705. * Constructs a URI to Drupal's default files location given a relative path.
  706. */
  707. function file_build_uri($path) {
  708. $uri = file_default_scheme() . '://' . $path;
  709. return file_stream_wrapper_uri_normalize($uri);
  710. }
  711. /**
  712. * Determines the destination path for a file.
  713. *
  714. * @param $destination
  715. * A string specifying the desired final URI or filepath.
  716. * @param $replace
  717. * Replace behavior when the destination file already exists.
  718. * - FILE_EXISTS_REPLACE - Replace the existing file.
  719. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  720. * unique.
  721. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  722. *
  723. * @return
  724. * The destination filepath, or FALSE if the file already exists
  725. * and FILE_EXISTS_ERROR is specified.
  726. */
  727. function file_destination($destination, $replace) {
  728. if (file_exists($destination)) {
  729. switch ($replace) {
  730. case FILE_EXISTS_REPLACE:
  731. // Do nothing here, we want to overwrite the existing file.
  732. break;
  733. case FILE_EXISTS_RENAME:
  734. $basename = drupal_basename($destination);
  735. $directory = drupal_dirname($destination);
  736. $destination = file_create_filename($basename, $directory);
  737. break;
  738. case FILE_EXISTS_ERROR:
  739. // Error reporting handled by calling function.
  740. return FALSE;
  741. }
  742. }
  743. return $destination;
  744. }
  745. /**
  746. * Moves a file to a new location without database changes or hook invocation.
  747. *
  748. * @param $source
  749. * A string specifying the filepath or URI of the original file.
  750. * @param $destination
  751. * A string containing the destination that $source should be moved to.
  752. * This must be a stream wrapper URI. If this value is omitted, Drupal's
  753. * default files scheme will be used, usually "public://".
  754. * @param $replace
  755. * Replace behavior when the destination file already exists:
  756. * - FILE_EXISTS_REPLACE - Replace the existing file.
  757. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  758. * unique.
  759. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  760. *
  761. * @return
  762. * The URI of the moved file, or FALSE in the event of an error.
  763. *
  764. * @see file_move()
  765. */
  766. function file_unmanaged_move($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  767. $filepath = file_unmanaged_copy($source, $destination, $replace);
  768. if ($filepath == FALSE || file_unmanaged_delete($source) == FALSE) {
  769. return FALSE;
  770. }
  771. return $filepath;
  772. }
  773. /**
  774. * Modifies a filename as needed for security purposes.
  775. *
  776. * Munging a file name prevents unknown file extensions from masking exploit
  777. * files. When web servers such as Apache decide how to process a URL request,
  778. * they use the file extension. If the extension is not recognized, Apache
  779. * skips that extension and uses the previous file extension. For example, if
  780. * the file being requested is exploit.php.pps, and Apache does not recognize
  781. * the '.pps' extension, it treats the file as PHP and executes it. To make
  782. * this file name safe for Apache and prevent it from executing as PHP, the
  783. * .php extension is "munged" into .php_, making the safe file name
  784. * exploit.php_.pps.
  785. *
  786. * Specifically, this function adds an underscore to all extensions that are
  787. * between 2 and 5 characters in length, internal to the file name, and not
  788. * included in $extensions.
  789. *
  790. * Function behavior is also controlled by the configuration
  791. * 'system.file:allow_insecure_uploads'. If it evaluates to TRUE, no alterations
  792. * will be made, if it evaluates to FALSE, the filename is 'munged'. *
  793. * @param $filename
  794. * File name to modify.
  795. * @param $extensions
  796. * A space-separated list of extensions that should not be altered.
  797. * @param $alerts
  798. * If TRUE, drupal_set_message() will be called to display a message if the
  799. * file name was changed.
  800. *
  801. * @return string
  802. * The potentially modified $filename.
  803. */
  804. function file_munge_filename($filename, $extensions, $alerts = TRUE) {
  805. $original = $filename;
  806. // Allow potentially insecure uploads for very savvy users and admin
  807. if (!\Drupal::config('system.file')->get('allow_insecure_uploads')) {
  808. // Remove any null bytes. See http://php.net/manual/en/security.filesystem.nullbytes.php
  809. $filename = str_replace(chr(0), '', $filename);
  810. $whitelist = array_unique(explode(' ', strtolower(trim($extensions))));
  811. // Split the filename up by periods. The first part becomes the basename
  812. // the last part the final extension.
  813. $filename_parts = explode('.', $filename);
  814. $new_filename = array_shift($filename_parts); // Remove file basename.
  815. $final_extension = array_pop($filename_parts); // Remove final extension.
  816. // Loop through the middle parts of the name and add an underscore to the
  817. // end of each section that could be a file extension but isn't in the list
  818. // of allowed extensions.
  819. foreach ($filename_parts as $filename_part) {
  820. $new_filename .= '.' . $filename_part;
  821. if (!in_array(strtolower($filename_part), $whitelist) && preg_match("/^[a-zA-Z]{2,5}\d?$/", $filename_part)) {
  822. $new_filename .= '_';
  823. }
  824. }
  825. $filename = $new_filename . '.' . $final_extension;
  826. if ($alerts && $original != $filename) {
  827. drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $filename)));
  828. }
  829. }
  830. return $filename;
  831. }
  832. /**
  833. * Undoes the effect of file_munge_filename().
  834. *
  835. * @param $filename
  836. * String with the filename to be unmunged.
  837. *
  838. * @return
  839. * An unmunged filename string.
  840. */
  841. function file_unmunge_filename($filename) {
  842. return str_replace('_.', '.', $filename);
  843. }
  844. /**
  845. * Creates a full file path from a directory and filename.
  846. *
  847. * If a file with the specified name already exists, an alternative will be
  848. * used.
  849. *
  850. * @param $basename
  851. * String filename
  852. * @param $directory
  853. * String containing the directory or parent URI.
  854. *
  855. * @return
  856. * File path consisting of $directory and a unique filename based off
  857. * of $basename.
  858. */
  859. function file_create_filename($basename, $directory) {
  860. // Strip control characters (ASCII value < 32). Though these are allowed in
  861. // some filesystems, not many applications handle them well.
  862. $basename = preg_replace('/[\x00-\x1F]/u', '_', $basename);
  863. if (substr(PHP_OS, 0, 3) == 'WIN') {
  864. // These characters are not allowed in Windows filenames
  865. $basename = str_replace(array(':', '*', '?', '"', '<', '>', '|'), '_', $basename);
  866. }
  867. // A URI or path may already have a trailing slash or look like "public://".
  868. if (substr($directory, -1) == '/') {
  869. $separator = '';
  870. }
  871. else {
  872. $separator = '/';
  873. }
  874. $destination = $directory . $separator . $basename;
  875. if (file_exists($destination)) {
  876. // Destination file already exists, generate an alternative.
  877. $pos = strrpos($basename, '.');
  878. if ($pos !== FALSE) {
  879. $name = substr($basename, 0, $pos);
  880. $ext = substr($basename, $pos);
  881. }
  882. else {
  883. $name = $basename;
  884. $ext = '';
  885. }
  886. $counter = 0;
  887. do {
  888. $destination = $directory . $separator . $name . '_' . $counter++ . $ext;
  889. } while (file_exists($destination));
  890. }
  891. return $destination;
  892. }
  893. /**
  894. * Deletes a file and its database record.
  895. *
  896. * Instead of directly deleting a file, it is strongly recommended to delete
  897. * file usages instead. That will automatically mark the file as temporary and
  898. * remove it during cleanup.
  899. *
  900. * @param $fid
  901. * The file id.
  902. *
  903. * @see file_unmanaged_delete()
  904. * @see \Drupal\file\FileUsage\FileUsageBase::delete()
  905. */
  906. function file_delete($fid) {
  907. return file_delete_multiple(array($fid));
  908. }
  909. /**
  910. * Deletes files.
  911. *
  912. * Instead of directly deleting a file, it is strongly recommended to delete
  913. * file usages instead. That will automatically mark the file as temporary and
  914. * remove it during cleanup.
  915. *
  916. * @param $fid
  917. * The file id.
  918. *
  919. * @see file_unmanaged_delete()
  920. * @see \Drupal\file\FileUsage\FileUsageBase::delete()
  921. */
  922. function file_delete_multiple(array $fids) {
  923. entity_delete_multiple('file', $fids);
  924. }
  925. /**
  926. * Deletes a file without database changes or hook invocations.
  927. *
  928. * This function should be used when the file to be deleted does not have an
  929. * entry recorded in the files table.
  930. *
  931. * @param $path
  932. * A string containing a file path or (streamwrapper) URI.
  933. *
  934. * @return
  935. * TRUE for success or path does not exist, or FALSE in the event of an
  936. * error.
  937. *
  938. * @see file_delete()
  939. * @see file_unmanaged_delete_recursive()
  940. */
  941. function file_unmanaged_delete($path) {
  942. $logger = \Drupal::logger('file');
  943. if (is_dir($path)) {
  944. $logger->error('%path is a directory and cannot be removed using file_unmanaged_delete().', array('%path' => $path));
  945. return FALSE;
  946. }
  947. if (is_file($path)) {
  948. return drupal_unlink($path);
  949. }
  950. // Return TRUE for non-existent file, but log that nothing was actually
  951. // deleted, as the current state is the intended result.
  952. if (!file_exists($path)) {
  953. $logger->notice('The file %path was not deleted because it does not exist.', array('%path' => $path));
  954. return TRUE;
  955. }
  956. // We cannot handle anything other than files and directories. Log an error
  957. // for everything else (sockets, symbolic links, etc).
  958. $logger->error('The file %path is not of a recognized type so it was not deleted.', array('%path' => $path));
  959. return FALSE;
  960. }
  961. /**
  962. * Deletes all files and directories in the specified filepath recursively.
  963. *
  964. * If the specified path is a directory then the function will call itself
  965. * recursively to process the contents. Once the contents have been removed the
  966. * directory will also be removed.
  967. *
  968. * If the specified path is a file then it will be passed to
  969. * file_unmanaged_delete().
  970. *
  971. * Note that this only deletes visible files with write permission.
  972. *
  973. * @param $path
  974. * A string containing either an URI or a file or directory path.
  975. * @param $callback
  976. * (optional) Callback function to run on each file prior to deleting it and
  977. * on each directory prior to traversing it. For example, can be used to
  978. * modify permissions.
  979. *
  980. * @return
  981. * TRUE for success or if path does not exist, FALSE in the event of an
  982. * error.
  983. *
  984. * @see file_unmanaged_delete()
  985. */
  986. function file_unmanaged_delete_recursive($path, $callback = NULL) {
  987. if (isset($callback)) {
  988. call_user_func($callback, $path);
  989. }
  990. if (is_dir($path)) {
  991. $dir = dir($path);
  992. while (($entry = $dir->read()) !== FALSE) {
  993. if ($entry == '.' || $entry == '..') {
  994. continue;
  995. }
  996. $entry_path = $path . '/' . $entry;
  997. file_unmanaged_delete_recursive($entry_path, $callback);
  998. }
  999. $dir->close();
  1000. return drupal_rmdir($path);
  1001. }
  1002. return file_unmanaged_delete($path);
  1003. }
  1004. /**
  1005. * Moves an uploaded file to a new location.
  1006. *
  1007. * PHP's move_uploaded_file() does not properly support streams if open_basedir
  1008. * is enabled, so this function fills that gap.
  1009. *
  1010. * Compatibility: normal paths and stream wrappers.
  1011. *
  1012. * @param $filename
  1013. * The filename of the uploaded file.
  1014. * @param $uri
  1015. * A string containing the destination URI of the file.
  1016. *
  1017. * @return
  1018. * TRUE on success, or FALSE on failure.
  1019. *
  1020. * @see move_uploaded_file()
  1021. * @see http://drupal.org/node/515192
  1022. * @ingroup php_wrappers
  1023. */
  1024. function drupal_move_uploaded_file($filename, $uri) {
  1025. $result = @move_uploaded_file($filename, $uri);
  1026. // PHP's move_uploaded_file() does not properly support streams if
  1027. // open_basedir is enabled so if the move failed, try finding a real path and
  1028. // retry the move operation.
  1029. if (!$result) {
  1030. if ($realpath = drupal_realpath($uri)) {
  1031. $result = move_uploaded_file($filename, $realpath);
  1032. }
  1033. else {
  1034. $result = move_uploaded_file($filename, $uri);
  1035. }
  1036. }
  1037. return $result;
  1038. }
  1039. /**
  1040. * Saves a file to the specified destination without invoking file API.
  1041. *
  1042. * This function is identical to file_save_data() except the file will not be
  1043. * saved to the {file_managed} table and none of the file_* hooks will be
  1044. * called.
  1045. *
  1046. * @param $data
  1047. * A string containing the contents of the file.
  1048. * @param $destination
  1049. * A string containing the destination location. This must be a stream wrapper
  1050. * URI. If no value is provided, a randomized name will be generated and the
  1051. * file will be saved using Drupal's default files scheme, usually
  1052. * "public://".
  1053. * @param $replace
  1054. * Replace behavior when the destination file already exists:
  1055. * - FILE_EXISTS_REPLACE - Replace the existing file.
  1056. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  1057. * unique.
  1058. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  1059. *
  1060. * @return
  1061. * A string with the path of the resulting file, or FALSE on error.
  1062. *
  1063. * @see file_save_data()
  1064. */
  1065. function file_unmanaged_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  1066. // Write the data to a temporary file.
  1067. $temp_name = drupal_tempnam('temporary://', 'file');
  1068. if (file_put_contents($temp_name, $data) === FALSE) {
  1069. drupal_set_message(t('The file could not be created.'), 'error');
  1070. return FALSE;
  1071. }
  1072. // Move the file to its final destination.
  1073. return file_unmanaged_move($temp_name, $destination, $replace);
  1074. }
  1075. /**
  1076. * Finds all files that match a given mask in a given directory.
  1077. *
  1078. * Directories and files beginning with a dot are excluded; this prevents
  1079. * hidden files and directories (such as SVN working directories) from being
  1080. * scanned. Use the umask option to skip configuration directories to
  1081. * eliminate the possibility of accidentally exposing configuration
  1082. * information. Also, you can use the base directory, recurse, and min_depth
  1083. * options to improve performance by limiting how much of the filesystem has
  1084. * to be traversed.
  1085. *
  1086. * @param $dir
  1087. * The base directory or URI to scan, without trailing slash.
  1088. * @param $mask
  1089. * The preg_match() regular expression for files to be included.
  1090. * @param $options
  1091. * An associative array of additional options, with the following elements:
  1092. * - 'nomask': The preg_match() regular expression for files to be excluded.
  1093. * There is no default.
  1094. * - 'callback': The callback function to call for each match. There is no
  1095. * default callback.
  1096. * - 'recurse': When TRUE, the directory scan will recurse the entire tree
  1097. * starting at the provided directory. Defaults to TRUE.
  1098. * - 'key': The key to be used for the returned associative array of files.
  1099. * Possible values are 'uri', for the file's URI; 'filename', for the
  1100. * basename of the file; and 'name' for the name of the file without the
  1101. * extension. Defaults to 'uri'.
  1102. * - 'min_depth': Minimum depth of directories to return files from. Defaults
  1103. * to 0.
  1104. * @param $depth
  1105. * The current depth of recursion. This parameter is only used internally and
  1106. * should not be passed in.
  1107. *
  1108. * @return
  1109. * An associative array (keyed on the chosen key) of objects with 'uri',
  1110. * 'filename', and 'name' properties corresponding to the matched files.
  1111. */
  1112. function file_scan_directory($dir, $mask, $options = array(), $depth = 0) {
  1113. // Merge in defaults.
  1114. $options += array(
  1115. 'callback' => 0,
  1116. 'recurse' => TRUE,
  1117. 'key' => 'uri',
  1118. 'min_depth' => 0,
  1119. );
  1120. // Normalize $dir only once.
  1121. if ($depth == 0) {
  1122. $dir = file_stream_wrapper_uri_normalize($dir);
  1123. $dir_has_slash = (substr($dir, -1) === '/');
  1124. }
  1125. $options['key'] = in_array($options['key'], array('uri', 'filename', 'name')) ? $options['key'] : 'uri';
  1126. $files = array();
  1127. // Avoid warnings when opendir does not have the permissions to open a
  1128. // directory.
  1129. if (is_dir($dir)) {
  1130. if ($handle = @opendir($dir)) {
  1131. while (FALSE !== ($filename = readdir($handle))) {
  1132. // Skip this file if it matches the nomask or starts with a dot.
  1133. if ($filename[0] != '.' && !(isset($options['nomask']) && preg_match($options['nomask'], $filename))) {
  1134. if ($depth == 0 && $dir_has_slash) {
  1135. $uri = "$dir$filename";
  1136. }
  1137. else {
  1138. $uri = "$dir/$filename";
  1139. }
  1140. if ($options['recurse'] && is_dir($uri)) {
  1141. // Give priority to files in this folder by merging them in after
  1142. // any subdirectory files.
  1143. $files = array_merge(file_scan_directory($uri, $mask, $options, $depth + 1), $files);
  1144. }
  1145. elseif ($depth >= $options['min_depth'] && preg_match($mask, $filename)) {
  1146. // Always use this match over anything already set in $files with
  1147. // the same $options['key'].
  1148. $file = new stdClass();
  1149. $file->uri = $uri;
  1150. $file->filename = $filename;
  1151. $file->name = pathinfo($filename, PATHINFO_FILENAME);
  1152. $key = $options['key'];
  1153. $files[$file->$key] = $file;
  1154. if ($options['callback']) {
  1155. $options['callback']($uri);
  1156. }
  1157. }
  1158. }
  1159. }
  1160. closedir($handle);
  1161. }
  1162. else {
  1163. \Drupal::logger('file')->error('@dir can not be opened', array('@dir' => $dir));
  1164. }
  1165. }
  1166. return $files;
  1167. }
  1168. /**
  1169. * Determines the maximum file upload size by querying the PHP settings.
  1170. *
  1171. * @return
  1172. * A file size limit in bytes based on the PHP upload_max_filesize and
  1173. * post_max_size
  1174. */
  1175. function file_upload_max_size() {
  1176. static $max_size = -1;
  1177. if ($max_size < 0) {
  1178. // Start with post_max_size.
  1179. $max_size = Bytes::toInt(ini_get('post_max_size'));
  1180. // If upload_max_size is less, then reduce. Except if upload_max_size is
  1181. // zero, which indicates no limit.
  1182. $upload_max = Bytes::toInt(ini_get('upload_max_filesize'));
  1183. if ($upload_max > 0 && $upload_max < $max_size) {
  1184. $max_size = $upload_max;
  1185. }
  1186. }
  1187. return $max_size;
  1188. }
  1189. /**
  1190. * Determines an Internet Media Type or MIME type from a filename.
  1191. *
  1192. * @param $uri
  1193. * A string containing the URI, path, or filename.
  1194. * @param $mapping
  1195. * An optional map of extensions to their mimetypes, in the form:
  1196. * - 'mimetypes': a list of mimetypes, keyed by an identifier,
  1197. * - 'extensions': the mapping itself, an associative array in which the key
  1198. * is the extension (lowercase) and the value is the mimetype identifier.
  1199. *
  1200. * @return
  1201. * The internet media type registered for the extension or
  1202. * application/octet-stream for unknown extensions.
  1203. *
  1204. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0. Calls are
  1205. * passed on to a new file.mime_type.guesser service, and the $mapping
  1206. * parameter is ignored. Use
  1207. * \Drupal::service('file.mime_type.guesser')->guess($uri).
  1208. *
  1209. * @see \Drupal\Core\File\MimeType\ExtensionMimeTypeGuesser::guess()
  1210. */
  1211. function file_get_mimetype($uri, $mapping = NULL) {
  1212. return \Drupal::service('file.mime_type.guesser')->guess($uri);
  1213. }
  1214. /**
  1215. * Sets the permissions on a file or directory.
  1216. *
  1217. * This function will use the file_chmod_directory and
  1218. * file_chmod_file settings for the default modes for directories
  1219. * and uploaded/generated files. By default these will give everyone read access
  1220. * so that users accessing the files with a user account without the webserver
  1221. * group (e.g. via FTP) can read these files, and give group write permissions
  1222. * so webserver group members (e.g. a vhost account) can alter files uploaded
  1223. * and owned by the webserver.
  1224. *
  1225. * PHP's chmod does not support stream wrappers so we use our wrapper
  1226. * implementation which interfaces with chmod() by default. Contrib wrappers
  1227. * may override this behavior in their implementations as needed.
  1228. *
  1229. * @param $uri
  1230. * A string containing a URI file, or directory path.
  1231. * @param $mode
  1232. * Integer value for the permissions. Consult PHP chmod() documentation for
  1233. * more information.
  1234. *
  1235. * @return bool
  1236. * TRUE for success, FALSE in the event of an error.
  1237. *
  1238. * @ingroup php_wrappers
  1239. */
  1240. function drupal_chmod($uri, $mode = NULL) {
  1241. if (!isset($mode)) {
  1242. if (is_dir($uri)) {
  1243. $mode = Settings::get('file_chmod_directory', FILE_CHMOD_DIRECTORY);
  1244. }
  1245. else {
  1246. $mode = Settings::get('file_chmod_file', FILE_CHMOD_FILE);
  1247. }
  1248. }
  1249. if (@chmod($uri, $mode)) {
  1250. return TRUE;
  1251. }
  1252. \Drupal::logger('file')->error('The file permissions could not be set on %uri.', array('%uri' => $uri));
  1253. return FALSE;
  1254. }
  1255. /**
  1256. * Deletes a file.
  1257. *
  1258. * PHP's unlink() is broken on Windows, as it can fail to remove a file
  1259. * when it has a read-only flag set.
  1260. *
  1261. * @param $uri
  1262. * A URI or pathname.
  1263. * @param $context
  1264. * Refer to http://php.net/manual/ref.stream.php
  1265. *
  1266. * @return
  1267. * Boolean TRUE on success, or FALSE on failure.
  1268. *
  1269. * @see unlink()
  1270. * @ingroup php_wrappers
  1271. */
  1272. function drupal_unlink($uri, $context = NULL) {
  1273. $scheme = file_uri_scheme($uri);
  1274. if (!file_stream_wrapper_valid_scheme($scheme) && (substr(PHP_OS, 0, 3) == 'WIN')) {
  1275. chmod($uri, 0600);
  1276. }
  1277. if ($context) {
  1278. return unlink($uri, $context);
  1279. }
  1280. else {
  1281. return unlink($uri);
  1282. }
  1283. }
  1284. /**
  1285. * Resolves the absolute filepath of a local URI or filepath.
  1286. *
  1287. * The use of drupal_realpath() is discouraged, because it does not work for
  1288. * remote URIs. Except in rare cases, URIs should not be manually resolved.
  1289. *
  1290. * Only use this function if you know that the stream wrapper in the URI uses
  1291. * the local file system, and you need to pass an absolute path to a function
  1292. * that is incompatible with stream URIs.
  1293. *
  1294. * @param string $uri
  1295. * A stream wrapper URI or a filepath, possibly including one or more symbolic
  1296. * links.
  1297. *
  1298. * @return string|false
  1299. * The absolute local filepath (with no symbolic links), or FALSE on failure.
  1300. *
  1301. * @see \Drupal\Core\StreamWrapper\StreamWrapperInterface::realpath()
  1302. * @see http://php.net/manual/function.realpath.php
  1303. * @ingroup php_wrappers
  1304. */
  1305. function drupal_realpath($uri) {
  1306. // If this URI is a stream, pass it off to the appropriate stream wrapper.
  1307. // Otherwise, attempt PHP's realpath. This allows use of drupal_realpath even
  1308. // for unmanaged files outside of the stream wrapper interface.
  1309. if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
  1310. return $wrapper->realpath();
  1311. }
  1312. return realpath($uri);
  1313. }
  1314. /**
  1315. * Gets the name of the directory from a given path.
  1316. *
  1317. * PHP's dirname() does not properly pass streams, so this function fills
  1318. * that gap. It is backwards compatible with normal paths and will use
  1319. * PHP's dirname() as a fallback.
  1320. *
  1321. * Compatibility: normal paths and stream wrappers.
  1322. *
  1323. * @param $uri
  1324. * A URI or path.
  1325. *
  1326. * @return
  1327. * A string containing the directory name.
  1328. *
  1329. * @see dirname()
  1330. * @see http://drupal.org/node/515192
  1331. * @ingroup php_wrappers
  1332. */
  1333. function drupal_dirname($uri) {
  1334. $scheme = file_uri_scheme($uri);
  1335. if (file_stream_wrapper_valid_scheme($scheme)) {
  1336. return file_stream_wrapper_get_instance_by_scheme($scheme)->dirname($uri);
  1337. }
  1338. else {
  1339. return dirname($uri);
  1340. }
  1341. }
  1342. /**
  1343. * Gets the filename from a given path.
  1344. *
  1345. * PHP's basename() does not properly support streams or filenames beginning
  1346. * with a non-US-ASCII character.
  1347. *
  1348. * @see http://bugs.php.net/bug.php?id=37738
  1349. * @see basename()
  1350. *
  1351. * @ingroup php_wrappers
  1352. */
  1353. function drupal_basename($uri, $suffix = NULL) {
  1354. $separators = '/';
  1355. if (DIRECTORY_SEPARATOR != '/') {
  1356. // For Windows OS add special separator.
  1357. $separators .= DIRECTORY_SEPARATOR;
  1358. }
  1359. // Remove right-most slashes when $uri points to directory.
  1360. $uri = rtrim($uri, $separators);
  1361. // Returns the trailing part of the $uri starting after one of the directory
  1362. // separators.
  1363. $filename = preg_match('@[^' . preg_quote($separators, '@') . ']+$@', $uri, $matches) ? $matches[0] : '';
  1364. // Cuts off a suffix from the filename.
  1365. if ($suffix) {
  1366. $filename = preg_replace('@' . preg_quote($suffix, '@') . '$@', '', $filename);
  1367. }
  1368. return $filename;
  1369. }
  1370. /**
  1371. * Creates a directory, optionally creating missing components in the path to
  1372. * the directory.
  1373. *
  1374. * When PHP's mkdir() creates a directory, the requested mode is affected by the
  1375. * process's umask. This function overrides the umask and sets the mode
  1376. * explicitly for all directory components created.
  1377. *
  1378. * @param $uri
  1379. * A URI or pathname.
  1380. * @param $mode
  1381. * Mode given to created directories. Defaults to the directory mode
  1382. * configured in the Drupal installation. It must have a leading zero.
  1383. * @param $recursive
  1384. * Create directories recursively, defaults to FALSE. Cannot work with a mode
  1385. * which denies writing or execution to the owner of the process.
  1386. * @param $context
  1387. * Refer to http://php.net/manual/ref.stream.php
  1388. *
  1389. * @return
  1390. * Boolean TRUE on success, or FALSE on failure.
  1391. *
  1392. * @see mkdir()
  1393. * @see http://drupal.org/node/515192
  1394. * @ingroup php_wrappers
  1395. *
  1396. * @todo Update with open_basedir compatible recursion logic from
  1397. * \Drupal\Component\PhpStorage\FileStorage::ensureDirectory().
  1398. */
  1399. function drupal_mkdir($uri, $mode = NULL, $recursive = FALSE, $context = NULL) {
  1400. if (!isset($mode)) {
  1401. $mode = Settings::get('file_chmod_directory', FILE_CHMOD_DIRECTORY);
  1402. }
  1403. // If the URI has a scheme, don't override the umask - schemes can handle this
  1404. // issue in their own implementation.
  1405. if (file_uri_scheme($uri)) {
  1406. return _drupal_mkdir_call($uri, $mode, $recursive, $context);
  1407. }
  1408. // If recursive, create each missing component of the parent directory
  1409. // individually and set the mode explicitly to override the umask.
  1410. if ($recursive) {
  1411. // Ensure the path is using DIRECTORY_SEPARATOR.
  1412. $uri = str_replace('/', DIRECTORY_SEPARATOR, $uri);
  1413. // Determine the components of the path.
  1414. $components = explode(DIRECTORY_SEPARATOR, $uri);
  1415. // If the filepath is absolute the first component will be empty as there
  1416. // will be nothing before the first slash.
  1417. if ($components[0] == '') {
  1418. $recursive_path = DIRECTORY_SEPARATOR;
  1419. // Get rid of the empty first component.
  1420. array_shift($components);
  1421. }
  1422. else {
  1423. $recursive_path = '';
  1424. }
  1425. // Don't handle the top-level directory in this loop.
  1426. array_pop($components);
  1427. // Create each component if necessary.
  1428. foreach ($components as $component) {
  1429. $recursive_path .= $component;
  1430. if (!file_exists($recursive_path)) {
  1431. if (!_drupal_mkdir_call($recursive_path, $mode, FALSE, $context)) {
  1432. return FALSE;
  1433. }
  1434. // Not necessary to use drupal_chmod() as there is no scheme.
  1435. if (!chmod($recursive_path, $mode)) {
  1436. return FALSE;
  1437. }
  1438. }
  1439. $recursive_path .= DIRECTORY_SEPARATOR;
  1440. }
  1441. }
  1442. // Do not check if the top-level directory already exists, as this condition
  1443. // must cause this function to fail.
  1444. if (!_drupal_mkdir_call($uri, $mode, FALSE, $context)) {
  1445. return FALSE;
  1446. }
  1447. // Not necessary to use drupal_chmod() as there is no scheme.
  1448. return chmod($uri, $mode);
  1449. }
  1450. /**
  1451. * Helper function. Ensures we don't pass a NULL as a context resource to
  1452. * mkdir().
  1453. *
  1454. * @see drupal_mkdir()
  1455. */
  1456. function _drupal_mkdir_call($uri, $mode, $recursive, $context) {
  1457. if (is_null($context)) {
  1458. return mkdir($uri, $mode, $recursive);
  1459. }
  1460. else {
  1461. return mkdir($uri, $mode, $recursive, $context);
  1462. }
  1463. }
  1464. /**
  1465. * Removes a directory.
  1466. *
  1467. * PHP's rmdir() is broken on Windows, as it can fail to remove a directory
  1468. * when it has a read-only flag set.
  1469. *
  1470. * @param $uri
  1471. * A URI or pathname.
  1472. * @param $context
  1473. * Refer to http://php.net/manual/ref.stream.php
  1474. *
  1475. * @return
  1476. * Boolean TRUE on success, or FALSE on failure.
  1477. *
  1478. * @see rmdir()
  1479. * @ingroup php_wrappers
  1480. */
  1481. function drupal_rmdir($uri, $context = NULL) {
  1482. $scheme = file_uri_scheme($uri);
  1483. if (!file_stream_wrapper_valid_scheme($scheme) && (substr(PHP_OS, 0, 3) == 'WIN')) {
  1484. chmod($uri, 0700);
  1485. }
  1486. if ($context) {
  1487. return rmdir($uri, $context);
  1488. }
  1489. else {
  1490. return rmdir($uri);
  1491. }
  1492. }
  1493. /**
  1494. * Creates a file with a unique filename in the specified directory.
  1495. *
  1496. * PHP's tempnam() does not return a URI like we want. This function
  1497. * will return a URI if given a URI, or it will return a filepath if
  1498. * given a filepath.
  1499. *
  1500. * Compatibility: normal paths and stream wrappers.
  1501. *
  1502. * @param $directory
  1503. * The directory where the temporary filename will be created.
  1504. * @param $prefix
  1505. * The prefix of the generated temporary filename.
  1506. * Note: Windows uses only the first three characters of prefix.
  1507. *
  1508. * @return
  1509. * The new temporary filename, or FALSE on failure.
  1510. *
  1511. * @see tempnam()
  1512. * @see http://drupal.org/node/515192
  1513. * @ingroup php_wrappers
  1514. */
  1515. function drupal_tempnam($directory, $prefix) {
  1516. $scheme = file_uri_scheme($directory);
  1517. if (file_stream_wrapper_valid_scheme($scheme)) {
  1518. $wrapper = file_stream_wrapper_get_instance_by_scheme($scheme);
  1519. if ($filename = tempnam($wrapper->getDirectoryPath(), $prefix)) {
  1520. return $scheme . '://' . drupal_basename($filename);
  1521. }
  1522. else {
  1523. return FALSE;
  1524. }
  1525. }
  1526. else {
  1527. // Handle as a normal tempnam() call.
  1528. return tempnam($directory, $prefix);
  1529. }
  1530. }
  1531. /**
  1532. * Gets and sets the path of the configured temporary directory.
  1533. *
  1534. * @return mixed|null
  1535. * A string containing the path to the temporary directory.
  1536. */
  1537. function file_directory_temp() {
  1538. $config = \Drupal::config('system.file');
  1539. $temporary_directory = $config->get('path.temporary');
  1540. if (empty($temporary_directory)) {
  1541. $temporary_directory = file_directory_os_temp();
  1542. if (empty($temporary_directory)) {
  1543. // If no directory has been found default to 'files/tmp'.
  1544. $temporary_directory = PublicStream::basePath() . '/tmp';
  1545. // Windows accepts paths with either slash (/) or backslash (\), but will
  1546. // not accept a path which contains both a slash and a backslash. Since
  1547. // the 'file_public_path' variable may have either format, we sanitize
  1548. // everything to use slash which is supported on all platforms.
  1549. $temporary_directory = str_replace('\\', '/', $temporary_directory);
  1550. }
  1551. // Save the path of the discovered directory.
  1552. $config->set('path.temporary', $temporary_directory)->save();
  1553. }
  1554. return $temporary_directory;
  1555. }
  1556. /**
  1557. * Discovers a writable system-appropriate temporary directory.
  1558. *
  1559. * @return mixed
  1560. * A string containing the path to the temporary directory.
  1561. */
  1562. function file_directory_os_temp() {
  1563. $directories = array();
  1564. // Has PHP been set with an upload_tmp_dir?
  1565. if (ini_get('upload_tmp_dir')) {
  1566. $directories[] = ini_get('upload_tmp_dir');
  1567. }
  1568. // Operating system specific dirs.
  1569. if (substr(PHP_OS, 0, 3) == 'WIN') {
  1570. $directories[] = 'c:\\windows\\temp';
  1571. $directories[] = 'c:\\winnt\\temp';
  1572. }
  1573. else {
  1574. $directories[] = '/tmp';
  1575. }
  1576. // PHP may be able to find an alternative tmp directory.
  1577. $directories[] = sys_get_temp_dir();
  1578. foreach ($directories as $directory) {
  1579. if (is_dir($directory) && is_writable($directory)) {
  1580. return $directory;
  1581. }
  1582. }
  1583. return FALSE;
  1584. }
  1585. /**
  1586. * @} End of "defgroup file".
  1587. */