PageRenderTime 50ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/symfony/symfony/src/Symfony/Component/Filesystem/Filesystem.php

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