4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Filesystem;
14 use Symfony\Component\Filesystem\Exception\IOException;
15 use Symfony\Component\Filesystem\Exception\FileNotFoundException;
18 * Provides basic utility to manipulate the file system.
20 * @author Fabien Potencier <fabien@symfony.com>
27 * If the target file is older than the origin file, it's always overwritten.
28 * If the target file is newer, it is overwritten only when the
29 * $overwriteNewerFiles option is set to true.
31 * @param string $originFile The original filename
32 * @param string $targetFile The target filename
33 * @param bool $overwriteNewerFiles If true, target files newer than origin files are overwritten
35 * @throws FileNotFoundException When originFile doesn't exist
36 * @throws IOException When copy fails
38 public function copy($originFile, $targetFile, $overwriteNewerFiles = false)
40 $originIsLocal = stream_is_local($originFile) || 0 === stripos($originFile, 'file://');
41 if ($originIsLocal && !is_file($originFile)) {
42 throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile);
45 $this->mkdir(dirname($targetFile));
48 if (!$overwriteNewerFiles && null === parse_url($originFile, PHP_URL_HOST) && is_file($targetFile)) {
49 $doCopy = filemtime($originFile) > filemtime($targetFile);
53 // https://bugs.php.net/bug.php?id=64634
54 if (false === $source = @fopen($originFile, 'r')) {
55 throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile);
58 // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default
59 if (false === $target = @fopen($targetFile, 'w', null, stream_context_create(array('ftp' => array('overwrite' => true))))) {
60 throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile);
63 $bytesCopied = stream_copy_to_stream($source, $target);
66 unset($source, $target);
68 if (!is_file($targetFile)) {
69 throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile);
73 // Like `cp`, preserve executable permission bits
74 @chmod($targetFile, fileperms($targetFile) | (fileperms($originFile) & 0111));
76 if ($bytesCopied !== $bytesOrigin = filesize($originFile)) {
77 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);
84 * Creates a directory recursively.
86 * @param string|iterable $dirs The directory path
87 * @param int $mode The directory mode
89 * @throws IOException On any directory creation failure
91 public function mkdir($dirs, $mode = 0777)
93 foreach ($this->toIterator($dirs) as $dir) {
98 if (true !== @mkdir($dir, $mode, true)) {
99 $error = error_get_last();
101 // The directory was not created by a concurrent process. Let's throw an exception with a developer friendly error message if we have one
103 throw new IOException(sprintf('Failed to create "%s": %s.', $dir, $error['message']), 0, null, $dir);
105 throw new IOException(sprintf('Failed to create "%s"', $dir), 0, null, $dir);
112 * Checks the existence of files or directories.
114 * @param string|iterable $files A filename, an array of files, or a \Traversable instance to check
116 * @return bool true if the file exists, false otherwise
118 public function exists($files)
120 $maxPathLength = PHP_MAXPATHLEN - 2;
122 foreach ($this->toIterator($files) as $file) {
123 if (strlen($file) > $maxPathLength) {
124 throw new IOException(sprintf('Could not check if file exist because path length exceeds %d characters.', $maxPathLength), 0, null, $file);
127 if (!file_exists($file)) {
136 * Sets access and modification time of file.
138 * @param string|iterable $files A filename, an array of files, or a \Traversable instance to create
139 * @param int $time The touch time as a Unix timestamp
140 * @param int $atime The access time as a Unix timestamp
142 * @throws IOException When touch fails
144 public function touch($files, $time = null, $atime = null)
146 foreach ($this->toIterator($files) as $file) {
147 $touch = $time ? @touch($file, $time, $atime) : @touch($file);
148 if (true !== $touch) {
149 throw new IOException(sprintf('Failed to touch "%s".', $file), 0, null, $file);
155 * Removes files or directories.
157 * @param string|iterable $files A filename, an array of files, or a \Traversable instance to remove
159 * @throws IOException When removal fails
161 public function remove($files)
163 if ($files instanceof \Traversable) {
164 $files = iterator_to_array($files, false);
165 } elseif (!is_array($files)) {
166 $files = array($files);
168 $files = array_reverse($files);
169 foreach ($files as $file) {
170 if (is_link($file)) {
171 // See https://bugs.php.net/52176
172 if (!@(unlink($file) || '\\' !== DIRECTORY_SEPARATOR || rmdir($file)) && file_exists($file)) {
173 $error = error_get_last();
174 throw new IOException(sprintf('Failed to remove symlink "%s": %s.', $file, $error['message']));
176 } elseif (is_dir($file)) {
177 $this->remove(new \FilesystemIterator($file, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS));
179 if (!@rmdir($file) && file_exists($file)) {
180 $error = error_get_last();
181 throw new IOException(sprintf('Failed to remove directory "%s": %s.', $file, $error['message']));
183 } elseif (!@unlink($file) && file_exists($file)) {
184 $error = error_get_last();
185 throw new IOException(sprintf('Failed to remove file "%s": %s.', $file, $error['message']));
191 * Change mode for an array of files or directories.
193 * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change mode
194 * @param int $mode The new mode (octal)
195 * @param int $umask The mode mask (octal)
196 * @param bool $recursive Whether change the mod recursively or not
198 * @throws IOException When the change fail
200 public function chmod($files, $mode, $umask = 0000, $recursive = false)
202 foreach ($this->toIterator($files) as $file) {
203 if (true !== @chmod($file, $mode & ~$umask)) {
204 throw new IOException(sprintf('Failed to chmod file "%s".', $file), 0, null, $file);
206 if ($recursive && is_dir($file) && !is_link($file)) {
207 $this->chmod(new \FilesystemIterator($file), $mode, $umask, true);
213 * Change the owner of an array of files or directories.
215 * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change owner
216 * @param string $user The new owner user name
217 * @param bool $recursive Whether change the owner recursively or not
219 * @throws IOException When the change fail
221 public function chown($files, $user, $recursive = false)
223 foreach ($this->toIterator($files) as $file) {
224 if ($recursive && is_dir($file) && !is_link($file)) {
225 $this->chown(new \FilesystemIterator($file), $user, true);
227 if (is_link($file) && function_exists('lchown')) {
228 if (true !== @lchown($file, $user)) {
229 throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
232 if (true !== @chown($file, $user)) {
233 throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
240 * Change the group of an array of files or directories.
242 * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change group
243 * @param string $group The group name
244 * @param bool $recursive Whether change the group recursively or not
246 * @throws IOException When the change fail
248 public function chgrp($files, $group, $recursive = false)
250 foreach ($this->toIterator($files) as $file) {
251 if ($recursive && is_dir($file) && !is_link($file)) {
252 $this->chgrp(new \FilesystemIterator($file), $group, true);
254 if (is_link($file) && function_exists('lchgrp')) {
255 if (true !== @lchgrp($file, $group) || (defined('HHVM_VERSION') && !posix_getgrnam($group))) {
256 throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
259 if (true !== @chgrp($file, $group)) {
260 throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
267 * Renames a file or a directory.
269 * @param string $origin The origin filename or directory
270 * @param string $target The new filename or directory
271 * @param bool $overwrite Whether to overwrite the target if it already exists
273 * @throws IOException When target file or directory already exists
274 * @throws IOException When origin cannot be renamed
276 public function rename($origin, $target, $overwrite = false)
278 // we check that target does not exist
279 if (!$overwrite && $this->isReadable($target)) {
280 throw new IOException(sprintf('Cannot rename because the target "%s" already exists.', $target), 0, null, $target);
283 if (true !== @rename($origin, $target)) {
284 if (is_dir($origin)) {
285 // See https://bugs.php.net/bug.php?id=54097 & http://php.net/manual/en/function.rename.php#113943
286 $this->mirror($origin, $target, null, array('override' => $overwrite, 'delete' => $overwrite));
287 $this->remove($origin);
291 throw new IOException(sprintf('Cannot rename "%s" to "%s".', $origin, $target), 0, null, $target);
296 * Tells whether a file exists and is readable.
298 * @param string $filename Path to the file
302 * @throws IOException When windows path is longer than 258 characters
304 private function isReadable($filename)
306 $maxPathLength = PHP_MAXPATHLEN - 2;
308 if (strlen($filename) > $maxPathLength) {
309 throw new IOException(sprintf('Could not check if file is readable because path length exceeds %d characters.', $maxPathLength), 0, null, $filename);
312 return is_readable($filename);
316 * Creates a symbolic link or copy a directory.
318 * @param string $originDir The origin directory path
319 * @param string $targetDir The symbolic link name
320 * @param bool $copyOnWindows Whether to copy files if on Windows
322 * @throws IOException When symlink fails
324 public function symlink($originDir, $targetDir, $copyOnWindows = false)
326 if ('\\' === DIRECTORY_SEPARATOR) {
327 $originDir = strtr($originDir, '/', '\\');
328 $targetDir = strtr($targetDir, '/', '\\');
330 if ($copyOnWindows) {
331 $this->mirror($originDir, $targetDir);
337 $this->mkdir(dirname($targetDir));
340 if (is_link($targetDir)) {
341 if (readlink($targetDir) != $originDir) {
342 $this->remove($targetDir);
348 if (!$ok && true !== @symlink($originDir, $targetDir)) {
349 $report = error_get_last();
350 if (is_array($report)) {
351 if ('\\' === DIRECTORY_SEPARATOR && false !== strpos($report['message'], 'error code(1314)')) {
352 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);
355 throw new IOException(sprintf('Failed to create symbolic link from "%s" to "%s".', $originDir, $targetDir), 0, null, $targetDir);
360 * Given an existing path, convert it to a path relative to a given starting path.
362 * @param string $endPath Absolute path of target
363 * @param string $startPath Absolute path where traversal begins
365 * @return string Path of target relative to starting path
367 public function makePathRelative($endPath, $startPath)
369 // Normalize separators on Windows
370 if ('\\' === DIRECTORY_SEPARATOR) {
371 $endPath = str_replace('\\', '/', $endPath);
372 $startPath = str_replace('\\', '/', $startPath);
375 $stripDriveLetter = function ($path) {
376 if (strlen($path) > 2 && ':' === $path[1] && '/' === $path[2] && ctype_alpha($path[0])) {
377 return substr($path, 2);
383 $endPath = $stripDriveLetter($endPath);
384 $startPath = $stripDriveLetter($startPath);
386 // Split the paths into arrays
387 $startPathArr = explode('/', trim($startPath, '/'));
388 $endPathArr = explode('/', trim($endPath, '/'));
390 $normalizePathArray = function ($pathSegments, $absolute) {
393 foreach ($pathSegments as $segment) {
394 if ('..' === $segment && ($absolute || count($result))) {
396 } elseif ('.' !== $segment) {
397 $result[] = $segment;
404 $startPathArr = $normalizePathArray($startPathArr, static::isAbsolutePath($startPath));
405 $endPathArr = $normalizePathArray($endPathArr, static::isAbsolutePath($endPath));
407 // Find for which directory the common path stops
409 while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {
413 // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels)
414 if (1 === count($startPathArr) && '' === $startPathArr[0]) {
417 $depth = count($startPathArr) - $index;
420 // Repeated "../" for each level need to reach the common path
421 $traverser = str_repeat('../', $depth);
423 $endPathRemainder = implode('/', array_slice($endPathArr, $index));
425 // Construct $endPath from traversing to the common path, then to the remaining $endPath
426 $relativePath = $traverser.('' !== $endPathRemainder ? $endPathRemainder.'/' : '');
428 return '' === $relativePath ? './' : $relativePath;
432 * Mirrors a directory to another.
434 * Copies files and directories from the origin directory into the target directory. By default:
436 * - existing files in the target directory will be overwritten, except if they are newer (see the `override` option)
437 * - files in the target directory that do not exist in the source directory will not be deleted (see the `delete` option)
439 * @param string $originDir The origin directory
440 * @param string $targetDir The target directory
441 * @param \Traversable $iterator Iterator that filters which files and directories to copy
442 * @param array $options An array of boolean options
444 * - $options['override'] If true, target files newer than origin files are overwritten (see copy(), defaults to false)
445 * - $options['copy_on_windows'] Whether to copy files instead of links on Windows (see symlink(), defaults to false)
446 * - $options['delete'] Whether to delete files that are not in the source directory (defaults to false)
448 * @throws IOException When file type is unknown
450 public function mirror($originDir, $targetDir, \Traversable $iterator = null, $options = array())
452 $targetDir = rtrim($targetDir, '/\\');
453 $originDir = rtrim($originDir, '/\\');
454 $originDirLen = strlen($originDir);
456 // Iterate in destination folder to remove obsolete entries
457 if ($this->exists($targetDir) && isset($options['delete']) && $options['delete']) {
458 $deleteIterator = $iterator;
459 if (null === $deleteIterator) {
460 $flags = \FilesystemIterator::SKIP_DOTS;
461 $deleteIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($targetDir, $flags), \RecursiveIteratorIterator::CHILD_FIRST);
463 $targetDirLen = strlen($targetDir);
464 foreach ($deleteIterator as $file) {
465 $origin = $originDir.substr($file->getPathname(), $targetDirLen);
466 if (!$this->exists($origin)) {
467 $this->remove($file);
472 $copyOnWindows = false;
473 if (isset($options['copy_on_windows'])) {
474 $copyOnWindows = $options['copy_on_windows'];
477 if (null === $iterator) {
478 $flags = $copyOnWindows ? \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS : \FilesystemIterator::SKIP_DOTS;
479 $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($originDir, $flags), \RecursiveIteratorIterator::SELF_FIRST);
482 if ($this->exists($originDir)) {
483 $this->mkdir($targetDir);
486 foreach ($iterator as $file) {
487 $target = $targetDir.substr($file->getPathname(), $originDirLen);
489 if ($copyOnWindows) {
490 if (is_file($file)) {
491 $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
492 } elseif (is_dir($file)) {
493 $this->mkdir($target);
495 throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
498 if (is_link($file)) {
499 $this->symlink($file->getLinkTarget(), $target);
500 } elseif (is_dir($file)) {
501 $this->mkdir($target);
502 } elseif (is_file($file)) {
503 $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
505 throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
512 * Returns whether the file path is an absolute path.
514 * @param string $file A file path
518 public function isAbsolutePath($file)
520 return strspn($file, '/\\', 0, 1)
521 || (strlen($file) > 3 && ctype_alpha($file[0])
522 && ':' === substr($file, 1, 1)
523 && strspn($file, '/\\', 2, 1)
525 || null !== parse_url($file, PHP_URL_SCHEME)
530 * Creates a temporary file with support for custom stream wrappers.
532 * @param string $dir The directory where the temporary filename will be created
533 * @param string $prefix The prefix of the generated temporary filename
534 * Note: Windows uses only the first three characters of prefix
536 * @return string The new temporary filename (with path), or throw an exception on failure
538 public function tempnam($dir, $prefix)
540 list($scheme, $hierarchy) = $this->getSchemeAndHierarchy($dir);
542 // If no scheme or scheme is "file" or "gs" (Google Cloud) create temp file in local filesystem
543 if (null === $scheme || 'file' === $scheme || 'gs' === $scheme) {
544 $tmpFile = @tempnam($hierarchy, $prefix);
546 // If tempnam failed or no scheme return the filename otherwise prepend the scheme
547 if (false !== $tmpFile) {
548 if (null !== $scheme && 'gs' !== $scheme) {
549 return $scheme.'://'.$tmpFile;
555 throw new IOException('A temporary file could not be created.');
558 // Loop until we create a valid temp file or have reached 10 attempts
559 for ($i = 0; $i < 10; ++$i) {
560 // Create a unique filename
561 $tmpFile = $dir.'/'.$prefix.uniqid(mt_rand(), true);
563 // Use fopen instead of file_exists as some streams do not support stat
564 // Use mode 'x+' to atomically check existence and create to avoid a TOCTOU vulnerability
565 $handle = @fopen($tmpFile, 'x+');
567 // If unsuccessful restart the loop
568 if (false === $handle) {
572 // Close the file if it was successfully opened
578 throw new IOException('A temporary file could not be created.');
582 * Atomically dumps content into a file.
584 * @param string $filename The file to be written to
585 * @param string $content The data to write into the file
586 * @param null|int $mode The file mode (octal). If null, file permissions are not modified
587 * Deprecated since version 2.3.12, to be removed in 3.0.
589 * @throws IOException if the file cannot be written to
591 public function dumpFile($filename, $content, $mode = 0666)
593 $dir = dirname($filename);
599 if (!is_writable($dir)) {
600 throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir);
603 $tmpFile = $this->tempnam($dir, basename($filename));
605 if (false === @file_put_contents($tmpFile, $content)) {
606 throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
609 if (null !== $mode) {
610 if (func_num_args() > 2) {
611 @trigger_error('Support for modifying file permissions is deprecated since Symfony 2.3.12 and will be removed in 3.0.', E_USER_DEPRECATED);
614 $this->chmod($tmpFile, $mode);
615 } elseif (file_exists($filename)) {
616 @chmod($tmpFile, fileperms($filename));
619 $this->rename($tmpFile, $filename, true);
623 * @param mixed $files
625 * @return \Traversable
627 private function toIterator($files)
629 if (!$files instanceof \Traversable) {
630 $files = new \ArrayObject(is_array($files) ? $files : array($files));
637 * Gets a 2-tuple of scheme (may be null) and hierarchical part of a filename (e.g. file:///tmp -> array(file, tmp)).
639 * @param string $filename The filename to be parsed
641 * @return array The filename scheme and hierarchical part
643 private function getSchemeAndHierarchy($filename)
645 $components = explode('://', $filename, 2);
647 return 2 === count($components) ? array($components[0], $components[1]) : array(null, $components[0]);