Filesystem.php 17 KB

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