file.inc 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  1. <?php
  2. /**
  3. * @file
  4. * API for handling file uploads and server file management.
  5. */
  6. use Drupal\Component\FileSystem\FileSystem as ComponentFileSystem;
  7. use Drupal\Component\Utility\Unicode;
  8. use Drupal\Component\Utility\UrlHelper;
  9. use Drupal\Component\PhpStorage\FileStorage;
  10. use Drupal\Component\Utility\Bytes;
  11. use Drupal\Core\File\FileSystem;
  12. use Drupal\Core\Site\Settings;
  13. use Drupal\Core\StreamWrapper\PublicStream;
  14. use Drupal\Core\StreamWrapper\PrivateStream;
  15. /**
  16. * Default mode for new directories. See drupal_chmod().
  17. *
  18. * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  19. * Use \Drupal\Core\File\FileSystem::CHMOD_DIRECTORY.
  20. */
  21. const FILE_CHMOD_DIRECTORY = FileSystem::CHMOD_DIRECTORY;
  22. /**
  23. * Default mode for new files. See drupal_chmod().
  24. *
  25. * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  26. * Use \Drupal\Core\File\FileSystem::CHMOD_FILE.
  27. */
  28. const FILE_CHMOD_FILE = FileSystem::CHMOD_FILE;
  29. /**
  30. * @defgroup file File interface
  31. * @{
  32. * Common file handling functions.
  33. */
  34. /**
  35. * Flag used by file_prepare_directory() -- create directory if not present.
  36. */
  37. const FILE_CREATE_DIRECTORY = 1;
  38. /**
  39. * Flag used by file_prepare_directory() -- file permissions may be changed.
  40. */
  41. const FILE_MODIFY_PERMISSIONS = 2;
  42. /**
  43. * Flag for dealing with existing files: Appends number until name is unique.
  44. */
  45. const FILE_EXISTS_RENAME = 0;
  46. /**
  47. * Flag for dealing with existing files: Replace the existing file.
  48. */
  49. const FILE_EXISTS_REPLACE = 1;
  50. /**
  51. * Flag for dealing with existing files: Do nothing and return FALSE.
  52. */
  53. const FILE_EXISTS_ERROR = 2;
  54. /**
  55. * Indicates that the file is permanent and should not be deleted.
  56. *
  57. * Temporary files older than the system.file.temporary_maximum_age
  58. * configuration value will be, if clean-up not disabled, removed during cron
  59. * runs, but permanent files will not be removed during the file garbage
  60. * collection process.
  61. */
  62. const FILE_STATUS_PERMANENT = 1;
  63. /**
  64. * Returns the scheme of a URI (e.g. a stream).
  65. *
  66. * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  67. * Use \Drupal\Core\File\FileSystem::uriScheme().
  68. */
  69. function file_uri_scheme($uri) {
  70. return \Drupal::service('file_system')->uriScheme($uri);
  71. }
  72. /**
  73. * Checks that the scheme of a stream URI is valid.
  74. *
  75. * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  76. * Use \Drupal\Core\File\FileSystem::validScheme().
  77. */
  78. function file_stream_wrapper_valid_scheme($scheme) {
  79. return \Drupal::service('file_system')->validScheme($scheme);
  80. }
  81. /**
  82. * Returns the part of a URI after the schema.
  83. *
  84. * @param string $uri
  85. * A stream, referenced as "scheme://target" or "data:target".
  86. *
  87. * @return string|bool
  88. * A string containing the target (path), or FALSE if none.
  89. * For example, the URI "public://sample/test.txt" would return
  90. * "sample/test.txt".
  91. *
  92. * @see file_uri_scheme()
  93. */
  94. function file_uri_target($uri) {
  95. // Remove the scheme from the URI and remove erroneous leading or trailing,
  96. // forward-slashes and backslashes.
  97. $target = trim(preg_replace('/^[\w\-]+:\/\/|^data:/', '', $uri), '\/');
  98. // If nothing was replaced, the URI doesn't have a valid scheme.
  99. return $target !== $uri ? $target : FALSE;
  100. }
  101. /**
  102. * Gets the default file stream implementation.
  103. *
  104. * @return string
  105. * 'public', 'private' or any other file scheme defined as the default.
  106. */
  107. function file_default_scheme() {
  108. return \Drupal::config('system.file')->get('default_scheme');
  109. }
  110. /**
  111. * Normalizes a URI by making it syntactically correct.
  112. *
  113. * A stream is referenced as "scheme://target".
  114. *
  115. * The following actions are taken:
  116. * - Remove trailing slashes from target
  117. * - Trim erroneous leading slashes from target. e.g. ":///" becomes "://".
  118. *
  119. * @param string $uri
  120. * String reference containing the URI to normalize.
  121. *
  122. * @return string
  123. * The normalized URI.
  124. */
  125. function file_stream_wrapper_uri_normalize($uri) {
  126. $scheme = \Drupal::service('file_system')->uriScheme($uri);
  127. if (file_stream_wrapper_valid_scheme($scheme)) {
  128. $target = file_uri_target($uri);
  129. if ($target !== FALSE) {
  130. $uri = $scheme . '://' . $target;
  131. }
  132. }
  133. return $uri;
  134. }
  135. /**
  136. * Creates a web-accessible URL for a stream to an external or local file.
  137. *
  138. * Compatibility: normal paths and stream wrappers.
  139. *
  140. * There are two kinds of local files:
  141. * - "managed files", i.e. those stored by a Drupal-compatible stream wrapper.
  142. * These are files that have either been uploaded by users or were generated
  143. * automatically (for example through CSS aggregation).
  144. * - "shipped files", i.e. those outside of the files directory, which ship as
  145. * part of Drupal core or contributed modules or themes.
  146. *
  147. * @param string $uri
  148. * The URI to a file for which we need an external URL, or the path to a
  149. * shipped file.
  150. *
  151. * @return string
  152. * A string containing a URL that may be used to access the file.
  153. * If the provided string already contains a preceding 'http', 'https', or
  154. * '/', nothing is done and the same string is returned. If a stream wrapper
  155. * could not be found to generate an external URL, then FALSE is returned.
  156. *
  157. * @see https://www.drupal.org/node/515192
  158. * @see file_url_transform_relative()
  159. */
  160. function file_create_url($uri) {
  161. // Allow the URI to be altered, e.g. to serve a file from a CDN or static
  162. // file server.
  163. \Drupal::moduleHandler()->alter('file_url', $uri);
  164. $scheme = \Drupal::service('file_system')->uriScheme($uri);
  165. if (!$scheme) {
  166. // Allow for:
  167. // - root-relative URIs (e.g. /foo.jpg in http://example.com/foo.jpg)
  168. // - protocol-relative URIs (e.g. //bar.jpg, which is expanded to
  169. // http://example.com/bar.jpg by the browser when viewing a page over
  170. // HTTP and to https://example.com/bar.jpg when viewing a HTTPS page)
  171. // Both types of relative URIs are characterized by a leading slash, hence
  172. // we can use a single check.
  173. if (Unicode::substr($uri, 0, 1) == '/') {
  174. return $uri;
  175. }
  176. else {
  177. // If this is not a properly formatted stream, then it is a shipped file.
  178. // Therefore, return the urlencoded URI with the base URL prepended.
  179. $options = UrlHelper::parse($uri);
  180. $path = $GLOBALS['base_url'] . '/' . UrlHelper::encodePath($options['path']);
  181. // Append the query.
  182. if ($options['query']) {
  183. $path .= '?' . UrlHelper::buildQuery($options['query']);
  184. }
  185. // Append fragment.
  186. if ($options['fragment']) {
  187. $path .= '#' . $options['fragment'];
  188. }
  189. return $path;
  190. }
  191. }
  192. elseif ($scheme == 'http' || $scheme == 'https' || $scheme == 'data') {
  193. // Check for HTTP and data URI-encoded URLs so that we don't have to
  194. // implement getExternalUrl() for the HTTP and data schemes.
  195. return $uri;
  196. }
  197. else {
  198. // Attempt to return an external URL using the appropriate wrapper.
  199. if ($wrapper = \Drupal::service('stream_wrapper_manager')->getViaUri($uri)) {
  200. return $wrapper->getExternalUrl();
  201. }
  202. else {
  203. return FALSE;
  204. }
  205. }
  206. }
  207. /**
  208. * Transforms an absolute URL of a local file to a relative URL.
  209. *
  210. * May be useful to prevent problems on multisite set-ups and prevent mixed
  211. * content errors when using HTTPS + HTTP.
  212. *
  213. * @param string $file_url
  214. * A file URL of a local file as generated by file_create_url().
  215. *
  216. * @return string
  217. * If the file URL indeed pointed to a local file and was indeed absolute,
  218. * then the transformed, relative URL to the local file. Otherwise: the
  219. * original value of $file_url.
  220. *
  221. * @see file_create_url()
  222. */
  223. function file_url_transform_relative($file_url) {
  224. // Unfortunately, we pretty much have to duplicate Symfony's
  225. // Request::getHttpHost() method because Request::getPort() may return NULL
  226. // instead of a port number.
  227. $request = \Drupal::request();
  228. $host = $request->getHost();
  229. $scheme = $request->getScheme();
  230. $port = $request->getPort() ?: 80;
  231. if (('http' == $scheme && $port == 80) || ('https' == $scheme && $port == 443)) {
  232. $http_host = $host;
  233. }
  234. else {
  235. $http_host = $host . ':' . $port;
  236. }
  237. return preg_replace('|^https?://' . $http_host . '|', '', $file_url);
  238. }
  239. /**
  240. * Checks that the directory exists and is writable.
  241. *
  242. * Directories need to have execute permissions to be considered a directory by
  243. * FTP servers, etc.
  244. *
  245. * @param $directory
  246. * A string reference containing the name of a directory path or URI. A
  247. * trailing slash will be trimmed from a path.
  248. * @param $options
  249. * A bitmask to indicate if the directory should be created if it does
  250. * not exist (FILE_CREATE_DIRECTORY) or made writable if it is read-only
  251. * (FILE_MODIFY_PERMISSIONS).
  252. *
  253. * @return
  254. * TRUE if the directory exists (or was created) and is writable. FALSE
  255. * otherwise.
  256. */
  257. function file_prepare_directory(&$directory, $options = FILE_MODIFY_PERMISSIONS) {
  258. if (!file_stream_wrapper_valid_scheme(\Drupal::service('file_system')->uriScheme($directory))) {
  259. // Only trim if we're not dealing with a stream.
  260. $directory = rtrim($directory, '/\\');
  261. }
  262. // Check if directory exists.
  263. if (!is_dir($directory)) {
  264. // Let mkdir() recursively create directories and use the default directory
  265. // permissions.
  266. if ($options & FILE_CREATE_DIRECTORY) {
  267. return @drupal_mkdir($directory, NULL, TRUE);
  268. }
  269. return FALSE;
  270. }
  271. // The directory exists, so check to see if it is writable.
  272. $writable = is_writable($directory);
  273. if (!$writable && ($options & FILE_MODIFY_PERMISSIONS)) {
  274. return drupal_chmod($directory);
  275. }
  276. return $writable;
  277. }
  278. /**
  279. * Creates a .htaccess file in each Drupal files directory if it is missing.
  280. */
  281. function file_ensure_htaccess() {
  282. file_save_htaccess('public://', FALSE);
  283. $private_path = PrivateStream::basePath();
  284. if (!empty($private_path)) {
  285. file_save_htaccess('private://', TRUE);
  286. }
  287. file_save_htaccess('temporary://', TRUE);
  288. // If a staging directory exists then it should contain a .htaccess file.
  289. // @todo https://www.drupal.org/node/2696103 catch a more specific exception
  290. // and simplify this code.
  291. try {
  292. $staging = config_get_config_directory(CONFIG_SYNC_DIRECTORY);
  293. }
  294. catch (\Exception $e) {
  295. $staging = FALSE;
  296. }
  297. if ($staging) {
  298. // Note that we log an error here if we can't write the .htaccess file. This
  299. // can occur if the staging directory is read-only. If it is then it is the
  300. // user's responsibility to create the .htaccess file.
  301. file_save_htaccess($staging, TRUE);
  302. }
  303. }
  304. /**
  305. * Creates a .htaccess file in the given directory.
  306. *
  307. * @param string $directory
  308. * The directory.
  309. * @param bool $private
  310. * (Optional) FALSE indicates that $directory should be a web-accessible
  311. * directory. Defaults to TRUE which indicates a private directory.
  312. * @param bool $force_overwrite
  313. * (Optional) Set to TRUE to attempt to overwrite the existing .htaccess file
  314. * if one is already present. Defaults to FALSE.
  315. */
  316. function file_save_htaccess($directory, $private = TRUE, $force_overwrite = FALSE) {
  317. if (\Drupal::service('file_system')->uriScheme($directory)) {
  318. $htaccess_path = file_stream_wrapper_uri_normalize($directory . '/.htaccess');
  319. }
  320. else {
  321. $directory = rtrim($directory, '/\\');
  322. $htaccess_path = $directory . '/.htaccess';
  323. }
  324. if (file_exists($htaccess_path) && !$force_overwrite) {
  325. // Short circuit if the .htaccess file already exists.
  326. return TRUE;
  327. }
  328. $htaccess_lines = FileStorage::htaccessLines($private);
  329. // Write the .htaccess file.
  330. if (file_exists($directory) && is_writable($directory) && file_put_contents($htaccess_path, $htaccess_lines)) {
  331. return drupal_chmod($htaccess_path, 0444);
  332. }
  333. else {
  334. $variables = ['%directory' => $directory, '@htaccess' => $htaccess_lines];
  335. \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: <pre><code>@htaccess</code></pre>", $variables);
  336. return FALSE;
  337. }
  338. }
  339. /**
  340. * Returns the standard .htaccess lines that Drupal writes to file directories.
  341. *
  342. * @param bool $private
  343. * (Optional) Set to FALSE to return the .htaccess lines for a web-accessible
  344. * public directory. The default is TRUE, which returns the .htaccess lines
  345. * for a private directory that should not be web-accessible.
  346. *
  347. * @return string
  348. * The desired contents of the .htaccess file.
  349. *
  350. * @deprecated in Drupal 8.0.x-dev and will be removed before Drupal 9.0.0.
  351. * Use \Drupal\Component\PhpStorage\FileStorage::htaccessLines().
  352. */
  353. function file_htaccess_lines($private = TRUE) {
  354. return FileStorage::htaccessLines($private);
  355. }
  356. /**
  357. * Determines whether the URI has a valid scheme for file API operations.
  358. *
  359. * There must be a scheme and it must be a Drupal-provided scheme like
  360. * 'public', 'private', 'temporary', or an extension provided with
  361. * hook_stream_wrappers().
  362. *
  363. * @param $uri
  364. * The URI to be tested.
  365. *
  366. * @return
  367. * TRUE if the URI is allowed.
  368. */
  369. function file_valid_uri($uri) {
  370. // Assert that the URI has an allowed scheme. Bare paths are not allowed.
  371. $uri_scheme = \Drupal::service('file_system')->uriScheme($uri);
  372. if (!file_stream_wrapper_valid_scheme($uri_scheme)) {
  373. return FALSE;
  374. }
  375. return TRUE;
  376. }
  377. /**
  378. * Copies a file to a new location without database changes or hook invocation.
  379. *
  380. * This is a powerful function that in many ways performs like an advanced
  381. * version of copy().
  382. * - Checks if $source and $destination are valid and readable/writable.
  383. * - If file already exists in $destination either the call will error out,
  384. * replace the file or rename the file based on the $replace parameter.
  385. * - If the $source and $destination are equal, the behavior depends on the
  386. * $replace parameter. FILE_EXISTS_REPLACE will error out. FILE_EXISTS_RENAME
  387. * will rename the file until the $destination is unique.
  388. * - Works around a PHP bug where copy() does not properly support streams if
  389. * safe_mode or open_basedir are enabled.
  390. * @see https://bugs.php.net/bug.php?id=60456
  391. *
  392. * @param $source
  393. * A string specifying the filepath or URI of the source file.
  394. * @param $destination
  395. * A URI containing the destination that $source should be copied to. The
  396. * URI may be a bare filepath (without a scheme). If this value is omitted,
  397. * Drupal's default files scheme will be used, usually "public://".
  398. * @param $replace
  399. * Replace behavior when the destination file already exists:
  400. * - FILE_EXISTS_REPLACE - Replace the existing file.
  401. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  402. * unique.
  403. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  404. *
  405. * @return
  406. * The path to the new file, or FALSE in the event of an error.
  407. *
  408. * @see file_copy()
  409. */
  410. function file_unmanaged_copy($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  411. if (!file_unmanaged_prepare($source, $destination, $replace)) {
  412. return FALSE;
  413. }
  414. // Attempt to resolve the URIs. This is necessary in certain configurations
  415. // (see above).
  416. $real_source = drupal_realpath($source) ?: $source;
  417. $real_destination = drupal_realpath($destination) ?: $destination;
  418. // Perform the copy operation.
  419. if (!@copy($real_source, $real_destination)) {
  420. \Drupal::logger('file')->error('The specified file %file could not be copied to %destination.', ['%file' => $source, '%destination' => $destination]);
  421. return FALSE;
  422. }
  423. // Set the permissions on the new file.
  424. drupal_chmod($destination);
  425. return $destination;
  426. }
  427. /**
  428. * Internal function that prepares the destination for a file_unmanaged_copy or
  429. * file_unmanaged_move operation.
  430. *
  431. * - Checks if $source and $destination are valid and readable/writable.
  432. * - Checks that $source is not equal to $destination; if they are an error
  433. * is reported.
  434. * - If file already exists in $destination either the call will error out,
  435. * replace the file or rename the file based on the $replace parameter.
  436. *
  437. * @param $source
  438. * A string specifying the filepath or URI of the source file.
  439. * @param $destination
  440. * A URI containing the destination that $source should be moved/copied to.
  441. * The URI may be a bare filepath (without a scheme) and in that case the
  442. * default scheme (file://) will be used. If this value is omitted, Drupal's
  443. * default files scheme will be used, usually "public://".
  444. * @param $replace
  445. * Replace behavior when the destination file already exists:
  446. * - FILE_EXISTS_REPLACE - Replace the existing file.
  447. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  448. * unique.
  449. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  450. *
  451. * @return
  452. * TRUE, or FALSE in the event of an error.
  453. *
  454. * @see file_unmanaged_copy()
  455. * @see file_unmanaged_move()
  456. */
  457. function file_unmanaged_prepare($source, &$destination = NULL, $replace = FILE_EXISTS_RENAME) {
  458. $original_source = $source;
  459. $logger = \Drupal::logger('file');
  460. // Assert that the source file actually exists.
  461. if (!file_exists($source)) {
  462. // @todo Replace drupal_set_message() calls with exceptions instead.
  463. drupal_set_message(t('The specified file %file could not be moved/copied because no file by that name exists. Please check that you supplied the correct filename.', ['%file' => $original_source]), 'error');
  464. if (($realpath = drupal_realpath($original_source)) !== FALSE) {
  465. $logger->notice('File %file (%realpath) could not be moved/copied because it does not exist.', ['%file' => $original_source, '%realpath' => $realpath]);
  466. }
  467. else {
  468. $logger->notice('File %file could not be moved/copied because it does not exist.', ['%file' => $original_source]);
  469. }
  470. return FALSE;
  471. }
  472. // Build a destination URI if necessary.
  473. if (!isset($destination)) {
  474. $destination = file_build_uri(drupal_basename($source));
  475. }
  476. // Prepare the destination directory.
  477. if (file_prepare_directory($destination)) {
  478. // The destination is already a directory, so append the source basename.
  479. $destination = file_stream_wrapper_uri_normalize($destination . '/' . drupal_basename($source));
  480. }
  481. else {
  482. // Perhaps $destination is a dir/file?
  483. $dirname = drupal_dirname($destination);
  484. if (!file_prepare_directory($dirname)) {
  485. // The destination is not valid.
  486. $logger->notice('File %file could not be moved/copied because the destination directory %destination is not configured correctly.', ['%file' => $original_source, '%destination' => $dirname]);
  487. drupal_set_message(t('The specified file %file could not be moved/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.', ['%file' => $original_source]), 'error');
  488. return FALSE;
  489. }
  490. }
  491. // Determine whether we can perform this operation based on overwrite rules.
  492. $destination = file_destination($destination, $replace);
  493. if ($destination === FALSE) {
  494. drupal_set_message(t('The file %file could not be moved/copied because a file by that name already exists in the destination directory.', ['%file' => $original_source]), 'error');
  495. $logger->notice('File %file could not be moved/copied because a file by that name already exists in the destination directory (%destination)', ['%file' => $original_source, '%destination' => $destination]);
  496. return FALSE;
  497. }
  498. // Assert that the source and destination filenames are not the same.
  499. $real_source = drupal_realpath($source);
  500. $real_destination = drupal_realpath($destination);
  501. if ($source == $destination || ($real_source !== FALSE) && ($real_source == $real_destination)) {
  502. drupal_set_message(t('The specified file %file was not moved/copied because it would overwrite itself.', ['%file' => $source]), 'error');
  503. $logger->notice('File %file could not be moved/copied because it would overwrite itself.', ['%file' => $source]);
  504. return FALSE;
  505. }
  506. // Make sure the .htaccess files are present.
  507. file_ensure_htaccess();
  508. return TRUE;
  509. }
  510. /**
  511. * Constructs a URI to Drupal's default files location given a relative path.
  512. */
  513. function file_build_uri($path) {
  514. $uri = file_default_scheme() . '://' . $path;
  515. return file_stream_wrapper_uri_normalize($uri);
  516. }
  517. /**
  518. * Determines the destination path for a file.
  519. *
  520. * @param $destination
  521. * A string specifying the desired final URI or filepath.
  522. * @param $replace
  523. * Replace behavior when the destination file already exists.
  524. * - FILE_EXISTS_REPLACE - Replace the existing file.
  525. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  526. * unique.
  527. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  528. *
  529. * @return
  530. * The destination filepath, or FALSE if the file already exists
  531. * and FILE_EXISTS_ERROR is specified.
  532. */
  533. function file_destination($destination, $replace) {
  534. if (file_exists($destination)) {
  535. switch ($replace) {
  536. case FILE_EXISTS_REPLACE:
  537. // Do nothing here, we want to overwrite the existing file.
  538. break;
  539. case FILE_EXISTS_RENAME:
  540. $basename = drupal_basename($destination);
  541. $directory = drupal_dirname($destination);
  542. $destination = file_create_filename($basename, $directory);
  543. break;
  544. case FILE_EXISTS_ERROR:
  545. // Error reporting handled by calling function.
  546. return FALSE;
  547. }
  548. }
  549. return $destination;
  550. }
  551. /**
  552. * Moves a file to a new location without database changes or hook invocation.
  553. *
  554. * This is a powerful function that in many ways performs like an advanced
  555. * version of rename().
  556. * - Checks if $source and $destination are valid and readable/writable.
  557. * - Checks that $source is not equal to $destination; if they are an error
  558. * is reported.
  559. * - If file already exists in $destination either the call will error out,
  560. * replace the file or rename the file based on the $replace parameter.
  561. * - Works around a PHP bug where rename() does not properly support streams if
  562. * safe_mode or open_basedir are enabled.
  563. * @see https://bugs.php.net/bug.php?id=60456
  564. *
  565. * @param $source
  566. * A string specifying the filepath or URI of the source file.
  567. * @param $destination
  568. * A URI containing the destination that $source should be moved to. The
  569. * URI may be a bare filepath (without a scheme) and in that case the default
  570. * scheme (file://) will be used. If this value is omitted, Drupal's default
  571. * files scheme will be used, usually "public://".
  572. * @param $replace
  573. * Replace behavior when the destination file already exists:
  574. * - FILE_EXISTS_REPLACE - Replace the existing file.
  575. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  576. * unique.
  577. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  578. *
  579. * @return
  580. * The path to the new file, or FALSE in the event of an error.
  581. *
  582. * @see file_move()
  583. */
  584. function file_unmanaged_move($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  585. if (!file_unmanaged_prepare($source, $destination, $replace)) {
  586. return FALSE;
  587. }
  588. // Ensure compatibility with Windows.
  589. // @see drupal_unlink()
  590. if ((substr(PHP_OS, 0, 3) == 'WIN') && (!file_stream_wrapper_valid_scheme(file_uri_scheme($source)))) {
  591. chmod($source, 0600);
  592. }
  593. // Attempt to resolve the URIs. This is necessary in certain configurations
  594. // (see above) and can also permit fast moves across local schemes.
  595. $real_source = drupal_realpath($source) ?: $source;
  596. $real_destination = drupal_realpath($destination) ?: $destination;
  597. // Perform the move operation.
  598. if (!@rename($real_source, $real_destination)) {
  599. // Fall back to slow copy and unlink procedure. This is necessary for
  600. // renames across schemes that are not local, or where rename() has not been
  601. // implemented. It's not necessary to use drupal_unlink() as the Windows
  602. // issue has already been resolved above.
  603. if (!@copy($real_source, $real_destination) || !@unlink($real_source)) {
  604. \Drupal::logger('file')->error('The specified file %file could not be moved to %destination.', ['%file' => $source, '%destination' => $destination]);
  605. return FALSE;
  606. }
  607. }
  608. // Set the permissions on the new file.
  609. drupal_chmod($destination);
  610. return $destination;
  611. }
  612. /**
  613. * Modifies a filename as needed for security purposes.
  614. *
  615. * Munging a file name prevents unknown file extensions from masking exploit
  616. * files. When web servers such as Apache decide how to process a URL request,
  617. * they use the file extension. If the extension is not recognized, Apache
  618. * skips that extension and uses the previous file extension. For example, if
  619. * the file being requested is exploit.php.pps, and Apache does not recognize
  620. * the '.pps' extension, it treats the file as PHP and executes it. To make
  621. * this file name safe for Apache and prevent it from executing as PHP, the
  622. * .php extension is "munged" into .php_, making the safe file name
  623. * exploit.php_.pps.
  624. *
  625. * Specifically, this function adds an underscore to all extensions that are
  626. * between 2 and 5 characters in length, internal to the file name, and not
  627. * included in $extensions.
  628. *
  629. * Function behavior is also controlled by the configuration
  630. * 'system.file:allow_insecure_uploads'. If it evaluates to TRUE, no alterations
  631. * will be made, if it evaluates to FALSE, the filename is 'munged'. *
  632. * @param $filename
  633. * File name to modify.
  634. * @param $extensions
  635. * A space-separated list of extensions that should not be altered.
  636. * @param $alerts
  637. * If TRUE, drupal_set_message() will be called to display a message if the
  638. * file name was changed.
  639. *
  640. * @return string
  641. * The potentially modified $filename.
  642. */
  643. function file_munge_filename($filename, $extensions, $alerts = TRUE) {
  644. $original = $filename;
  645. // Allow potentially insecure uploads for very savvy users and admin
  646. if (!\Drupal::config('system.file')->get('allow_insecure_uploads')) {
  647. // Remove any null bytes. See
  648. // http://php.net/manual/security.filesystem.nullbytes.php
  649. $filename = str_replace(chr(0), '', $filename);
  650. $whitelist = array_unique(explode(' ', strtolower(trim($extensions))));
  651. // Split the filename up by periods. The first part becomes the basename
  652. // the last part the final extension.
  653. $filename_parts = explode('.', $filename);
  654. $new_filename = array_shift($filename_parts); // Remove file basename.
  655. $final_extension = array_pop($filename_parts); // Remove final extension.
  656. // Loop through the middle parts of the name and add an underscore to the
  657. // end of each section that could be a file extension but isn't in the list
  658. // of allowed extensions.
  659. foreach ($filename_parts as $filename_part) {
  660. $new_filename .= '.' . $filename_part;
  661. if (!in_array(strtolower($filename_part), $whitelist) && preg_match("/^[a-zA-Z]{2,5}\d?$/", $filename_part)) {
  662. $new_filename .= '_';
  663. }
  664. }
  665. $filename = $new_filename . '.' . $final_extension;
  666. if ($alerts && $original != $filename) {
  667. drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', ['%filename' => $filename]));
  668. }
  669. }
  670. return $filename;
  671. }
  672. /**
  673. * Undoes the effect of file_munge_filename().
  674. *
  675. * @param $filename
  676. * String with the filename to be unmunged.
  677. *
  678. * @return
  679. * An unmunged filename string.
  680. */
  681. function file_unmunge_filename($filename) {
  682. return str_replace('_.', '.', $filename);
  683. }
  684. /**
  685. * Creates a full file path from a directory and filename.
  686. *
  687. * If a file with the specified name already exists, an alternative will be
  688. * used.
  689. *
  690. * @param $basename
  691. * String filename
  692. * @param $directory
  693. * String containing the directory or parent URI.
  694. *
  695. * @return
  696. * File path consisting of $directory and a unique filename based off
  697. * of $basename.
  698. */
  699. function file_create_filename($basename, $directory) {
  700. // Strip control characters (ASCII value < 32). Though these are allowed in
  701. // some filesystems, not many applications handle them well.
  702. $basename = preg_replace('/[\x00-\x1F]/u', '_', $basename);
  703. if (substr(PHP_OS, 0, 3) == 'WIN') {
  704. // These characters are not allowed in Windows filenames
  705. $basename = str_replace([':', '*', '?', '"', '<', '>', '|'], '_', $basename);
  706. }
  707. // A URI or path may already have a trailing slash or look like "public://".
  708. if (substr($directory, -1) == '/') {
  709. $separator = '';
  710. }
  711. else {
  712. $separator = '/';
  713. }
  714. $destination = $directory . $separator . $basename;
  715. if (file_exists($destination)) {
  716. // Destination file already exists, generate an alternative.
  717. $pos = strrpos($basename, '.');
  718. if ($pos !== FALSE) {
  719. $name = substr($basename, 0, $pos);
  720. $ext = substr($basename, $pos);
  721. }
  722. else {
  723. $name = $basename;
  724. $ext = '';
  725. }
  726. $counter = 0;
  727. do {
  728. $destination = $directory . $separator . $name . '_' . $counter++ . $ext;
  729. } while (file_exists($destination));
  730. }
  731. return $destination;
  732. }
  733. /**
  734. * Deletes a file and its database record.
  735. *
  736. * Instead of directly deleting a file, it is strongly recommended to delete
  737. * file usages instead. That will automatically mark the file as temporary and
  738. * remove it during cleanup.
  739. *
  740. * @param $fid
  741. * The file id.
  742. *
  743. * @see file_unmanaged_delete()
  744. * @see \Drupal\file\FileUsage\FileUsageBase::delete()
  745. */
  746. function file_delete($fid) {
  747. return file_delete_multiple([$fid]);
  748. }
  749. /**
  750. * Deletes files.
  751. *
  752. * Instead of directly deleting a file, it is strongly recommended to delete
  753. * file usages instead. That will automatically mark the file as temporary and
  754. * remove it during cleanup.
  755. *
  756. * @param $fid
  757. * The file id.
  758. *
  759. * @see file_unmanaged_delete()
  760. * @see \Drupal\file\FileUsage\FileUsageBase::delete()
  761. */
  762. function file_delete_multiple(array $fids) {
  763. entity_delete_multiple('file', $fids);
  764. }
  765. /**
  766. * Deletes a file without database changes or hook invocations.
  767. *
  768. * This function should be used when the file to be deleted does not have an
  769. * entry recorded in the files table.
  770. *
  771. * @param $path
  772. * A string containing a file path or (streamwrapper) URI.
  773. *
  774. * @return
  775. * TRUE for success or path does not exist, or FALSE in the event of an
  776. * error.
  777. *
  778. * @see file_delete()
  779. * @see file_unmanaged_delete_recursive()
  780. */
  781. function file_unmanaged_delete($path) {
  782. if (is_file($path)) {
  783. return drupal_unlink($path);
  784. }
  785. $logger = \Drupal::logger('file');
  786. if (is_dir($path)) {
  787. $logger->error('%path is a directory and cannot be removed using file_unmanaged_delete().', ['%path' => $path]);
  788. return FALSE;
  789. }
  790. // Return TRUE for non-existent file, but log that nothing was actually
  791. // deleted, as the current state is the intended result.
  792. if (!file_exists($path)) {
  793. $logger->notice('The file %path was not deleted because it does not exist.', ['%path' => $path]);
  794. return TRUE;
  795. }
  796. // We cannot handle anything other than files and directories. Log an error
  797. // for everything else (sockets, symbolic links, etc).
  798. $logger->error('The file %path is not of a recognized type so it was not deleted.', ['%path' => $path]);
  799. return FALSE;
  800. }
  801. /**
  802. * Deletes all files and directories in the specified filepath recursively.
  803. *
  804. * If the specified path is a directory then the function will call itself
  805. * recursively to process the contents. Once the contents have been removed the
  806. * directory will also be removed.
  807. *
  808. * If the specified path is a file then it will be passed to
  809. * file_unmanaged_delete().
  810. *
  811. * Note that this only deletes visible files with write permission.
  812. *
  813. * @param $path
  814. * A string containing either an URI or a file or directory path.
  815. * @param $callback
  816. * (optional) Callback function to run on each file prior to deleting it and
  817. * on each directory prior to traversing it. For example, can be used to
  818. * modify permissions.
  819. *
  820. * @return
  821. * TRUE for success or if path does not exist, FALSE in the event of an
  822. * error.
  823. *
  824. * @see file_unmanaged_delete()
  825. */
  826. function file_unmanaged_delete_recursive($path, $callback = NULL) {
  827. if (isset($callback)) {
  828. call_user_func($callback, $path);
  829. }
  830. if (is_dir($path)) {
  831. $dir = dir($path);
  832. while (($entry = $dir->read()) !== FALSE) {
  833. if ($entry == '.' || $entry == '..') {
  834. continue;
  835. }
  836. $entry_path = $path . '/' . $entry;
  837. file_unmanaged_delete_recursive($entry_path, $callback);
  838. }
  839. $dir->close();
  840. return drupal_rmdir($path);
  841. }
  842. return file_unmanaged_delete($path);
  843. }
  844. /**
  845. * Moves an uploaded file to a new location.
  846. *
  847. * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  848. * Use \Drupal\Core\File\FileSystem::moveUploadedFile().
  849. */
  850. function drupal_move_uploaded_file($filename, $uri) {
  851. return \Drupal::service('file_system')->moveUploadedFile($filename, $uri);
  852. }
  853. /**
  854. * Saves a file to the specified destination without invoking file API.
  855. *
  856. * This function is identical to file_save_data() except the file will not be
  857. * saved to the {file_managed} table and none of the file_* hooks will be
  858. * called.
  859. *
  860. * @param $data
  861. * A string containing the contents of the file.
  862. * @param $destination
  863. * A string containing the destination location. This must be a stream wrapper
  864. * URI. If no value is provided, a randomized name will be generated and the
  865. * file will be saved using Drupal's default files scheme, usually
  866. * "public://".
  867. * @param $replace
  868. * Replace behavior when the destination file already exists:
  869. * - FILE_EXISTS_REPLACE - Replace the existing file.
  870. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  871. * unique.
  872. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  873. *
  874. * @return
  875. * A string with the path of the resulting file, or FALSE on error.
  876. *
  877. * @see file_save_data()
  878. */
  879. function file_unmanaged_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  880. // Write the data to a temporary file.
  881. $temp_name = drupal_tempnam('temporary://', 'file');
  882. if (file_put_contents($temp_name, $data) === FALSE) {
  883. drupal_set_message(t('The file could not be created.'), 'error');
  884. return FALSE;
  885. }
  886. // Move the file to its final destination.
  887. return file_unmanaged_move($temp_name, $destination, $replace);
  888. }
  889. /**
  890. * Finds all files that match a given mask in a given directory.
  891. *
  892. * Directories and files beginning with a dot are excluded; this prevents
  893. * hidden files and directories (such as SVN working directories) from being
  894. * scanned. Use the umask option to skip configuration directories to
  895. * eliminate the possibility of accidentally exposing configuration
  896. * information. Also, you can use the base directory, recurse, and min_depth
  897. * options to improve performance by limiting how much of the filesystem has
  898. * to be traversed.
  899. *
  900. * @param $dir
  901. * The base directory or URI to scan, without trailing slash.
  902. * @param $mask
  903. * The preg_match() regular expression for files to be included.
  904. * @param $options
  905. * An associative array of additional options, with the following elements:
  906. * - 'nomask': The preg_match() regular expression for files to be excluded.
  907. * Defaults to the 'file_scan_ignore_directories' setting.
  908. * - 'callback': The callback function to call for each match. There is no
  909. * default callback.
  910. * - 'recurse': When TRUE, the directory scan will recurse the entire tree
  911. * starting at the provided directory. Defaults to TRUE.
  912. * - 'key': The key to be used for the returned associative array of files.
  913. * Possible values are 'uri', for the file's URI; 'filename', for the
  914. * basename of the file; and 'name' for the name of the file without the
  915. * extension. Defaults to 'uri'.
  916. * - 'min_depth': Minimum depth of directories to return files from. Defaults
  917. * to 0.
  918. * @param $depth
  919. * The current depth of recursion. This parameter is only used internally and
  920. * should not be passed in.
  921. *
  922. * @return
  923. * An associative array (keyed on the chosen key) of objects with 'uri',
  924. * 'filename', and 'name' properties corresponding to the matched files.
  925. */
  926. function file_scan_directory($dir, $mask, $options = [], $depth = 0) {
  927. // Merge in defaults.
  928. $options += [
  929. 'callback' => 0,
  930. 'recurse' => TRUE,
  931. 'key' => 'uri',
  932. 'min_depth' => 0,
  933. ];
  934. // Normalize $dir only once.
  935. if ($depth == 0) {
  936. $dir = file_stream_wrapper_uri_normalize($dir);
  937. $dir_has_slash = (substr($dir, -1) === '/');
  938. }
  939. // Allow directories specified in settings.php to be ignored. You can use this
  940. // to not check for files in common special-purpose directories. For example,
  941. // node_modules and bower_components. Ignoring irrelevant directories is a
  942. // performance boost.
  943. if (!isset($options['nomask'])) {
  944. $ignore_directories = Settings::get('file_scan_ignore_directories', []);
  945. array_walk($ignore_directories, function(&$value) {
  946. $value = preg_quote($value, '/');
  947. });
  948. $default_nomask = '/^' . implode('|', $ignore_directories) . '$/';
  949. }
  950. $options['key'] = in_array($options['key'], ['uri', 'filename', 'name']) ? $options['key'] : 'uri';
  951. $files = [];
  952. // Avoid warnings when opendir does not have the permissions to open a
  953. // directory.
  954. if (is_dir($dir)) {
  955. if ($handle = @opendir($dir)) {
  956. while (FALSE !== ($filename = readdir($handle))) {
  957. // Skip this file if it matches the nomask or starts with a dot.
  958. if ($filename[0] != '.'
  959. && !(isset($options['nomask']) && preg_match($options['nomask'], $filename))
  960. && !(!empty($default_nomask) && preg_match($default_nomask, $filename))
  961. ) {
  962. if ($depth == 0 && $dir_has_slash) {
  963. $uri = "$dir$filename";
  964. }
  965. else {
  966. $uri = "$dir/$filename";
  967. }
  968. if ($options['recurse'] && is_dir($uri)) {
  969. // Give priority to files in this folder by merging them in after
  970. // any subdirectory files.
  971. $files = array_merge(file_scan_directory($uri, $mask, $options, $depth + 1), $files);
  972. }
  973. elseif ($depth >= $options['min_depth'] && preg_match($mask, $filename)) {
  974. // Always use this match over anything already set in $files with
  975. // the same $options['key'].
  976. $file = new stdClass();
  977. $file->uri = $uri;
  978. $file->filename = $filename;
  979. $file->name = pathinfo($filename, PATHINFO_FILENAME);
  980. $key = $options['key'];
  981. $files[$file->$key] = $file;
  982. if ($options['callback']) {
  983. $options['callback']($uri);
  984. }
  985. }
  986. }
  987. }
  988. closedir($handle);
  989. }
  990. else {
  991. \Drupal::logger('file')->error('@dir can not be opened', ['@dir' => $dir]);
  992. }
  993. }
  994. return $files;
  995. }
  996. /**
  997. * Determines the maximum file upload size by querying the PHP settings.
  998. *
  999. * @return
  1000. * A file size limit in bytes based on the PHP upload_max_filesize and
  1001. * post_max_size
  1002. */
  1003. function file_upload_max_size() {
  1004. static $max_size = -1;
  1005. if ($max_size < 0) {
  1006. // Start with post_max_size.
  1007. $max_size = Bytes::toInt(ini_get('post_max_size'));
  1008. // If upload_max_size is less, then reduce. Except if upload_max_size is
  1009. // zero, which indicates no limit.
  1010. $upload_max = Bytes::toInt(ini_get('upload_max_filesize'));
  1011. if ($upload_max > 0 && $upload_max < $max_size) {
  1012. $max_size = $upload_max;
  1013. }
  1014. }
  1015. return $max_size;
  1016. }
  1017. /**
  1018. * Sets the permissions on a file or directory.
  1019. *
  1020. * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  1021. * Use \Drupal\Core\File\FileSystem::chmod().
  1022. */
  1023. function drupal_chmod($uri, $mode = NULL) {
  1024. return \Drupal::service('file_system')->chmod($uri, $mode);
  1025. }
  1026. /**
  1027. * Deletes a file.
  1028. *
  1029. * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  1030. * Use \Drupal\Core\File\FileSystem::unlink().
  1031. */
  1032. function drupal_unlink($uri, $context = NULL) {
  1033. return \Drupal::service('file_system')->unlink($uri, $context);
  1034. }
  1035. /**
  1036. * Resolves the absolute filepath of a local URI or filepath.
  1037. *
  1038. * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  1039. * Use \Drupal\Core\File\FileSystem::realpath().
  1040. */
  1041. function drupal_realpath($uri) {
  1042. return \Drupal::service('file_system')->realpath($uri);
  1043. }
  1044. /**
  1045. * Gets the name of the directory from a given path.
  1046. *
  1047. * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  1048. * Use \Drupal\Core\File\FileSystem::dirname().
  1049. */
  1050. function drupal_dirname($uri) {
  1051. return \Drupal::service('file_system')->dirname($uri);
  1052. }
  1053. /**
  1054. * Gets the filename from a given path.
  1055. *
  1056. * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  1057. * Use \Drupal\Core\File\FileSystem::basename().
  1058. */
  1059. function drupal_basename($uri, $suffix = NULL) {
  1060. return \Drupal::service('file_system')->basename($uri, $suffix);
  1061. }
  1062. /**
  1063. * Creates a directory, optionally creating missing components in the path to
  1064. * the directory.
  1065. *
  1066. * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  1067. * Use \Drupal\Core\File\FileSystem::mkdir().
  1068. */
  1069. function drupal_mkdir($uri, $mode = NULL, $recursive = FALSE, $context = NULL) {
  1070. return \Drupal::service('file_system')->mkdir($uri, $mode, $recursive, $context);
  1071. }
  1072. /**
  1073. * Removes a directory.
  1074. *
  1075. * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  1076. * Use \Drupal\Core\File\FileSystem::rmdir().
  1077. */
  1078. function drupal_rmdir($uri, $context = NULL) {
  1079. return \Drupal::service('file_system')->rmdir($uri, $context);
  1080. }
  1081. /**
  1082. * Creates a file with a unique filename in the specified directory.
  1083. *
  1084. * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  1085. * Use \Drupal\Core\File\FileSystem::tempnam().
  1086. */
  1087. function drupal_tempnam($directory, $prefix) {
  1088. return \Drupal::service('file_system')->tempnam($directory, $prefix);
  1089. }
  1090. /**
  1091. * Gets and sets the path of the configured temporary directory.
  1092. *
  1093. * @return mixed|null
  1094. * A string containing the path to the temporary directory.
  1095. */
  1096. function file_directory_temp() {
  1097. $temporary_directory = \Drupal::config('system.file')->get('path.temporary');
  1098. if (empty($temporary_directory)) {
  1099. // Needs set up.
  1100. $config = \Drupal::configFactory()->getEditable('system.file');
  1101. $temporary_directory = ComponentFileSystem::getOsTemporaryDirectory();
  1102. if (empty($temporary_directory)) {
  1103. // If no directory has been found default to 'files/tmp'.
  1104. $temporary_directory = PublicStream::basePath() . '/tmp';
  1105. // Windows accepts paths with either slash (/) or backslash (\), but will
  1106. // not accept a path which contains both a slash and a backslash. Since
  1107. // the 'file_public_path' variable may have either format, we sanitize
  1108. // everything to use slash which is supported on all platforms.
  1109. $temporary_directory = str_replace('\\', '/', $temporary_directory);
  1110. }
  1111. // Save the path of the discovered directory. Do not check config schema on
  1112. // save.
  1113. $config->set('path.temporary', (string) $temporary_directory)->save(TRUE);
  1114. }
  1115. return $temporary_directory;
  1116. }
  1117. /**
  1118. * Discovers a writable system-appropriate temporary directory.
  1119. *
  1120. * @return mixed
  1121. * A string containing the path to the temporary directory.
  1122. *
  1123. * @deprecated in Drupal 8.3.x-dev, will be removed before Drupal 9.0.0.
  1124. * Use \Drupal\Component\FileSystem\FileSystem::getOsTemporaryDirectory().
  1125. */
  1126. function file_directory_os_temp() {
  1127. return ComponentFileSystem::getOsTemporaryDirectory();
  1128. }
  1129. /**
  1130. * @} End of "defgroup file".
  1131. */