Filesystem.php 29 KB

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