file.inc 44 KB

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