Filesystem.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. * This method only copies the file if the origin file is newer than the target file.
  24. *
  25. * By default, if the target already exists, it is not overridden.
  26. *
  27. * @param string $originFile The original filename
  28. * @param string $targetFile The target filename
  29. * @param bool $override Whether to override an existing file or not
  30. *
  31. * @throws FileNotFoundException When originFile doesn't exist
  32. * @throws IOException When copy fails
  33. */
  34. public function copy($originFile, $targetFile, $override = 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. if (!$override && is_file($targetFile) && null === parse_url($originFile, PHP_URL_HOST)) {
  41. $doCopy = filemtime($originFile) > filemtime($targetFile);
  42. } else {
  43. $doCopy = true;
  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 (stream_is_local($originFile) && $bytesCopied !== filesize($originFile)) {
  62. throw new IOException(sprintf('Failed to copy the whole content of "%s" to "%s %g bytes copied".', $originFile, $targetFile, $bytesCopied), 0, null, $originFile);
  63. }
  64. }
  65. }
  66. /**
  67. * Creates a directory recursively.
  68. *
  69. * @param string|array|\Traversable $dirs The directory path
  70. * @param int $mode The directory mode
  71. *
  72. * @throws IOException On any directory creation failure
  73. */
  74. public function mkdir($dirs, $mode = 0777)
  75. {
  76. foreach ($this->toIterator($dirs) as $dir) {
  77. if (is_dir($dir)) {
  78. continue;
  79. }
  80. if (true !== @mkdir($dir, $mode, true)) {
  81. $error = error_get_last();
  82. if (!is_dir($dir)) {
  83. // The directory was not created by a concurrent process. Let's throw an exception with a developer friendly error message if we have one
  84. if ($error) {
  85. throw new IOException(sprintf('Failed to create "%s": %s.', $dir, $error['message']), 0, null, $dir);
  86. }
  87. throw new IOException(sprintf('Failed to create "%s"', $dir), 0, null, $dir);
  88. }
  89. }
  90. }
  91. }
  92. /**
  93. * Checks the existence of files or directories.
  94. *
  95. * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to check
  96. *
  97. * @return bool true if the file exists, false otherwise
  98. */
  99. public function exists($files)
  100. {
  101. foreach ($this->toIterator($files) as $file) {
  102. if (!file_exists($file)) {
  103. return false;
  104. }
  105. }
  106. return true;
  107. }
  108. /**
  109. * Sets access and modification time of file.
  110. *
  111. * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to create
  112. * @param int $time The touch time as a Unix timestamp
  113. * @param int $atime The access time as a Unix timestamp
  114. *
  115. * @throws IOException When touch fails
  116. */
  117. public function touch($files, $time = null, $atime = null)
  118. {
  119. foreach ($this->toIterator($files) as $file) {
  120. $touch = $time ? @touch($file, $time, $atime) : @touch($file);
  121. if (true !== $touch) {
  122. throw new IOException(sprintf('Failed to touch "%s".', $file), 0, null, $file);
  123. }
  124. }
  125. }
  126. /**
  127. * Removes files or directories.
  128. *
  129. * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to remove
  130. *
  131. * @throws IOException When removal fails
  132. */
  133. public function remove($files)
  134. {
  135. $files = iterator_to_array($this->toIterator($files));
  136. $files = array_reverse($files);
  137. foreach ($files as $file) {
  138. if (!file_exists($file) && !is_link($file)) {
  139. continue;
  140. }
  141. if (is_dir($file) && !is_link($file)) {
  142. $this->remove(new \FilesystemIterator($file));
  143. if (true !== @rmdir($file)) {
  144. throw new IOException(sprintf('Failed to remove directory "%s".', $file), 0, null, $file);
  145. }
  146. } else {
  147. // https://bugs.php.net/bug.php?id=52176
  148. if (defined('PHP_WINDOWS_VERSION_MAJOR') && is_dir($file)) {
  149. if (true !== @rmdir($file)) {
  150. throw new IOException(sprintf('Failed to remove file "%s".', $file), 0, null, $file);
  151. }
  152. } else {
  153. if (true !== @unlink($file)) {
  154. throw new IOException(sprintf('Failed to remove file "%s".', $file), 0, null, $file);
  155. }
  156. }
  157. }
  158. }
  159. }
  160. /**
  161. * Change mode for an array of files or directories.
  162. *
  163. * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change mode
  164. * @param int $mode The new mode (octal)
  165. * @param int $umask The mode mask (octal)
  166. * @param bool $recursive Whether change the mod recursively or not
  167. *
  168. * @throws IOException When the change fail
  169. */
  170. public function chmod($files, $mode, $umask = 0000, $recursive = false)
  171. {
  172. foreach ($this->toIterator($files) as $file) {
  173. if ($recursive && is_dir($file) && !is_link($file)) {
  174. $this->chmod(new \FilesystemIterator($file), $mode, $umask, true);
  175. }
  176. if (true !== @chmod($file, $mode & ~$umask)) {
  177. throw new IOException(sprintf('Failed to chmod file "%s".', $file), 0, null, $file);
  178. }
  179. }
  180. }
  181. /**
  182. * Change the owner of an array of files or directories
  183. *
  184. * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change owner
  185. * @param string $user The new owner user name
  186. * @param bool $recursive Whether change the owner recursively or not
  187. *
  188. * @throws IOException When the change fail
  189. */
  190. public function chown($files, $user, $recursive = false)
  191. {
  192. foreach ($this->toIterator($files) as $file) {
  193. if ($recursive && is_dir($file) && !is_link($file)) {
  194. $this->chown(new \FilesystemIterator($file), $user, true);
  195. }
  196. if (is_link($file) && function_exists('lchown')) {
  197. if (true !== @lchown($file, $user)) {
  198. throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
  199. }
  200. } else {
  201. if (true !== @chown($file, $user)) {
  202. throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
  203. }
  204. }
  205. }
  206. }
  207. /**
  208. * Change the group of an array of files or directories
  209. *
  210. * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change group
  211. * @param string $group The group name
  212. * @param bool $recursive Whether change the group recursively or not
  213. *
  214. * @throws IOException When the change fail
  215. */
  216. public function chgrp($files, $group, $recursive = false)
  217. {
  218. foreach ($this->toIterator($files) as $file) {
  219. if ($recursive && is_dir($file) && !is_link($file)) {
  220. $this->chgrp(new \FilesystemIterator($file), $group, true);
  221. }
  222. if (is_link($file) && function_exists('lchgrp')) {
  223. if (true !== @lchgrp($file, $group)) {
  224. throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
  225. }
  226. } else {
  227. if (true !== @chgrp($file, $group)) {
  228. throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
  229. }
  230. }
  231. }
  232. }
  233. /**
  234. * Renames a file or a directory.
  235. *
  236. * @param string $origin The origin filename or directory
  237. * @param string $target The new filename or directory
  238. * @param bool $overwrite Whether to overwrite the target if it already exists
  239. *
  240. * @throws IOException When target file or directory already exists
  241. * @throws IOException When origin cannot be renamed
  242. */
  243. public function rename($origin, $target, $overwrite = false)
  244. {
  245. // we check that target does not exist
  246. if (!$overwrite && is_readable($target)) {
  247. throw new IOException(sprintf('Cannot rename because the target "%s" already exists.', $target), 0, null, $target);
  248. }
  249. if (true !== @rename($origin, $target)) {
  250. throw new IOException(sprintf('Cannot rename "%s" to "%s".', $origin, $target), 0, null, $target);
  251. }
  252. }
  253. /**
  254. * Creates a symbolic link or copy a directory.
  255. *
  256. * @param string $originDir The origin directory path
  257. * @param string $targetDir The symbolic link name
  258. * @param bool $copyOnWindows Whether to copy files if on Windows
  259. *
  260. * @throws IOException When symlink fails
  261. */
  262. public function symlink($originDir, $targetDir, $copyOnWindows = false)
  263. {
  264. $onWindows = strtoupper(substr(php_uname('s'), 0, 3)) === 'WIN';
  265. if ($onWindows && $copyOnWindows) {
  266. $this->mirror($originDir, $targetDir);
  267. return;
  268. }
  269. $this->mkdir(dirname($targetDir));
  270. $ok = false;
  271. if (is_link($targetDir)) {
  272. if (readlink($targetDir) != $originDir) {
  273. $this->remove($targetDir);
  274. } else {
  275. $ok = true;
  276. }
  277. }
  278. if (!$ok) {
  279. if (true !== @symlink($originDir, $targetDir)) {
  280. $report = error_get_last();
  281. if (is_array($report)) {
  282. if (defined('PHP_WINDOWS_VERSION_MAJOR') && false !== strpos($report['message'], 'error code(1314)')) {
  283. 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?');
  284. }
  285. }
  286. throw new IOException(sprintf('Failed to create symbolic link from "%s" to "%s".', $originDir, $targetDir), 0, null, $targetDir);
  287. }
  288. if (!file_exists($targetDir)) {
  289. throw new IOException(sprintf('Symbolic link "%s" is created but appears to be broken.', $targetDir), 0, null, $targetDir);
  290. }
  291. }
  292. }
  293. /**
  294. * Given an existing path, convert it to a path relative to a given starting path
  295. *
  296. * @param string $endPath Absolute path of target
  297. * @param string $startPath Absolute path where traversal begins
  298. *
  299. * @return string Path of target relative to starting path
  300. */
  301. public function makePathRelative($endPath, $startPath)
  302. {
  303. // Normalize separators on Windows
  304. if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
  305. $endPath = strtr($endPath, '\\', '/');
  306. $startPath = strtr($startPath, '\\', '/');
  307. }
  308. // Split the paths into arrays
  309. $startPathArr = explode('/', trim($startPath, '/'));
  310. $endPathArr = explode('/', trim($endPath, '/'));
  311. // Find for which directory the common path stops
  312. $index = 0;
  313. while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {
  314. $index++;
  315. }
  316. // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels)
  317. $depth = count($startPathArr) - $index;
  318. // Repeated "../" for each level need to reach the common path
  319. $traverser = str_repeat('../', $depth);
  320. $endPathRemainder = implode('/', array_slice($endPathArr, $index));
  321. // Construct $endPath from traversing to the common path, then to the remaining $endPath
  322. $relativePath = $traverser.(strlen($endPathRemainder) > 0 ? $endPathRemainder.'/' : '');
  323. return (strlen($relativePath) === 0) ? './' : $relativePath;
  324. }
  325. /**
  326. * Mirrors a directory to another.
  327. *
  328. * @param string $originDir The origin directory
  329. * @param string $targetDir The target directory
  330. * @param \Traversable $iterator A Traversable instance
  331. * @param array $options An array of boolean options
  332. * Valid options are:
  333. * - $options['override'] Whether to override an existing file on copy or not (see copy())
  334. * - $options['copy_on_windows'] Whether to copy files instead of links on Windows (see symlink())
  335. * - $options['delete'] Whether to delete files that are not in the source directory (defaults to false)
  336. *
  337. * @throws IOException When file type is unknown
  338. */
  339. public function mirror($originDir, $targetDir, \Traversable $iterator = null, $options = array())
  340. {
  341. $targetDir = rtrim($targetDir, '/\\');
  342. $originDir = rtrim($originDir, '/\\');
  343. // Iterate in destination folder to remove obsolete entries
  344. if ($this->exists($targetDir) && isset($options['delete']) && $options['delete']) {
  345. $deleteIterator = $iterator;
  346. if (null === $deleteIterator) {
  347. $flags = \FilesystemIterator::SKIP_DOTS;
  348. $deleteIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($targetDir, $flags), \RecursiveIteratorIterator::CHILD_FIRST);
  349. }
  350. foreach ($deleteIterator as $file) {
  351. $origin = str_replace($targetDir, $originDir, $file->getPathname());
  352. if (!$this->exists($origin)) {
  353. $this->remove($file);
  354. }
  355. }
  356. }
  357. $copyOnWindows = false;
  358. if (isset($options['copy_on_windows'])) {
  359. $copyOnWindows = $options['copy_on_windows'];
  360. }
  361. if (null === $iterator) {
  362. $flags = $copyOnWindows ? \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS : \FilesystemIterator::SKIP_DOTS;
  363. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($originDir, $flags), \RecursiveIteratorIterator::SELF_FIRST);
  364. }
  365. if ($this->exists($originDir)) {
  366. $this->mkdir($targetDir);
  367. }
  368. foreach ($iterator as $file) {
  369. $target = str_replace($originDir, $targetDir, $file->getPathname());
  370. if ($copyOnWindows) {
  371. if (is_link($file) || is_file($file)) {
  372. $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
  373. } elseif (is_dir($file)) {
  374. $this->mkdir($target);
  375. } else {
  376. throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
  377. }
  378. } else {
  379. if (is_link($file)) {
  380. $this->symlink($file->getLinkTarget(), $target);
  381. } elseif (is_dir($file)) {
  382. $this->mkdir($target);
  383. } elseif (is_file($file)) {
  384. $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
  385. } else {
  386. throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
  387. }
  388. }
  389. }
  390. }
  391. /**
  392. * Returns whether the file path is an absolute path.
  393. *
  394. * @param string $file A file path
  395. *
  396. * @return bool
  397. */
  398. public function isAbsolutePath($file)
  399. {
  400. if (strspn($file, '/\\', 0, 1)
  401. || (strlen($file) > 3 && ctype_alpha($file[0])
  402. && substr($file, 1, 1) === ':'
  403. && (strspn($file, '/\\', 2, 1))
  404. )
  405. || null !== parse_url($file, PHP_URL_SCHEME)
  406. ) {
  407. return true;
  408. }
  409. return false;
  410. }
  411. /**
  412. * Atomically dumps content into a file.
  413. *
  414. * @param string $filename The file to be written to.
  415. * @param string $content The data to write into the file.
  416. * @param null|int $mode The file mode (octal). If null, file permissions are not modified
  417. * Deprecated since version 2.3.12, to be removed in 3.0.
  418. *
  419. * @throws IOException If the file cannot be written to.
  420. */
  421. public function dumpFile($filename, $content, $mode = 0666)
  422. {
  423. $dir = dirname($filename);
  424. if (!is_dir($dir)) {
  425. $this->mkdir($dir);
  426. } elseif (!is_writable($dir)) {
  427. throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir);
  428. }
  429. $tmpFile = tempnam($dir, basename($filename));
  430. if (false === @file_put_contents($tmpFile, $content)) {
  431. throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
  432. }
  433. $this->rename($tmpFile, $filename, true);
  434. if (null !== $mode) {
  435. $this->chmod($filename, $mode);
  436. }
  437. }
  438. /**
  439. * @param mixed $files
  440. *
  441. * @return \Traversable
  442. */
  443. private function toIterator($files)
  444. {
  445. if (!$files instanceof \Traversable) {
  446. $files = new \ArrayObject(is_array($files) ? $files : array($files));
  447. }
  448. return $files;
  449. }
  450. }