Filesystem.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Util;
  12. use RecursiveDirectoryIterator;
  13. use RecursiveIteratorIterator;
  14. /**
  15. * @author Jordi Boggiano <j.boggiano@seld.be>
  16. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  17. */
  18. class Filesystem
  19. {
  20. private $processExecutor;
  21. public function __construct(ProcessExecutor $executor = null)
  22. {
  23. $this->processExecutor = $executor ?: new ProcessExecutor();
  24. }
  25. public function remove($file)
  26. {
  27. if (is_dir($file)) {
  28. return $this->removeDirectory($file);
  29. }
  30. if (file_exists($file)) {
  31. return unlink($file);
  32. }
  33. return false;
  34. }
  35. /**
  36. * Checks if a directory is empty
  37. *
  38. * @param string $dir
  39. * @return bool
  40. */
  41. public function isDirEmpty($dir)
  42. {
  43. $dir = rtrim($dir, '/\\');
  44. return count(glob($dir.'/*') ?: array()) === 0 && count(glob($dir.'/.*') ?: array()) === 2;
  45. }
  46. /**
  47. * Recursively remove a directory
  48. *
  49. * Uses the process component if proc_open is enabled on the PHP
  50. * installation.
  51. *
  52. * @param string $directory
  53. * @return bool
  54. */
  55. public function removeDirectory($directory)
  56. {
  57. if (!is_dir($directory)) {
  58. return true;
  59. }
  60. if (preg_match('{^(?:[a-z]:)?[/\\\\]+$}i', $directory)) {
  61. throw new \RuntimeException('Aborting an attempted deletion of '.$directory.', this was probably not intended, if it is a real use case please report it.');
  62. }
  63. if (!function_exists('proc_open')) {
  64. return $this->removeDirectoryPhp($directory);
  65. }
  66. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  67. $cmd = sprintf('rmdir /S /Q %s', escapeshellarg(realpath($directory)));
  68. } else {
  69. $cmd = sprintf('rm -rf %s', escapeshellarg($directory));
  70. }
  71. $result = $this->getProcess()->execute($cmd, $output) === 0;
  72. // clear stat cache because external processes aren't tracked by the php stat cache
  73. clearstatcache();
  74. return $result && !is_dir($directory);
  75. }
  76. /**
  77. * Recursively delete directory using PHP iterators.
  78. *
  79. * Uses a CHILD_FIRST RecursiveIteratorIterator to sort files
  80. * before directories, creating a single non-recursive loop
  81. * to delete files/directories in the correct order.
  82. *
  83. * @param string $directory
  84. * @return bool
  85. */
  86. public function removeDirectoryPhp($directory)
  87. {
  88. $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
  89. $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
  90. foreach ($ri as $file) {
  91. if ($file->isDir()) {
  92. rmdir($file->getPathname());
  93. } else {
  94. unlink($file->getPathname());
  95. }
  96. }
  97. return rmdir($directory);
  98. }
  99. public function ensureDirectoryExists($directory)
  100. {
  101. if (!is_dir($directory)) {
  102. if (file_exists($directory)) {
  103. throw new \RuntimeException(
  104. $directory.' exists and is not a directory.'
  105. );
  106. }
  107. if (!@mkdir($directory, 0777, true)) {
  108. throw new \RuntimeException(
  109. $directory.' does not exist and could not be created.'
  110. );
  111. }
  112. }
  113. }
  114. /**
  115. * Copy then delete is a non-atomic version of {@link rename}.
  116. *
  117. * Some systems can't rename and also don't have proc_open,
  118. * which requires this solution.
  119. *
  120. * @param string $source
  121. * @param string $target
  122. */
  123. public function copyThenRemove($source, $target)
  124. {
  125. $it = new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS);
  126. $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::SELF_FIRST);
  127. $this->ensureDirectoryExists($target);
  128. foreach ($ri as $file) {
  129. $targetPath = $target . DIRECTORY_SEPARATOR . $ri->getSubPathName();
  130. if ($file->isDir()) {
  131. $this->ensureDirectoryExists($targetPath);
  132. } else {
  133. copy($file->getPathname(), $targetPath);
  134. }
  135. }
  136. $this->removeDirectoryPhp($source);
  137. }
  138. public function rename($source, $target)
  139. {
  140. if (true === @rename($source, $target)) {
  141. return;
  142. }
  143. if (!function_exists('proc_open')) {
  144. return $this->copyThenRemove($source, $target);
  145. }
  146. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  147. // Try to copy & delete - this is a workaround for random "Access denied" errors.
  148. $command = sprintf('xcopy %s %s /E /I /Q', escapeshellarg($source), escapeshellarg($target));
  149. $result = $this->processExecutor->execute($command, $output);
  150. // clear stat cache because external processes aren't tracked by the php stat cache
  151. clearstatcache();
  152. if (0 === $result) {
  153. $this->remove($source);
  154. return;
  155. }
  156. } else {
  157. // We do not use PHP's "rename" function here since it does not support
  158. // the case where $source, and $target are located on different partitions.
  159. $command = sprintf('mv %s %s', escapeshellarg($source), escapeshellarg($target));
  160. $result = $this->processExecutor->execute($command, $output);
  161. // clear stat cache because external processes aren't tracked by the php stat cache
  162. clearstatcache();
  163. if (0 === $result) {
  164. return;
  165. }
  166. }
  167. return $this->copyThenRemove($source, $target);
  168. }
  169. /**
  170. * Returns the shortest path from $from to $to
  171. *
  172. * @param string $from
  173. * @param string $to
  174. * @param bool $directories if true, the source/target are considered to be directories
  175. * @throws \InvalidArgumentException
  176. * @return string
  177. */
  178. public function findShortestPath($from, $to, $directories = false)
  179. {
  180. if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) {
  181. throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to));
  182. }
  183. $from = lcfirst($this->normalizePath($from));
  184. $to = lcfirst($this->normalizePath($to));
  185. if ($directories) {
  186. $from .= '/dummy_file';
  187. }
  188. if (dirname($from) === dirname($to)) {
  189. return './'.basename($to);
  190. }
  191. $commonPath = $to;
  192. while (strpos($from.'/', $commonPath.'/') !== 0 && '/' !== $commonPath && !preg_match('{^[a-z]:/?$}i', $commonPath)) {
  193. $commonPath = strtr(dirname($commonPath), '\\', '/');
  194. }
  195. if (0 !== strpos($from, $commonPath) || '/' === $commonPath) {
  196. return $to;
  197. }
  198. $commonPath = rtrim($commonPath, '/') . '/';
  199. $sourcePathDepth = substr_count(substr($from, strlen($commonPath)), '/');
  200. $commonPathCode = str_repeat('../', $sourcePathDepth);
  201. return ($commonPathCode . substr($to, strlen($commonPath))) ?: './';
  202. }
  203. /**
  204. * Returns PHP code that, when executed in $from, will return the path to $to
  205. *
  206. * @param string $from
  207. * @param string $to
  208. * @param bool $directories if true, the source/target are considered to be directories
  209. * @throws \InvalidArgumentException
  210. * @return string
  211. */
  212. public function findShortestPathCode($from, $to, $directories = false)
  213. {
  214. if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) {
  215. throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to));
  216. }
  217. $from = lcfirst($this->normalizePath($from));
  218. $to = lcfirst($this->normalizePath($to));
  219. if ($from === $to) {
  220. return $directories ? '__DIR__' : '__FILE__';
  221. }
  222. $commonPath = $to;
  223. while (strpos($from.'/', $commonPath.'/') !== 0 && '/' !== $commonPath && !preg_match('{^[a-z]:/?$}i', $commonPath) && '.' !== $commonPath) {
  224. $commonPath = strtr(dirname($commonPath), '\\', '/');
  225. }
  226. if (0 !== strpos($from, $commonPath) || '/' === $commonPath || '.' === $commonPath) {
  227. return var_export($to, true);
  228. }
  229. $commonPath = rtrim($commonPath, '/') . '/';
  230. if (strpos($to, $from.'/') === 0) {
  231. return '__DIR__ . '.var_export(substr($to, strlen($from)), true);
  232. }
  233. $sourcePathDepth = substr_count(substr($from, strlen($commonPath)), '/') + $directories;
  234. $commonPathCode = str_repeat('dirname(', $sourcePathDepth).'__DIR__'.str_repeat(')', $sourcePathDepth);
  235. $relTarget = substr($to, strlen($commonPath));
  236. return $commonPathCode . (strlen($relTarget) ? '.' . var_export('/' . $relTarget, true) : '');
  237. }
  238. /**
  239. * Checks if the given path is absolute
  240. *
  241. * @param string $path
  242. * @return bool
  243. */
  244. public function isAbsolutePath($path)
  245. {
  246. return substr($path, 0, 1) === '/' || substr($path, 1, 1) === ':';
  247. }
  248. /**
  249. * Returns size of a file or directory specified by path. If a directory is
  250. * given, it's size will be computed recursively.
  251. *
  252. * @param string $path Path to the file or directory
  253. * @throws \RuntimeException
  254. * @return int
  255. */
  256. public function size($path)
  257. {
  258. if (!file_exists($path)) {
  259. throw new \RuntimeException("$path does not exist.");
  260. }
  261. if (is_dir($path)) {
  262. return $this->directorySize($path);
  263. }
  264. return filesize($path);
  265. }
  266. /**
  267. * Normalize a path. This replaces backslashes with slashes, removes ending
  268. * slash and collapses redundant separators and up-level references.
  269. *
  270. * @param string $path Path to the file or directory
  271. * @return string
  272. */
  273. public function normalizePath($path)
  274. {
  275. $parts = array();
  276. $path = strtr($path, '\\', '/');
  277. $prefix = '';
  278. $absolute = false;
  279. if (preg_match('{^([0-9a-z]+:(?://(?:[a-z]:)?)?)}i', $path, $match)) {
  280. $prefix = $match[1];
  281. $path = substr($path, strlen($prefix));
  282. }
  283. if (substr($path, 0, 1) === '/') {
  284. $absolute = true;
  285. $path = substr($path, 1);
  286. }
  287. $up = false;
  288. foreach (explode('/', $path) as $chunk) {
  289. if ('..' === $chunk && ($absolute || $up)) {
  290. array_pop($parts);
  291. $up = !(empty($parts) || '..' === end($parts));
  292. } elseif ('.' !== $chunk && '' !== $chunk) {
  293. $parts[] = $chunk;
  294. $up = '..' !== $chunk;
  295. }
  296. }
  297. return $prefix.($absolute ? '/' : '').implode('/', $parts);
  298. }
  299. protected function directorySize($directory)
  300. {
  301. $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
  302. $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
  303. $size = 0;
  304. foreach ($ri as $file) {
  305. if ($file->isFile()) {
  306. $size += $file->getSize();
  307. }
  308. }
  309. return $size;
  310. }
  311. protected function getProcess()
  312. {
  313. return new ProcessExecutor;
  314. }
  315. }