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 if (stream_is_local($originFile) && !is_file($originFile)) {
41 throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile);
44 $this->mkdir(dirname($targetFile));
47 if (!$overwriteNewerFiles && null === parse_url($originFile, PHP_URL_HOST) && is_file($targetFile)) {
48 $doCopy = filemtime($originFile) > filemtime($targetFile);
52 // https://bugs.php.net/bug.php?id=64634
53 if (false === $source = @fopen($originFile, 'r')) {
54 throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile);
57 // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default
58 if (false === $target = @fopen($targetFile, 'w', null, stream_context_create(array('ftp' => array('overwrite' => true))))) {
59 throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile);
62 $bytesCopied = stream_copy_to_stream($source, $target);
65 unset($source, $target);
67 if (!is_file($targetFile)) {
68 throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile);
71 // Like `cp`, preserve executable permission bits
72 @chmod($targetFile, fileperms($targetFile) | (fileperms($originFile) & 0111));
74 if (stream_is_local($originFile) && $bytesCopied !== ($bytesOrigin = filesize($originFile))) {
75 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);
81 * Creates a directory recursively.
83 * @param string|array|\Traversable $dirs The directory path
84 * @param int $mode The directory mode
86 * @throws IOException On any directory creation failure
88 public function mkdir($dirs, $mode = 0777)
90 foreach ($this->toIterator($dirs) as $dir) {
95 if (true !== @mkdir($dir, $mode, true)) {
96 $error = error_get_last();
98 // The directory was not created by a concurrent process. Let's throw an exception with a developer friendly error message if we have one
100 throw new IOException(sprintf('Failed to create "%s": %s.', $dir, $error['message']), 0, null, $dir);
102 throw new IOException(sprintf('Failed to create "%s"', $dir), 0, null, $dir);
109 * Checks the existence of files or directories.
111 * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to check
113 * @return bool true if the file exists, false otherwise
115 public function exists($files)
117 foreach ($this->toIterator($files) as $file) {
118 if ('\\' === DIRECTORY_SEPARATOR && strlen($file) > 258) {
119 throw new IOException('Could not check if file exist because path length exceeds 258 characters.', 0, null, $file);
122 if (!file_exists($file)) {
131 * Sets access and modification time of file.
133 * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to create
134 * @param int $time The touch time as a Unix timestamp
135 * @param int $atime The access time as a Unix timestamp
137 * @throws IOException When touch fails
139 public function touch($files, $time = null, $atime = null)
141 foreach ($this->toIterator($files) as $file) {
142 $touch = $time ? @touch($file, $time, $atime) : @touch($file);
143 if (true !== $touch) {
144 throw new IOException(sprintf('Failed to touch "%s".', $file), 0, null, $file);
150 * Removes files or directories.
152 * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to remove
154 * @throws IOException When removal fails
156 public function remove($files)
158 if ($files instanceof \Traversable) {
159 $files = iterator_to_array($files, false);
160 } elseif (!is_array($files)) {
161 $files = array($files);
163 $files = array_reverse($files);
164 foreach ($files as $file) {
165 if (is_link($file)) {
166 // See https://bugs.php.net/52176
167 if (!@(unlink($file) || '\\' !== DIRECTORY_SEPARATOR || rmdir($file)) && file_exists($file)) {
168 $error = error_get_last();
169 throw new IOException(sprintf('Failed to remove symlink "%s": %s.', $file, $error['message']));
171 } elseif (is_dir($file)) {
172 $this->remove(new \FilesystemIterator($file, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS));
174 if (!@rmdir($file) && file_exists($file)) {
175 $error = error_get_last();
176 throw new IOException(sprintf('Failed to remove directory "%s": %s.', $file, $error['message']));
178 } elseif (!@unlink($file) && file_exists($file)) {
179 $error = error_get_last();
180 throw new IOException(sprintf('Failed to remove file "%s": %s.', $file, $error['message']));
186 * Change mode for an array of files or directories.
188 * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change mode
189 * @param int $mode The new mode (octal)
190 * @param int $umask The mode mask (octal)
191 * @param bool $recursive Whether change the mod recursively or not
193 * @throws IOException When the change fail
195 public function chmod($files, $mode, $umask = 0000, $recursive = false)
197 foreach ($this->toIterator($files) as $file) {
198 if (true !== @chmod($file, $mode & ~$umask)) {
199 throw new IOException(sprintf('Failed to chmod file "%s".', $file), 0, null, $file);
201 if ($recursive && is_dir($file) && !is_link($file)) {
202 $this->chmod(new \FilesystemIterator($file), $mode, $umask, true);
208 * Change the owner of an array of files or directories.
210 * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change owner
211 * @param string $user The new owner user name
212 * @param bool $recursive Whether change the owner recursively or not
214 * @throws IOException When the change fail
216 public function chown($files, $user, $recursive = false)
218 foreach ($this->toIterator($files) as $file) {
219 if ($recursive && is_dir($file) && !is_link($file)) {
220 $this->chown(new \FilesystemIterator($file), $user, true);
222 if (is_link($file) && function_exists('lchown')) {
223 if (true !== @lchown($file, $user)) {
224 throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
227 if (true !== @chown($file, $user)) {
228 throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
235 * Change the group of an array of files or directories.
237 * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change group
238 * @param string $group The group name
239 * @param bool $recursive Whether change the group recursively or not
241 * @throws IOException When the change fail
243 public function chgrp($files, $group, $recursive = false)
245 foreach ($this->toIterator($files) as $file) {
246 if ($recursive && is_dir($file) && !is_link($file)) {
247 $this->chgrp(new \FilesystemIterator($file), $group, true);
249 if (is_link($file) && function_exists('lchgrp')) {
250 if (true !== @lchgrp($file, $group) || (defined('HHVM_VERSION') && !posix_getgrnam($group))) {
251 throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
254 if (true !== @chgrp($file, $group)) {
255 throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
262 * Renames a file or a directory.
264 * @param string $origin The origin filename or directory
265 * @param string $target The new filename or directory
266 * @param bool $overwrite Whether to overwrite the target if it already exists
268 * @throws IOException When target file or directory already exists
269 * @throws IOException When origin cannot be renamed
271 public function rename($origin, $target, $overwrite = false)
273 // we check that target does not exist
274 if (!$overwrite && $this->isReadable($target)) {
275 throw new IOException(sprintf('Cannot rename because the target "%s" already exists.', $target), 0, null, $target);
278 if (true !== @rename($origin, $target)) {
279 throw new IOException(sprintf('Cannot rename "%s" to "%s".', $origin, $target), 0, null, $target);
284 * Tells whether a file exists and is readable.
286 * @param string $filename Path to the file
290 * @throws IOException When windows path is longer than 258 characters
292 private function isReadable($filename)
294 if ('\\' === DIRECTORY_SEPARATOR && strlen($filename) > 258) {
295 throw new IOException('Could not check if file is readable because path length exceeds 258 characters.', 0, null, $filename);
298 return is_readable($filename);
302 * Creates a symbolic link or copy a directory.
304 * @param string $originDir The origin directory path
305 * @param string $targetDir The symbolic link name
306 * @param bool $copyOnWindows Whether to copy files if on Windows
308 * @throws IOException When symlink fails
310 public function symlink($originDir, $targetDir, $copyOnWindows = false)
312 if ('\\' === DIRECTORY_SEPARATOR) {
313 $originDir = strtr($originDir, '/', '\\');
314 $targetDir = strtr($targetDir, '/', '\\');
316 if ($copyOnWindows) {
317 $this->mirror($originDir, $targetDir);
323 $this->mkdir(dirname($targetDir));
326 if (is_link($targetDir)) {
327 if (readlink($targetDir) != $originDir) {
328 $this->remove($targetDir);
334 if (!$ok && true !== @symlink($originDir, $targetDir)) {
335 $report = error_get_last();
336 if (is_array($report)) {
337 if ('\\' === DIRECTORY_SEPARATOR && false !== strpos($report['message'], 'error code(1314)')) {
338 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);
341 throw new IOException(sprintf('Failed to create symbolic link from "%s" to "%s".', $originDir, $targetDir), 0, null, $targetDir);
346 * Given an existing path, convert it to a path relative to a given starting path.
348 * @param string $endPath Absolute path of target
349 * @param string $startPath Absolute path where traversal begins
351 * @return string Path of target relative to starting path
353 public function makePathRelative($endPath, $startPath)
355 // Normalize separators on Windows
356 if ('\\' === DIRECTORY_SEPARATOR) {
357 $endPath = str_replace('\\', '/', $endPath);
358 $startPath = str_replace('\\', '/', $startPath);
361 // Split the paths into arrays
362 $startPathArr = explode('/', trim($startPath, '/'));
363 $endPathArr = explode('/', trim($endPath, '/'));
365 if ('/' !== $startPath[0]) {
366 array_shift($startPathArr);
369 if ('/' !== $endPath[0]) {
370 array_shift($endPathArr);
373 $normalizePathArray = function ($pathSegments) {
376 foreach ($pathSegments as $segment) {
377 if ('..' === $segment) {
380 $result[] = $segment;
387 $startPathArr = $normalizePathArray($startPathArr);
388 $endPathArr = $normalizePathArray($endPathArr);
390 // Find for which directory the common path stops
392 while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {
396 // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels)
397 if (count($startPathArr) === 1 && $startPathArr[0] === '') {
400 $depth = count($startPathArr) - $index;
403 // When we need to traverse from the start, and we are starting from a root path, don't add '../'
404 if ('/' === $startPath[0] && 0 === $index && 0 === $depth) {
407 // Repeated "../" for each level need to reach the common path
408 $traverser = str_repeat('../', $depth);
411 $endPathRemainder = implode('/', array_slice($endPathArr, $index));
413 // Construct $endPath from traversing to the common path, then to the remaining $endPath
414 $relativePath = $traverser.('' !== $endPathRemainder ? $endPathRemainder.'/' : '');
416 return '' === $relativePath ? './' : $relativePath;
420 * Mirrors a directory to another.
422 * @param string $originDir The origin directory
423 * @param string $targetDir The target directory
424 * @param \Traversable $iterator A Traversable instance
425 * @param array $options An array of boolean options
427 * - $options['override'] Whether to override an existing file on copy or not (see copy())
428 * - $options['copy_on_windows'] Whether to copy files instead of links on Windows (see symlink())
429 * - $options['delete'] Whether to delete files that are not in the source directory (defaults to false)
431 * @throws IOException When file type is unknown
433 public function mirror($originDir, $targetDir, \Traversable $iterator = null, $options = array())
435 $targetDir = rtrim($targetDir, '/\\');
436 $originDir = rtrim($originDir, '/\\');
438 // Iterate in destination folder to remove obsolete entries
439 if ($this->exists($targetDir) && isset($options['delete']) && $options['delete']) {
440 $deleteIterator = $iterator;
441 if (null === $deleteIterator) {
442 $flags = \FilesystemIterator::SKIP_DOTS;
443 $deleteIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($targetDir, $flags), \RecursiveIteratorIterator::CHILD_FIRST);
445 foreach ($deleteIterator as $file) {
446 $origin = str_replace($targetDir, $originDir, $file->getPathname());
447 if (!$this->exists($origin)) {
448 $this->remove($file);
453 $copyOnWindows = false;
454 if (isset($options['copy_on_windows'])) {
455 $copyOnWindows = $options['copy_on_windows'];
458 if (null === $iterator) {
459 $flags = $copyOnWindows ? \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS : \FilesystemIterator::SKIP_DOTS;
460 $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($originDir, $flags), \RecursiveIteratorIterator::SELF_FIRST);
463 if ($this->exists($originDir)) {
464 $this->mkdir($targetDir);
467 foreach ($iterator as $file) {
468 $target = str_replace($originDir, $targetDir, $file->getPathname());
470 if ($copyOnWindows) {
471 if (is_file($file)) {
472 $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
473 } elseif (is_dir($file)) {
474 $this->mkdir($target);
476 throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
479 if (is_link($file)) {
480 $this->symlink($file->getLinkTarget(), $target);
481 } elseif (is_dir($file)) {
482 $this->mkdir($target);
483 } elseif (is_file($file)) {
484 $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
486 throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
493 * Returns whether the file path is an absolute path.
495 * @param string $file A file path
499 public function isAbsolutePath($file)
501 return strspn($file, '/\\', 0, 1)
502 || (strlen($file) > 3 && ctype_alpha($file[0])
503 && substr($file, 1, 1) === ':'
504 && strspn($file, '/\\', 2, 1)
506 || null !== parse_url($file, PHP_URL_SCHEME)
511 * Creates a temporary file with support for custom stream wrappers.
513 * @param string $dir The directory where the temporary filename will be created
514 * @param string $prefix The prefix of the generated temporary filename
515 * Note: Windows uses only the first three characters of prefix
517 * @return string The new temporary filename (with path), or throw an exception on failure
519 public function tempnam($dir, $prefix)
521 list($scheme, $hierarchy) = $this->getSchemeAndHierarchy($dir);
523 // If no scheme or scheme is "file" or "gs" (Google Cloud) create temp file in local filesystem
524 if (null === $scheme || 'file' === $scheme || 'gs' === $scheme) {
525 $tmpFile = @tempnam($hierarchy, $prefix);
527 // If tempnam failed or no scheme return the filename otherwise prepend the scheme
528 if (false !== $tmpFile) {
529 if (null !== $scheme && 'gs' !== $scheme) {
530 return $scheme.'://'.$tmpFile;
536 throw new IOException('A temporary file could not be created.');
539 // Loop until we create a valid temp file or have reached 10 attempts
540 for ($i = 0; $i < 10; ++$i) {
541 // Create a unique filename
542 $tmpFile = $dir.'/'.$prefix.uniqid(mt_rand(), true);
544 // Use fopen instead of file_exists as some streams do not support stat
545 // Use mode 'x+' to atomically check existence and create to avoid a TOCTOU vulnerability
546 $handle = @fopen($tmpFile, 'x+');
548 // If unsuccessful restart the loop
549 if (false === $handle) {
553 // Close the file if it was successfully opened
559 throw new IOException('A temporary file could not be created.');
563 * Atomically dumps content into a file.
565 * @param string $filename The file to be written to
566 * @param string $content The data to write into the file
567 * @param null|int $mode The file mode (octal). If null, file permissions are not modified
568 * Deprecated since version 2.3.12, to be removed in 3.0.
570 * @throws IOException If the file cannot be written to.
572 public function dumpFile($filename, $content, $mode = 0666)
574 $dir = dirname($filename);
580 if (!is_writable($dir)) {
581 throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir);
584 $tmpFile = $this->tempnam($dir, basename($filename));
586 if (false === @file_put_contents($tmpFile, $content)) {
587 throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
590 if (null !== $mode) {
591 if (func_num_args() > 2) {
592 @trigger_error('Support for modifying file permissions is deprecated since version 2.3.12 and will be removed in 3.0.', E_USER_DEPRECATED);
595 $this->chmod($tmpFile, $mode);
596 } elseif (file_exists($filename)) {
597 @chmod($tmpFile, fileperms($filename));
600 $this->rename($tmpFile, $filename, true);
604 * @param mixed $files
606 * @return \Traversable
608 private function toIterator($files)
610 if (!$files instanceof \Traversable) {
611 $files = new \ArrayObject(is_array($files) ? $files : array($files));
618 * Gets a 2-tuple of scheme (may be null) and hierarchical part of a filename (e.g. file:///tmp -> array(file, tmp)).
620 * @param string $filename The filename to be parsed
622 * @return array The filename scheme and hierarchical part
624 private function getSchemeAndHierarchy($filename)
626 $components = explode('://', $filename, 2);
628 return 2 === count($components) ? array($components[0], $components[1]) : array(null, $components[0]);