file.inc 43 KB

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