Filesystem.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Filesystem;
  11. use Symfony\Component\Filesystem\Exception\FileNotFoundException;
  12. use Symfony\Component\Filesystem\Exception\InvalidArgumentException;
  13. use Symfony\Component\Filesystem\Exception\IOException;
  14. /**
  15. * Provides basic utility to manipulate the file system.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. */
  19. class Filesystem
  20. {
  21. private static $lastError;
  22. /**
  23. * Copies a file.
  24. *
  25. * If the target file is older than the origin file, it's always overwritten.
  26. * If the target file is newer, it is overwritten only when the
  27. * $overwriteNewerFiles option is set to true.
  28. *
  29. * @param string $originFile The original filename
  30. * @param string $targetFile The target filename
  31. * @param bool $overwriteNewerFiles If true, target files newer than origin files are overwritten
  32. *
  33. * @throws FileNotFoundException When originFile doesn't exist
  34. * @throws IOException When copy fails
  35. */
  36. public function copy($originFile, $targetFile, $overwriteNewerFiles = false)
  37. {
  38. $originIsLocal = stream_is_local($originFile) || 0 === stripos($originFile, 'file://');
  39. if ($originIsLocal && !is_file($originFile)) {
  40. throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile);
  41. }
  42. $this->mkdir(\dirname($targetFile));
  43. $doCopy = true;
  44. if (!$overwriteNewerFiles && null === parse_url($originFile, PHP_URL_HOST) && is_file($targetFile)) {
  45. $doCopy = filemtime($originFile) > filemtime($targetFile);
  46. }
  47. if ($doCopy) {
  48. // https://bugs.php.net/bug.php?id=64634
  49. if (false === $source = @fopen($originFile, 'r')) {
  50. throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile);
  51. }
  52. // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default
  53. if (false === $target = @fopen($targetFile, 'w', null, stream_context_create(array('ftp' => array('overwrite' => true))))) {
  54. throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile);
  55. }
  56. $bytesCopied = stream_copy_to_stream($source, $target);
  57. fclose($source);
  58. fclose($target);
  59. unset($source, $target);
  60. if (!is_file($targetFile)) {
  61. throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile);
  62. }
  63. if ($originIsLocal) {
  64. // Like `cp`, preserve executable permission bits
  65. @chmod($targetFile, fileperms($targetFile) | (fileperms($originFile) & 0111));
  66. if ($bytesCopied !== $bytesOrigin = filesize($originFile)) {
  67. throw new IOException(sprintf('Failed to copy the whole content of "%s" to "%s" (%g of %g bytes copied).', $originFile, $targetFile, $bytesCopied, $bytesOrigin), 0, null, $originFile);
  68. }
  69. }
  70. }
  71. }
  72. /**
  73. * Creates a directory recursively.
  74. *
  75. * @param string|iterable $dirs The directory path
  76. * @param int $mode The directory mode
  77. *
  78. * @throws IOException On any directory creation failure
  79. */
  80. public function mkdir($dirs, $mode = 0777)
  81. {
  82. foreach ($this->toIterable($dirs) as $dir) {
  83. if (is_dir($dir)) {
  84. continue;
  85. }
  86. if (!self::box('mkdir', $dir, $mode, true)) {
  87. if (!is_dir($dir)) {
  88. // The directory was not created by a concurrent process. Let's throw an exception with a developer friendly error message if we have one
  89. if (self::$lastError) {
  90. throw new IOException(sprintf('Failed to create "%s": %s.', $dir, self::$lastError), 0, null, $dir);
  91. }
  92. throw new IOException(sprintf('Failed to create "%s"', $dir), 0, null, $dir);
  93. }
  94. }
  95. }
  96. }
  97. /**
  98. * Checks the existence of files or directories.
  99. *
  100. * @param string|iterable $files A filename, an array of files, or a \Traversable instance to check
  101. *
  102. * @return bool true if the file exists, false otherwise
  103. */
  104. public function exists($files)
  105. {
  106. $maxPathLength = PHP_MAXPATHLEN - 2;
  107. foreach ($this->toIterable($files) as $file) {
  108. if (\strlen($file) > $maxPathLength) {
  109. throw new IOException(sprintf('Could not check if file exist because path length exceeds %d characters.', $maxPathLength), 0, null, $file);
  110. }
  111. if (!file_exists($file)) {
  112. return false;
  113. }
  114. }
  115. return true;
  116. }
  117. /**
  118. * Sets access and modification time of file.
  119. *
  120. * @param string|iterable $files A filename, an array of files, or a \Traversable instance to create
  121. * @param int $time The touch time as a Unix timestamp
  122. * @param int $atime The access time as a Unix timestamp
  123. *
  124. * @throws IOException When touch fails
  125. */
  126. public function touch($files, $time = null, $atime = null)
  127. {
  128. foreach ($this->toIterable($files) as $file) {
  129. $touch = $time ? @touch($file, $time, $atime) : @touch($file);
  130. if (true !== $touch) {
  131. throw new IOException(sprintf('Failed to touch "%s".', $file), 0, null, $file);
  132. }
  133. }
  134. }
  135. /**
  136. * Removes files or directories.
  137. *
  138. * @param string|iterable $files A filename, an array of files, or a \Traversable instance to remove
  139. *
  140. * @throws IOException When removal fails
  141. */
  142. public function remove($files)
  143. {
  144. if ($files instanceof \Traversable) {
  145. $files = iterator_to_array($files, false);
  146. } elseif (!\is_array($files)) {
  147. $files = array($files);
  148. }
  149. $files = array_reverse($files);
  150. foreach ($files as $file) {
  151. if (is_link($file)) {
  152. // See https://bugs.php.net/52176
  153. if (!(self::box('unlink', $file) || '\\' !== \DIRECTORY_SEPARATOR || self::box('rmdir', $file)) && file_exists($file)) {
  154. throw new IOException(sprintf('Failed to remove symlink "%s": %s.', $file, self::$lastError));
  155. }
  156. } elseif (is_dir($file)) {
  157. $this->remove(new \FilesystemIterator($file, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS));
  158. if (!self::box('rmdir', $file) && file_exists($file)) {
  159. throw new IOException(sprintf('Failed to remove directory "%s": %s.', $file, self::$lastError));
  160. }
  161. } elseif (!self::box('unlink', $file) && file_exists($file)) {
  162. throw new IOException(sprintf('Failed to remove file "%s": %s.', $file, self::$lastError));
  163. }
  164. }
  165. }
  166. /**
  167. * Change mode for an array of files or directories.
  168. *
  169. * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change mode
  170. * @param int $mode The new mode (octal)
  171. * @param int $umask The mode mask (octal)
  172. * @param bool $recursive Whether change the mod recursively or not
  173. *
  174. * @throws IOException When the change fail
  175. */
  176. public function chmod($files, $mode, $umask = 0000, $recursive = false)
  177. {
  178. foreach ($this->toIterable($files) as $file) {
  179. if (true !== @chmod($file, $mode & ~$umask)) {
  180. throw new IOException(sprintf('Failed to chmod file "%s".', $file), 0, null, $file);
  181. }
  182. if ($recursive && is_dir($file) && !is_link($file)) {
  183. $this->chmod(new \FilesystemIterator($file), $mode, $umask, true);
  184. }
  185. }
  186. }
  187. /**
  188. * Change the owner of an array of files or directories.
  189. *
  190. * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change owner
  191. * @param string $user The new owner user name
  192. * @param bool $recursive Whether change the owner recursively or not
  193. *
  194. * @throws IOException When the change fail
  195. */
  196. public function chown($files, $user, $recursive = false)
  197. {
  198. foreach ($this->toIterable($files) as $file) {
  199. if ($recursive && is_dir($file) && !is_link($file)) {
  200. $this->chown(new \FilesystemIterator($file), $user, true);
  201. }
  202. if (is_link($file) && \function_exists('lchown')) {
  203. if (true !== @lchown($file, $user)) {
  204. throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
  205. }
  206. } else {
  207. if (true !== @chown($file, $user)) {
  208. throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
  209. }
  210. }
  211. }
  212. }
  213. /**
  214. * Change the group of an array of files or directories.
  215. *
  216. * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change group
  217. * @param string $group The group name
  218. * @param bool $recursive Whether change the group recursively or not
  219. *
  220. * @throws IOException When the change fail
  221. */
  222. public function chgrp($files, $group, $recursive = false)
  223. {
  224. foreach ($this->toIterable($files) as $file) {
  225. if ($recursive && is_dir($file) && !is_link($file)) {
  226. $this->chgrp(new \FilesystemIterator($file), $group, true);
  227. }
  228. if (is_link($file) && \function_exists('lchgrp')) {
  229. if (true !== @lchgrp($file, $group)) {
  230. throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
  231. }
  232. } else {
  233. if (true !== @chgrp($file, $group)) {
  234. throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
  235. }
  236. }
  237. }
  238. }
  239. /**
  240. * Renames a file or a directory.
  241. *
  242. * @param string $origin The origin filename or directory
  243. * @param string $target The new filename or directory
  244. * @param bool $overwrite Whether to overwrite the target if it already exists
  245. *
  246. * @throws IOException When target file or directory already exists
  247. * @throws IOException When origin cannot be renamed
  248. */
  249. public function rename($origin, $target, $overwrite = false)
  250. {
  251. // we check that target does not exist
  252. if (!$overwrite && $this->isReadable($target)) {
  253. throw new IOException(sprintf('Cannot rename because the target "%s" already exists.', $target), 0, null, $target);
  254. }
  255. if (true !== @rename($origin, $target)) {
  256. if (is_dir($origin)) {
  257. // See https://bugs.php.net/bug.php?id=54097 & http://php.net/manual/en/function.rename.php#113943
  258. $this->mirror($origin, $target, null, array('override' => $overwrite, 'delete' => $overwrite));
  259. $this->remove($origin);
  260. return;
  261. }
  262. throw new IOException(sprintf('Cannot rename "%s" to "%s".', $origin, $target), 0, null, $target);
  263. }
  264. }
  265. /**
  266. * Tells whether a file exists and is readable.
  267. *
  268. * @param string $filename Path to the file
  269. *
  270. * @return bool
  271. *
  272. * @throws IOException When windows path is longer than 258 characters
  273. */
  274. private function isReadable($filename)
  275. {
  276. $maxPathLength = PHP_MAXPATHLEN - 2;
  277. if (\strlen($filename) > $maxPathLength) {
  278. throw new IOException(sprintf('Could not check if file is readable because path length exceeds %d characters.', $maxPathLength), 0, null, $filename);
  279. }
  280. return is_readable($filename);
  281. }
  282. /**
  283. * Creates a symbolic link or copy a directory.
  284. *
  285. * @param string $originDir The origin directory path
  286. * @param string $targetDir The symbolic link name
  287. * @param bool $copyOnWindows Whether to copy files if on Windows
  288. *
  289. * @throws IOException When symlink fails
  290. */
  291. public function symlink($originDir, $targetDir, $copyOnWindows = false)
  292. {
  293. if ('\\' === \DIRECTORY_SEPARATOR) {
  294. $originDir = strtr($originDir, '/', '\\');
  295. $targetDir = strtr($targetDir, '/', '\\');
  296. if ($copyOnWindows) {
  297. $this->mirror($originDir, $targetDir);
  298. return;
  299. }
  300. }
  301. $this->mkdir(\dirname($targetDir));
  302. if (is_link($targetDir)) {
  303. if (readlink($targetDir) === $originDir) {
  304. return;
  305. }
  306. $this->remove($targetDir);
  307. }
  308. if (!self::box('symlink', $originDir, $targetDir)) {
  309. $this->linkException($originDir, $targetDir, 'symbolic');
  310. }
  311. }
  312. /**
  313. * Creates a hard link, or several hard links to a file.
  314. *
  315. * @param string $originFile The original file
  316. * @param string|string[] $targetFiles The target file(s)
  317. *
  318. * @throws FileNotFoundException When original file is missing or not a file
  319. * @throws IOException When link fails, including if link already exists
  320. */
  321. public function hardlink($originFile, $targetFiles)
  322. {
  323. if (!$this->exists($originFile)) {
  324. throw new FileNotFoundException(null, 0, null, $originFile);
  325. }
  326. if (!is_file($originFile)) {
  327. throw new FileNotFoundException(sprintf('Origin file "%s" is not a file', $originFile));
  328. }
  329. foreach ($this->toIterable($targetFiles) as $targetFile) {
  330. if (is_file($targetFile)) {
  331. if (fileinode($originFile) === fileinode($targetFile)) {
  332. continue;
  333. }
  334. $this->remove($targetFile);
  335. }
  336. if (!self::box('link', $originFile, $targetFile)) {
  337. $this->linkException($originFile, $targetFile, 'hard');
  338. }
  339. }
  340. }
  341. /**
  342. * @param string $origin
  343. * @param string $target
  344. * @param string $linkType Name of the link type, typically 'symbolic' or 'hard'
  345. */
  346. private function linkException($origin, $target, $linkType)
  347. {
  348. if (self::$lastError) {
  349. if ('\\' === \DIRECTORY_SEPARATOR && false !== strpos(self::$lastError, 'error code(1314)')) {
  350. throw new IOException(sprintf('Unable to create %s link due to error code 1314: \'A required privilege is not held by the client\'. Do you have the required Administrator-rights?', $linkType), 0, null, $target);
  351. }
  352. }
  353. throw new IOException(sprintf('Failed to create %s link from "%s" to "%s".', $linkType, $origin, $target), 0, null, $target);
  354. }
  355. /**
  356. * Resolves links in paths.
  357. *
  358. * With $canonicalize = false (default)
  359. * - if $path does not exist or is not a link, returns null
  360. * - if $path is a link, returns the next direct target of the link without considering the existence of the target
  361. *
  362. * With $canonicalize = true
  363. * - if $path does not exist, returns null
  364. * - if $path exists, returns its absolute fully resolved final version
  365. *
  366. * @param string $path A filesystem path
  367. * @param bool $canonicalize Whether or not to return a canonicalized path
  368. *
  369. * @return string|null
  370. */
  371. public function readlink($path, $canonicalize = false)
  372. {
  373. if (!$canonicalize && !is_link($path)) {
  374. return;
  375. }
  376. if ($canonicalize) {
  377. if (!$this->exists($path)) {
  378. return;
  379. }
  380. if ('\\' === \DIRECTORY_SEPARATOR) {
  381. $path = readlink($path);
  382. }
  383. return realpath($path);
  384. }
  385. if ('\\' === \DIRECTORY_SEPARATOR) {
  386. return realpath($path);
  387. }
  388. return readlink($path);
  389. }
  390. /**
  391. * Given an existing path, convert it to a path relative to a given starting path.
  392. *
  393. * @param string $endPath Absolute path of target
  394. * @param string $startPath Absolute path where traversal begins
  395. *
  396. * @return string Path of target relative to starting path
  397. */
  398. public function makePathRelative($endPath, $startPath)
  399. {
  400. if (!$this->isAbsolutePath($startPath)) {
  401. throw new InvalidArgumentException(sprintf('The start path "%s" is not absolute.', $startPath));
  402. }
  403. if (!$this->isAbsolutePath($endPath)) {
  404. throw new InvalidArgumentException(sprintf('The end path "%s" is not absolute.', $endPath));
  405. }
  406. // Normalize separators on Windows
  407. if ('\\' === \DIRECTORY_SEPARATOR) {
  408. $endPath = str_replace('\\', '/', $endPath);
  409. $startPath = str_replace('\\', '/', $startPath);
  410. }
  411. $stripDriveLetter = function ($path) {
  412. if (\strlen($path) > 2 && ':' === $path[1] && '/' === $path[2] && ctype_alpha($path[0])) {
  413. return substr($path, 2);
  414. }
  415. return $path;
  416. };
  417. $endPath = $stripDriveLetter($endPath);
  418. $startPath = $stripDriveLetter($startPath);
  419. // Split the paths into arrays
  420. $startPathArr = explode('/', trim($startPath, '/'));
  421. $endPathArr = explode('/', trim($endPath, '/'));
  422. $normalizePathArray = function ($pathSegments) {
  423. $result = array();
  424. foreach ($pathSegments as $segment) {
  425. if ('..' === $segment) {
  426. array_pop($result);
  427. } elseif ('.' !== $segment) {
  428. $result[] = $segment;
  429. }
  430. }
  431. return $result;
  432. };
  433. $startPathArr = $normalizePathArray($startPathArr);
  434. $endPathArr = $normalizePathArray($endPathArr);
  435. // Find for which directory the common path stops
  436. $index = 0;
  437. while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {
  438. ++$index;
  439. }
  440. // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels)
  441. if (1 === \count($startPathArr) && '' === $startPathArr[0]) {
  442. $depth = 0;
  443. } else {
  444. $depth = \count($startPathArr) - $index;
  445. }
  446. // Repeated "../" for each level need to reach the common path
  447. $traverser = str_repeat('../', $depth);
  448. $endPathRemainder = implode('/', \array_slice($endPathArr, $index));
  449. // Construct $endPath from traversing to the common path, then to the remaining $endPath
  450. $relativePath = $traverser.('' !== $endPathRemainder ? $endPathRemainder.'/' : '');
  451. return '' === $relativePath ? './' : $relativePath;
  452. }
  453. /**
  454. * Mirrors a directory to another.
  455. *
  456. * Copies files and directories from the origin directory into the target directory. By default:
  457. *
  458. * - existing files in the target directory will be overwritten, except if they are newer (see the `override` option)
  459. * - files in the target directory that do not exist in the source directory will not be deleted (see the `delete` option)
  460. *
  461. * @param string $originDir The origin directory
  462. * @param string $targetDir The target directory
  463. * @param \Traversable $iterator Iterator that filters which files and directories to copy
  464. * @param array $options An array of boolean options
  465. * Valid options are:
  466. * - $options['override'] If true, target files newer than origin files are overwritten (see copy(), defaults to false)
  467. * - $options['copy_on_windows'] Whether to copy files instead of links on Windows (see symlink(), defaults to false)
  468. * - $options['delete'] Whether to delete files that are not in the source directory (defaults to false)
  469. *
  470. * @throws IOException When file type is unknown
  471. */
  472. public function mirror($originDir, $targetDir, \Traversable $iterator = null, $options = array())
  473. {
  474. $targetDir = rtrim($targetDir, '/\\');
  475. $originDir = rtrim($originDir, '/\\');
  476. $originDirLen = \strlen($originDir);
  477. // Iterate in destination folder to remove obsolete entries
  478. if ($this->exists($targetDir) && isset($options['delete']) && $options['delete']) {
  479. $deleteIterator = $iterator;
  480. if (null === $deleteIterator) {
  481. $flags = \FilesystemIterator::SKIP_DOTS;
  482. $deleteIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($targetDir, $flags), \RecursiveIteratorIterator::CHILD_FIRST);
  483. }
  484. $targetDirLen = \strlen($targetDir);
  485. foreach ($deleteIterator as $file) {
  486. $origin = $originDir.substr($file->getPathname(), $targetDirLen);
  487. if (!$this->exists($origin)) {
  488. $this->remove($file);
  489. }
  490. }
  491. }
  492. $copyOnWindows = false;
  493. if (isset($options['copy_on_windows'])) {
  494. $copyOnWindows = $options['copy_on_windows'];
  495. }
  496. if (null === $iterator) {
  497. $flags = $copyOnWindows ? \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS : \FilesystemIterator::SKIP_DOTS;
  498. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($originDir, $flags), \RecursiveIteratorIterator::SELF_FIRST);
  499. }
  500. if ($this->exists($originDir)) {
  501. $this->mkdir($targetDir);
  502. }
  503. foreach ($iterator as $file) {
  504. $target = $targetDir.substr($file->getPathname(), $originDirLen);
  505. if ($copyOnWindows) {
  506. if (is_file($file)) {
  507. $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
  508. } elseif (is_dir($file)) {
  509. $this->mkdir($target);
  510. } else {
  511. throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
  512. }
  513. } else {
  514. if (is_link($file)) {
  515. $this->symlink($file->getLinkTarget(), $target);
  516. } elseif (is_dir($file)) {
  517. $this->mkdir($target);
  518. } elseif (is_file($file)) {
  519. $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
  520. } else {
  521. throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
  522. }
  523. }
  524. }
  525. }
  526. /**
  527. * Returns whether the file path is an absolute path.
  528. *
  529. * @param string $file A file path
  530. *
  531. * @return bool
  532. */
  533. public function isAbsolutePath($file)
  534. {
  535. return strspn($file, '/\\', 0, 1)
  536. || (\strlen($file) > 3 && ctype_alpha($file[0])
  537. && ':' === $file[1]
  538. && strspn($file, '/\\', 2, 1)
  539. )
  540. || null !== parse_url($file, PHP_URL_SCHEME)
  541. ;
  542. }
  543. /**
  544. * Creates a temporary file with support for custom stream wrappers.
  545. *
  546. * @param string $dir The directory where the temporary filename will be created
  547. * @param string $prefix The prefix of the generated temporary filename
  548. * Note: Windows uses only the first three characters of prefix
  549. *
  550. * @return string The new temporary filename (with path), or throw an exception on failure
  551. */
  552. public function tempnam($dir, $prefix)
  553. {
  554. list($scheme, $hierarchy) = $this->getSchemeAndHierarchy($dir);
  555. // If no scheme or scheme is "file" or "gs" (Google Cloud) create temp file in local filesystem
  556. if (null === $scheme || 'file' === $scheme || 'gs' === $scheme) {
  557. $tmpFile = @tempnam($hierarchy, $prefix);
  558. // If tempnam failed or no scheme return the filename otherwise prepend the scheme
  559. if (false !== $tmpFile) {
  560. if (null !== $scheme && 'gs' !== $scheme) {
  561. return $scheme.'://'.$tmpFile;
  562. }
  563. return $tmpFile;
  564. }
  565. throw new IOException('A temporary file could not be created.');
  566. }
  567. // Loop until we create a valid temp file or have reached 10 attempts
  568. for ($i = 0; $i < 10; ++$i) {
  569. // Create a unique filename
  570. $tmpFile = $dir.'/'.$prefix.uniqid(mt_rand(), true);
  571. // Use fopen instead of file_exists as some streams do not support stat
  572. // Use mode 'x+' to atomically check existence and create to avoid a TOCTOU vulnerability
  573. $handle = @fopen($tmpFile, 'x+');
  574. // If unsuccessful restart the loop
  575. if (false === $handle) {
  576. continue;
  577. }
  578. // Close the file if it was successfully opened
  579. @fclose($handle);
  580. return $tmpFile;
  581. }
  582. throw new IOException('A temporary file could not be created.');
  583. }
  584. /**
  585. * Atomically dumps content into a file.
  586. *
  587. * @param string $filename The file to be written to
  588. * @param string $content The data to write into the file
  589. *
  590. * @throws IOException if the file cannot be written to
  591. */
  592. public function dumpFile($filename, $content)
  593. {
  594. $dir = \dirname($filename);
  595. if (!is_dir($dir)) {
  596. $this->mkdir($dir);
  597. }
  598. if (!is_writable($dir)) {
  599. throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir);
  600. }
  601. // Will create a temp file with 0600 access rights
  602. // when the filesystem supports chmod.
  603. $tmpFile = $this->tempnam($dir, basename($filename));
  604. if (false === @file_put_contents($tmpFile, $content)) {
  605. throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
  606. }
  607. @chmod($tmpFile, file_exists($filename) ? fileperms($filename) : 0666 & ~umask());
  608. $this->rename($tmpFile, $filename, true);
  609. }
  610. /**
  611. * Appends content to an existing file.
  612. *
  613. * @param string $filename The file to which to append content
  614. * @param string $content The content to append
  615. *
  616. * @throws IOException If the file is not writable
  617. */
  618. public function appendToFile($filename, $content)
  619. {
  620. $dir = \dirname($filename);
  621. if (!is_dir($dir)) {
  622. $this->mkdir($dir);
  623. }
  624. if (!is_writable($dir)) {
  625. throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir);
  626. }
  627. if (false === @file_put_contents($filename, $content, FILE_APPEND)) {
  628. throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
  629. }
  630. }
  631. private function toIterable($files): iterable
  632. {
  633. return \is_array($files) || $files instanceof \Traversable ? $files : array($files);
  634. }
  635. /**
  636. * Gets a 2-tuple of scheme (may be null) and hierarchical part of a filename (e.g. file:///tmp -> array(file, tmp)).
  637. */
  638. private function getSchemeAndHierarchy(string $filename): array
  639. {
  640. $components = explode('://', $filename, 2);
  641. return 2 === \count($components) ? array($components[0], $components[1]) : array(null, $components[0]);
  642. }
  643. private static function box($func)
  644. {
  645. self::$lastError = null;
  646. \set_error_handler(__CLASS__.'::handleError');
  647. try {
  648. $result = \call_user_func_array($func, \array_slice(\func_get_args(), 1));
  649. \restore_error_handler();
  650. return $result;
  651. } catch (\Throwable $e) {
  652. } catch (\Exception $e) {
  653. }
  654. \restore_error_handler();
  655. throw $e;
  656. }
  657. /**
  658. * @internal
  659. */
  660. public static function handleError($type, $msg)
  661. {
  662. self::$lastError = $msg;
  663. }
  664. }