Filesystem.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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\IOException;
  12. use Symfony\Component\Filesystem\Exception\FileNotFoundException;
  13. /**
  14. * Provides basic utility to manipulate the file system.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. */
  18. class Filesystem
  19. {
  20. /**
  21. * Copies a file.
  22. *
  23. * If the target file is older than the origin file, it's always overwritten.
  24. * If the target file is newer, it is overwritten only when the
  25. * $overwriteNewerFiles option is set to true.
  26. *
  27. * @param string $originFile The original filename
  28. * @param string $targetFile The target filename
  29. * @param bool $overwriteNewerFiles If true, target files newer than origin files are overwritten
  30. *
  31. * @throws FileNotFoundException When originFile doesn't exist
  32. * @throws IOException When copy fails
  33. */
  34. public function copy($originFile, $targetFile, $overwriteNewerFiles = false)
  35. {
  36. if (stream_is_local($originFile) && !is_file($originFile)) {
  37. throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile);
  38. }
  39. $this->mkdir(dirname($targetFile));
  40. $doCopy = true;
  41. if (!$overwriteNewerFiles && null === parse_url($originFile, PHP_URL_HOST) && is_file($targetFile)) {
  42. $doCopy = filemtime($originFile) > filemtime($targetFile);
  43. }
  44. if ($doCopy) {
  45. // https://bugs.php.net/bug.php?id=64634
  46. if (false === $source = @fopen($originFile, 'r')) {
  47. throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile);
  48. }
  49. // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default
  50. if (false === $target = @fopen($targetFile, 'w', null, stream_context_create(array('ftp' => array('overwrite' => true))))) {
  51. throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile);
  52. }
  53. $bytesCopied = stream_copy_to_stream($source, $target);
  54. fclose($source);
  55. fclose($target);
  56. unset($source, $target);
  57. if (!is_file($targetFile)) {
  58. throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile);
  59. }
  60. // Like `cp`, preserve executable permission bits
  61. @chmod($targetFile, fileperms($targetFile) | (fileperms($originFile) & 0111));
  62. if (stream_is_local($originFile) && $bytesCopied !== ($bytesOrigin = filesize($originFile))) {
  63. 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);
  64. }
  65. }
  66. }
  67. /**
  68. * Creates a directory recursively.
  69. *
  70. * @param string|array|\Traversable $dirs The directory path
  71. * @param int $mode The directory mode
  72. *
  73. * @throws IOException On any directory creation failure
  74. */
  75. public function mkdir($dirs, $mode = 0777)
  76. {
  77. foreach ($this->toIterator($dirs) as $dir) {
  78. if (is_dir($dir)) {
  79. continue;
  80. }
  81. if (true !== @mkdir($dir, $mode, true)) {
  82. $error = error_get_last();
  83. if (!is_dir($dir)) {
  84. // The directory was not created by a concurrent process. Let's throw an exception with a developer friendly error message if we have one
  85. if ($error) {
  86. throw new IOException(sprintf('Failed to create "%s": %s.', $dir, $error['message']), 0, null, $dir);
  87. }
  88. throw new IOException(sprintf('Failed to create "%s"', $dir), 0, null, $dir);
  89. }
  90. }
  91. }
  92. }
  93. /**
  94. * Checks the existence of files or directories.
  95. *
  96. * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to check
  97. *
  98. * @return bool true if the file exists, false otherwise
  99. */
  100. public function exists($files)
  101. {
  102. foreach ($this->toIterator($files) as $file) {
  103. if ('\\' === DIRECTORY_SEPARATOR && strlen($file) > 258) {
  104. throw new IOException('Could not check if file exist because path length exceeds 258 characters.', 0, null, $file);
  105. }
  106. if (!file_exists($file)) {
  107. return false;
  108. }
  109. }
  110. return true;
  111. }
  112. /**
  113. * Sets access and modification time of file.
  114. *
  115. * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to create
  116. * @param int $time The touch time as a Unix timestamp
  117. * @param int $atime The access time as a Unix timestamp
  118. *
  119. * @throws IOException When touch fails
  120. */
  121. public function touch($files, $time = null, $atime = null)
  122. {
  123. foreach ($this->toIterator($files) as $file) {
  124. $touch = $time ? @touch($file, $time, $atime) : @touch($file);
  125. if (true !== $touch) {
  126. throw new IOException(sprintf('Failed to touch "%s".', $file), 0, null, $file);
  127. }
  128. }
  129. }
  130. /**
  131. * Removes files or directories.
  132. *
  133. * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to remove
  134. *
  135. * @throws IOException When removal fails
  136. */
  137. public function remove($files)
  138. {
  139. if ($files instanceof \Traversable) {
  140. $files = iterator_to_array($files, false);
  141. } elseif (!is_array($files)) {
  142. $files = array($files);
  143. }
  144. $files = array_reverse($files);
  145. foreach ($files as $file) {
  146. if (is_link($file)) {
  147. // See https://bugs.php.net/52176
  148. if (!@(unlink($file) || '\\' !== DIRECTORY_SEPARATOR || rmdir($file)) && file_exists($file)) {
  149. $error = error_get_last();
  150. throw new IOException(sprintf('Failed to remove symlink "%s": %s.', $file, $error['message']));
  151. }
  152. } elseif (is_dir($file)) {
  153. $this->remove(new \FilesystemIterator($file, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS));
  154. if (!@rmdir($file) && file_exists($file)) {
  155. $error = error_get_last();
  156. throw new IOException(sprintf('Failed to remove directory "%s": %s.', $file, $error['message']));
  157. }
  158. } elseif (!@unlink($file) && file_exists($file)) {
  159. $error = error_get_last();
  160. throw new IOException(sprintf('Failed to remove file "%s": %s.', $file, $error['message']));
  161. }
  162. }
  163. }
  164. /**
  165. * Change mode for an array of files or directories.
  166. *
  167. * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change mode
  168. * @param int $mode The new mode (octal)
  169. * @param int $umask The mode mask (octal)
  170. * @param bool $recursive Whether change the mod recursively or not
  171. *
  172. * @throws IOException When the change fail
  173. */
  174. public function chmod($files, $mode, $umask = 0000, $recursive = false)
  175. {
  176. foreach ($this->toIterator($files) as $file) {
  177. if (true !== @chmod($file, $mode & ~$umask)) {
  178. throw new IOException(sprintf('Failed to chmod file "%s".', $file), 0, null, $file);
  179. }
  180. if ($recursive && is_dir($file) && !is_link($file)) {
  181. $this->chmod(new \FilesystemIterator($file), $mode, $umask, true);
  182. }
  183. }
  184. }
  185. /**
  186. * Change the owner of an array of files or directories.
  187. *
  188. * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change owner
  189. * @param string $user The new owner user name
  190. * @param bool $recursive Whether change the owner recursively or not
  191. *
  192. * @throws IOException When the change fail
  193. */
  194. public function chown($files, $user, $recursive = false)
  195. {
  196. foreach ($this->toIterator($files) as $file) {
  197. if ($recursive && is_dir($file) && !is_link($file)) {
  198. $this->chown(new \FilesystemIterator($file), $user, true);
  199. }
  200. if (is_link($file) && function_exists('lchown')) {
  201. if (true !== @lchown($file, $user)) {
  202. throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
  203. }
  204. } else {
  205. if (true !== @chown($file, $user)) {
  206. throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
  207. }
  208. }
  209. }
  210. }
  211. /**
  212. * Change the group of an array of files or directories.
  213. *
  214. * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change group
  215. * @param string $group The group name
  216. * @param bool $recursive Whether change the group recursively or not
  217. *
  218. * @throws IOException When the change fail
  219. */
  220. public function chgrp($files, $group, $recursive = false)
  221. {
  222. foreach ($this->toIterator($files) as $file) {
  223. if ($recursive && is_dir($file) && !is_link($file)) {
  224. $this->chgrp(new \FilesystemIterator($file), $group, true);
  225. }
  226. if (is_link($file) && function_exists('lchgrp')) {
  227. if (true !== @lchgrp($file, $group) || (defined('HHVM_VERSION') && !posix_getgrnam($group))) {
  228. throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
  229. }
  230. } else {
  231. if (true !== @chgrp($file, $group)) {
  232. throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
  233. }
  234. }
  235. }
  236. }
  237. /**
  238. * Renames a file or a directory.
  239. *
  240. * @param string $origin The origin filename or directory
  241. * @param string $target The new filename or directory
  242. * @param bool $overwrite Whether to overwrite the target if it already exists
  243. *
  244. * @throws IOException When target file or directory already exists
  245. * @throws IOException When origin cannot be renamed
  246. */
  247. public function rename($origin, $target, $overwrite = false)
  248. {
  249. // we check that target does not exist
  250. if (!$overwrite && $this->isReadable($target)) {
  251. throw new IOException(sprintf('Cannot rename because the target "%s" already exists.', $target), 0, null, $target);
  252. }
  253. if (true !== @rename($origin, $target)) {
  254. throw new IOException(sprintf('Cannot rename "%s" to "%s".', $origin, $target), 0, null, $target);
  255. }
  256. }
  257. /**
  258. * Tells whether a file exists and is readable.
  259. *
  260. * @param string $filename Path to the file
  261. *
  262. * @throws IOException When windows path is longer than 258 characters
  263. */
  264. private function isReadable($filename)
  265. {
  266. if ('\\' === DIRECTORY_SEPARATOR && strlen($filename) > 258) {
  267. throw new IOException('Could not check if file is readable because path length exceeds 258 characters.', 0, null, $filename);
  268. }
  269. return is_readable($filename);
  270. }
  271. /**
  272. * Creates a symbolic link or copy a directory.
  273. *
  274. * @param string $originDir The origin directory path
  275. * @param string $targetDir The symbolic link name
  276. * @param bool $copyOnWindows Whether to copy files if on Windows
  277. *
  278. * @throws IOException When symlink fails
  279. */
  280. public function symlink($originDir, $targetDir, $copyOnWindows = false)
  281. {
  282. if ('\\' === DIRECTORY_SEPARATOR) {
  283. $originDir = strtr($originDir, '/', '\\');
  284. $targetDir = strtr($targetDir, '/', '\\');
  285. if ($copyOnWindows) {
  286. $this->mirror($originDir, $targetDir);
  287. return;
  288. }
  289. }
  290. $this->mkdir(dirname($targetDir));
  291. $ok = false;
  292. if (is_link($targetDir)) {
  293. if (readlink($targetDir) != $originDir) {
  294. $this->remove($targetDir);
  295. } else {
  296. $ok = true;
  297. }
  298. }
  299. if (!$ok && true !== @symlink($originDir, $targetDir)) {
  300. $report = error_get_last();
  301. if (is_array($report)) {
  302. if ('\\' === DIRECTORY_SEPARATOR && false !== strpos($report['message'], 'error code(1314)')) {
  303. throw new IOException('Unable to create symlink due to error code 1314: \'A required privilege is not held by the client\'. Do you have the required Administrator-rights?', 0, null, $targetDir);
  304. }
  305. }
  306. throw new IOException(sprintf('Failed to create symbolic link from "%s" to "%s".', $originDir, $targetDir), 0, null, $targetDir);
  307. }
  308. }
  309. /**
  310. * Given an existing path, convert it to a path relative to a given starting path.
  311. *
  312. * @param string $endPath Absolute path of target
  313. * @param string $startPath Absolute path where traversal begins
  314. *
  315. * @return string Path of target relative to starting path
  316. */
  317. public function makePathRelative($endPath, $startPath)
  318. {
  319. // Normalize separators on Windows
  320. if ('\\' === DIRECTORY_SEPARATOR) {
  321. $endPath = str_replace('\\', '/', $endPath);
  322. $startPath = str_replace('\\', '/', $startPath);
  323. }
  324. // Split the paths into arrays
  325. $startPathArr = explode('/', trim($startPath, '/'));
  326. $endPathArr = explode('/', trim($endPath, '/'));
  327. // Find for which directory the common path stops
  328. $index = 0;
  329. while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {
  330. ++$index;
  331. }
  332. // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels)
  333. $depth = count($startPathArr) - $index;
  334. // When we need to traverse from the start, and we are starting from a root path, don't add '../'
  335. if ('/' === $startPath[0] && 0 === $index && 1 === $depth) {
  336. $traverser = '';
  337. } else {
  338. // Repeated "../" for each level need to reach the common path
  339. $traverser = str_repeat('../', $depth);
  340. }
  341. $endPathRemainder = implode('/', array_slice($endPathArr, $index));
  342. // Construct $endPath from traversing to the common path, then to the remaining $endPath
  343. $relativePath = $traverser.('' !== $endPathRemainder ? $endPathRemainder.'/' : '');
  344. return '' === $relativePath ? './' : $relativePath;
  345. }
  346. /**
  347. * Mirrors a directory to another.
  348. *
  349. * @param string $originDir The origin directory
  350. * @param string $targetDir The target directory
  351. * @param \Traversable $iterator A Traversable instance
  352. * @param array $options An array of boolean options
  353. * Valid options are:
  354. * - $options['override'] Whether to override an existing file on copy or not (see copy())
  355. * - $options['copy_on_windows'] Whether to copy files instead of links on Windows (see symlink())
  356. * - $options['delete'] Whether to delete files that are not in the source directory (defaults to false)
  357. *
  358. * @throws IOException When file type is unknown
  359. */
  360. public function mirror($originDir, $targetDir, \Traversable $iterator = null, $options = array())
  361. {
  362. $targetDir = rtrim($targetDir, '/\\');
  363. $originDir = rtrim($originDir, '/\\');
  364. // Iterate in destination folder to remove obsolete entries
  365. if ($this->exists($targetDir) && isset($options['delete']) && $options['delete']) {
  366. $deleteIterator = $iterator;
  367. if (null === $deleteIterator) {
  368. $flags = \FilesystemIterator::SKIP_DOTS;
  369. $deleteIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($targetDir, $flags), \RecursiveIteratorIterator::CHILD_FIRST);
  370. }
  371. foreach ($deleteIterator as $file) {
  372. $origin = str_replace($targetDir, $originDir, $file->getPathname());
  373. if (!$this->exists($origin)) {
  374. $this->remove($file);
  375. }
  376. }
  377. }
  378. $copyOnWindows = false;
  379. if (isset($options['copy_on_windows'])) {
  380. $copyOnWindows = $options['copy_on_windows'];
  381. }
  382. if (null === $iterator) {
  383. $flags = $copyOnWindows ? \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS : \FilesystemIterator::SKIP_DOTS;
  384. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($originDir, $flags), \RecursiveIteratorIterator::SELF_FIRST);
  385. }
  386. if ($this->exists($originDir)) {
  387. $this->mkdir($targetDir);
  388. }
  389. foreach ($iterator as $file) {
  390. $target = str_replace($originDir, $targetDir, $file->getPathname());
  391. if ($copyOnWindows) {
  392. if (is_file($file)) {
  393. $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
  394. } elseif (is_dir($file)) {
  395. $this->mkdir($target);
  396. } else {
  397. throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
  398. }
  399. } else {
  400. if (is_link($file)) {
  401. $this->symlink($file->getLinkTarget(), $target);
  402. } elseif (is_dir($file)) {
  403. $this->mkdir($target);
  404. } elseif (is_file($file)) {
  405. $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
  406. } else {
  407. throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
  408. }
  409. }
  410. }
  411. }
  412. /**
  413. * Returns whether the file path is an absolute path.
  414. *
  415. * @param string $file A file path
  416. *
  417. * @return bool
  418. */
  419. public function isAbsolutePath($file)
  420. {
  421. return strspn($file, '/\\', 0, 1)
  422. || (strlen($file) > 3 && ctype_alpha($file[0])
  423. && substr($file, 1, 1) === ':'
  424. && strspn($file, '/\\', 2, 1)
  425. )
  426. || null !== parse_url($file, PHP_URL_SCHEME)
  427. ;
  428. }
  429. /**
  430. * Creates a temporary file with support for custom stream wrappers.
  431. *
  432. * @param string $dir The directory where the temporary filename will be created
  433. * @param string $prefix The prefix of the generated temporary filename
  434. * Note: Windows uses only the first three characters of prefix
  435. *
  436. * @return string The new temporary filename (with path), or throw an exception on failure
  437. */
  438. public function tempnam($dir, $prefix)
  439. {
  440. list($scheme, $hierarchy) = $this->getSchemeAndHierarchy($dir);
  441. // If no scheme or scheme is "file" or "gs" (Google Cloud) create temp file in local filesystem
  442. if (null === $scheme || 'file' === $scheme || 'gs' === $scheme) {
  443. $tmpFile = @tempnam($hierarchy, $prefix);
  444. // If tempnam failed or no scheme return the filename otherwise prepend the scheme
  445. if (false !== $tmpFile) {
  446. if (null !== $scheme && 'gs' !== $scheme) {
  447. return $scheme.'://'.$tmpFile;
  448. }
  449. return $tmpFile;
  450. }
  451. throw new IOException('A temporary file could not be created.');
  452. }
  453. // Loop until we create a valid temp file or have reached 10 attempts
  454. for ($i = 0; $i < 10; ++$i) {
  455. // Create a unique filename
  456. $tmpFile = $dir.'/'.$prefix.uniqid(mt_rand(), true);
  457. // Use fopen instead of file_exists as some streams do not support stat
  458. // Use mode 'x+' to atomically check existence and create to avoid a TOCTOU vulnerability
  459. $handle = @fopen($tmpFile, 'x+');
  460. // If unsuccessful restart the loop
  461. if (false === $handle) {
  462. continue;
  463. }
  464. // Close the file if it was successfully opened
  465. @fclose($handle);
  466. return $tmpFile;
  467. }
  468. throw new IOException('A temporary file could not be created.');
  469. }
  470. /**
  471. * Atomically dumps content into a file.
  472. *
  473. * @param string $filename The file to be written to
  474. * @param string $content The data to write into the file
  475. *
  476. * @throws IOException If the file cannot be written to.
  477. */
  478. public function dumpFile($filename, $content)
  479. {
  480. $dir = dirname($filename);
  481. if (!is_dir($dir)) {
  482. $this->mkdir($dir);
  483. } elseif (!is_writable($dir)) {
  484. throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir);
  485. }
  486. // Will create a temp file with 0600 access rights
  487. // when the filesystem supports chmod.
  488. $tmpFile = $this->tempnam($dir, basename($filename));
  489. if (false === @file_put_contents($tmpFile, $content)) {
  490. throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
  491. }
  492. // Ignore for filesystems that do not support umask
  493. @chmod($tmpFile, 0666);
  494. $this->rename($tmpFile, $filename, true);
  495. }
  496. /**
  497. * @param mixed $files
  498. *
  499. * @return \Traversable
  500. */
  501. private function toIterator($files)
  502. {
  503. if (!$files instanceof \Traversable) {
  504. $files = new \ArrayObject(is_array($files) ? $files : array($files));
  505. }
  506. return $files;
  507. }
  508. /**
  509. * Gets a 2-tuple of scheme (may be null) and hierarchical part of a filename (e.g. file:///tmp -> array(file, tmp)).
  510. *
  511. * @param string $filename The filename to be parsed
  512. *
  513. * @return array The filename scheme and hierarchical part
  514. */
  515. private function getSchemeAndHierarchy($filename)
  516. {
  517. $components = explode('://', $filename, 2);
  518. return 2 === count($components) ? array($components[0], $components[1]) : array(null, $components[0]);
  519. }
  520. }