Filesystem.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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. use Symfony\Component\Finder\Finder;
  15. /**
  16. * @author Jordi Boggiano <j.boggiano@seld.be>
  17. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  18. */
  19. class Filesystem
  20. {
  21. private $processExecutor;
  22. public function __construct(ProcessExecutor $executor = null)
  23. {
  24. $this->processExecutor = $executor ?: new ProcessExecutor();
  25. }
  26. public function remove($file)
  27. {
  28. if (is_dir($file)) {
  29. return $this->removeDirectory($file);
  30. }
  31. if (file_exists($file)) {
  32. return $this->unlink($file);
  33. }
  34. return false;
  35. }
  36. /**
  37. * Checks if a directory is empty
  38. *
  39. * @param string $dir
  40. * @return bool
  41. */
  42. public function isDirEmpty($dir)
  43. {
  44. $finder = Finder::create()
  45. ->ignoreVCS(false)
  46. ->ignoreDotFiles(false)
  47. ->depth(0)
  48. ->in($dir);
  49. return count($finder) === 0;
  50. }
  51. public function emptyDirectory($dir, $ensureDirectoryExists = true)
  52. {
  53. if (file_exists($dir) && is_link($dir)) {
  54. $this->unlink($dir);
  55. }
  56. if ($ensureDirectoryExists) {
  57. $this->ensureDirectoryExists($dir);
  58. }
  59. if (is_dir($dir)) {
  60. $finder = Finder::create()
  61. ->ignoreVCS(false)
  62. ->ignoreDotFiles(false)
  63. ->depth(0)
  64. ->in($dir);
  65. foreach ($finder as $path) {
  66. $this->remove((string) $path);
  67. }
  68. }
  69. }
  70. /**
  71. * Recursively remove a directory
  72. *
  73. * Uses the process component if proc_open is enabled on the PHP
  74. * installation.
  75. *
  76. * @param string $directory
  77. * @throws \RuntimeException
  78. * @return bool
  79. */
  80. public function removeDirectory($directory)
  81. {
  82. if ($this->isSymlinkedDirectory($directory)) {
  83. return $this->unlinkSymlinkedDirectory($directory);
  84. }
  85. if (!file_exists($directory) || !is_dir($directory)) {
  86. return true;
  87. }
  88. if (preg_match('{^(?:[a-z]:)?[/\\\\]+$}i', $directory)) {
  89. throw new \RuntimeException('Aborting an attempted deletion of '.$directory.', this was probably not intended, if it is a real use case please report it.');
  90. }
  91. if (!function_exists('proc_open')) {
  92. return $this->removeDirectoryPhp($directory);
  93. }
  94. if (Platform::isWindows()) {
  95. $cmd = sprintf('rmdir /S /Q %s', ProcessExecutor::escape(realpath($directory)));
  96. } else {
  97. $cmd = sprintf('rm -rf %s', ProcessExecutor::escape($directory));
  98. }
  99. $result = $this->getProcess()->execute($cmd, $output) === 0;
  100. // clear stat cache because external processes aren't tracked by the php stat cache
  101. clearstatcache();
  102. if ($result && !file_exists($directory)) {
  103. return true;
  104. }
  105. return $this->removeDirectoryPhp($directory);
  106. }
  107. /**
  108. * Recursively delete directory using PHP iterators.
  109. *
  110. * Uses a CHILD_FIRST RecursiveIteratorIterator to sort files
  111. * before directories, creating a single non-recursive loop
  112. * to delete files/directories in the correct order.
  113. *
  114. * @param string $directory
  115. * @return bool
  116. */
  117. public function removeDirectoryPhp($directory)
  118. {
  119. $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
  120. $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
  121. foreach ($ri as $file) {
  122. if ($file->isDir()) {
  123. $this->rmdir($file->getPathname());
  124. } else {
  125. $this->unlink($file->getPathname());
  126. }
  127. }
  128. return $this->rmdir($directory);
  129. }
  130. public function ensureDirectoryExists($directory)
  131. {
  132. if (!is_dir($directory)) {
  133. if (file_exists($directory)) {
  134. throw new \RuntimeException(
  135. $directory.' exists and is not a directory.'
  136. );
  137. }
  138. if (!@mkdir($directory, 0777, true)) {
  139. throw new \RuntimeException(
  140. $directory.' does not exist and could not be created.'
  141. );
  142. }
  143. }
  144. }
  145. /**
  146. * Attempts to unlink a file and in case of failure retries after 350ms on windows
  147. *
  148. * @param string $path
  149. * @throws \RuntimeException
  150. * @return bool
  151. */
  152. public function unlink($path)
  153. {
  154. if (!@$this->unlinkImplementation($path)) {
  155. // retry after a bit on windows since it tends to be touchy with mass removals
  156. if (!Platform::isWindows() || (usleep(350000) && !@$this->unlinkImplementation($path))) {
  157. $error = error_get_last();
  158. $message = 'Could not delete '.$path.': ' . @$error['message'];
  159. if (Platform::isWindows()) {
  160. $message .= "\nThis can be due to an antivirus or the Windows Search Indexer locking the file while they are analyzed";
  161. }
  162. throw new \RuntimeException($message);
  163. }
  164. }
  165. return true;
  166. }
  167. /**
  168. * Attempts to rmdir a file and in case of failure retries after 350ms on windows
  169. *
  170. * @param string $path
  171. * @throws \RuntimeException
  172. * @return bool
  173. */
  174. public function rmdir($path)
  175. {
  176. if (!@rmdir($path)) {
  177. // retry after a bit on windows since it tends to be touchy with mass removals
  178. if (!Platform::isWindows() || (usleep(350000) && !@rmdir($path))) {
  179. $error = error_get_last();
  180. $message = 'Could not delete '.$path.': ' . @$error['message'];
  181. if (Platform::isWindows()) {
  182. $message .= "\nThis can be due to an antivirus or the Windows Search Indexer locking the file while they are analyzed";
  183. }
  184. throw new \RuntimeException($message);
  185. }
  186. }
  187. return true;
  188. }
  189. /**
  190. * Copy then delete is a non-atomic version of {@link rename}.
  191. *
  192. * Some systems can't rename and also don't have proc_open,
  193. * which requires this solution.
  194. *
  195. * @param string $source
  196. * @param string $target
  197. */
  198. public function copyThenRemove($source, $target)
  199. {
  200. if (!is_dir($source)) {
  201. copy($source, $target);
  202. $this->unlink($source);
  203. return;
  204. }
  205. $it = new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS);
  206. $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::SELF_FIRST);
  207. $this->ensureDirectoryExists($target);
  208. foreach ($ri as $file) {
  209. $targetPath = $target . DIRECTORY_SEPARATOR . $ri->getSubPathName();
  210. if ($file->isDir()) {
  211. $this->ensureDirectoryExists($targetPath);
  212. } else {
  213. copy($file->getPathname(), $targetPath);
  214. }
  215. }
  216. $this->removeDirectoryPhp($source);
  217. }
  218. public function rename($source, $target)
  219. {
  220. if (true === @rename($source, $target)) {
  221. return;
  222. }
  223. if (!function_exists('proc_open')) {
  224. return $this->copyThenRemove($source, $target);
  225. }
  226. if (Platform::isWindows()) {
  227. // Try to copy & delete - this is a workaround for random "Access denied" errors.
  228. $command = sprintf('xcopy %s %s /E /I /Q /Y', ProcessExecutor::escape($source), ProcessExecutor::escape($target));
  229. $result = $this->processExecutor->execute($command, $output);
  230. // clear stat cache because external processes aren't tracked by the php stat cache
  231. clearstatcache();
  232. if (0 === $result) {
  233. $this->remove($source);
  234. return;
  235. }
  236. } else {
  237. // We do not use PHP's "rename" function here since it does not support
  238. // the case where $source, and $target are located on different partitions.
  239. $command = sprintf('mv %s %s', ProcessExecutor::escape($source), ProcessExecutor::escape($target));
  240. $result = $this->processExecutor->execute($command, $output);
  241. // clear stat cache because external processes aren't tracked by the php stat cache
  242. clearstatcache();
  243. if (0 === $result) {
  244. return;
  245. }
  246. }
  247. return $this->copyThenRemove($source, $target);
  248. }
  249. /**
  250. * Returns the shortest path from $from to $to
  251. *
  252. * @param string $from
  253. * @param string $to
  254. * @param bool $directories if true, the source/target are considered to be directories
  255. * @throws \InvalidArgumentException
  256. * @return string
  257. */
  258. public function findShortestPath($from, $to, $directories = false)
  259. {
  260. if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) {
  261. throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to));
  262. }
  263. $from = lcfirst($this->normalizePath($from));
  264. $to = lcfirst($this->normalizePath($to));
  265. if ($directories) {
  266. $from = rtrim($from, '/') . '/dummy_file';
  267. }
  268. if (dirname($from) === dirname($to)) {
  269. return './'.basename($to);
  270. }
  271. $commonPath = $to;
  272. while (strpos($from.'/', $commonPath.'/') !== 0 && '/' !== $commonPath && !preg_match('{^[a-z]:/?$}i', $commonPath)) {
  273. $commonPath = strtr(dirname($commonPath), '\\', '/');
  274. }
  275. if (0 !== strpos($from, $commonPath) || '/' === $commonPath) {
  276. return $to;
  277. }
  278. $commonPath = rtrim($commonPath, '/') . '/';
  279. $sourcePathDepth = substr_count(substr($from, strlen($commonPath)), '/');
  280. $commonPathCode = str_repeat('../', $sourcePathDepth);
  281. return ($commonPathCode . substr($to, strlen($commonPath))) ?: './';
  282. }
  283. /**
  284. * Returns PHP code that, when executed in $from, will return the path to $to
  285. *
  286. * @param string $from
  287. * @param string $to
  288. * @param bool $directories if true, the source/target are considered to be directories
  289. * @throws \InvalidArgumentException
  290. * @return string
  291. */
  292. public function findShortestPathCode($from, $to, $directories = false)
  293. {
  294. if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) {
  295. throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to));
  296. }
  297. $from = lcfirst($this->normalizePath($from));
  298. $to = lcfirst($this->normalizePath($to));
  299. if ($from === $to) {
  300. return $directories ? '__DIR__' : '__FILE__';
  301. }
  302. $commonPath = $to;
  303. while (strpos($from.'/', $commonPath.'/') !== 0 && '/' !== $commonPath && !preg_match('{^[a-z]:/?$}i', $commonPath) && '.' !== $commonPath) {
  304. $commonPath = strtr(dirname($commonPath), '\\', '/');
  305. }
  306. if (0 !== strpos($from, $commonPath) || '/' === $commonPath || '.' === $commonPath) {
  307. return var_export($to, true);
  308. }
  309. $commonPath = rtrim($commonPath, '/') . '/';
  310. if (strpos($to, $from.'/') === 0) {
  311. return '__DIR__ . '.var_export(substr($to, strlen($from)), true);
  312. }
  313. $sourcePathDepth = substr_count(substr($from, strlen($commonPath)), '/') + $directories;
  314. $commonPathCode = str_repeat('dirname(', $sourcePathDepth).'__DIR__'.str_repeat(')', $sourcePathDepth);
  315. $relTarget = substr($to, strlen($commonPath));
  316. return $commonPathCode . (strlen($relTarget) ? '.' . var_export('/' . $relTarget, true) : '');
  317. }
  318. /**
  319. * Checks if the given path is absolute
  320. *
  321. * @param string $path
  322. * @return bool
  323. */
  324. public function isAbsolutePath($path)
  325. {
  326. return substr($path, 0, 1) === '/' || substr($path, 1, 1) === ':';
  327. }
  328. /**
  329. * Returns size of a file or directory specified by path. If a directory is
  330. * given, it's size will be computed recursively.
  331. *
  332. * @param string $path Path to the file or directory
  333. * @throws \RuntimeException
  334. * @return int
  335. */
  336. public function size($path)
  337. {
  338. if (!file_exists($path)) {
  339. throw new \RuntimeException("$path does not exist.");
  340. }
  341. if (is_dir($path)) {
  342. return $this->directorySize($path);
  343. }
  344. return filesize($path);
  345. }
  346. /**
  347. * Normalize a path. This replaces backslashes with slashes, removes ending
  348. * slash and collapses redundant separators and up-level references.
  349. *
  350. * @param string $path Path to the file or directory
  351. * @return string
  352. */
  353. public function normalizePath($path)
  354. {
  355. $parts = array();
  356. $path = strtr($path, '\\', '/');
  357. $prefix = '';
  358. $absolute = false;
  359. if (preg_match('{^([0-9a-z]+:(?://(?:[a-z]:)?)?)}i', $path, $match)) {
  360. $prefix = $match[1];
  361. $path = substr($path, strlen($prefix));
  362. }
  363. if (substr($path, 0, 1) === '/') {
  364. $absolute = true;
  365. $path = substr($path, 1);
  366. }
  367. $up = false;
  368. foreach (explode('/', $path) as $chunk) {
  369. if ('..' === $chunk && ($absolute || $up)) {
  370. array_pop($parts);
  371. $up = !(empty($parts) || '..' === end($parts));
  372. } elseif ('.' !== $chunk && '' !== $chunk) {
  373. $parts[] = $chunk;
  374. $up = '..' !== $chunk;
  375. }
  376. }
  377. return $prefix.($absolute ? '/' : '').implode('/', $parts);
  378. }
  379. /**
  380. * Return if the given path is local
  381. *
  382. * @param string $path
  383. * @return bool
  384. */
  385. public static function isLocalPath($path)
  386. {
  387. return (bool) preg_match('{^(file://|/|[a-z]:[\\\\/]|\.\.[\\\\/]|[a-z0-9_.-]+[\\\\/])}i', $path);
  388. }
  389. public static function getPlatformPath($path)
  390. {
  391. if (Platform::isWindows()) {
  392. $path = preg_replace('{^(?:file:///([a-z])/)}i', 'file://$1:/', $path);
  393. }
  394. return preg_replace('{^file://}i', '', $path);
  395. }
  396. protected function directorySize($directory)
  397. {
  398. $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
  399. $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
  400. $size = 0;
  401. foreach ($ri as $file) {
  402. if ($file->isFile()) {
  403. $size += $file->getSize();
  404. }
  405. }
  406. return $size;
  407. }
  408. protected function getProcess()
  409. {
  410. return new ProcessExecutor;
  411. }
  412. /**
  413. * delete symbolic link implementation (commonly known as "unlink()")
  414. *
  415. * symbolic links on windows which link to directories need rmdir instead of unlink
  416. *
  417. * @param string $path
  418. *
  419. * @return bool
  420. */
  421. private function unlinkImplementation($path)
  422. {
  423. if (Platform::isWindows() && is_dir($path) && is_link($path)) {
  424. return rmdir($path);
  425. }
  426. return unlink($path);
  427. }
  428. /**
  429. * Creates a relative symlink from $link to $target
  430. *
  431. * @param string $target The path of the binary file to be symlinked
  432. * @param string $link The path where the symlink should be created
  433. * @return bool
  434. */
  435. public function relativeSymlink($target, $link)
  436. {
  437. $cwd = getcwd();
  438. $relativePath = $this->findShortestPath($link, $target);
  439. chdir(dirname($link));
  440. $result = @symlink($relativePath, $link);
  441. chdir($cwd);
  442. return (bool) $result;
  443. }
  444. /**
  445. * return true if that directory is a symlink.
  446. *
  447. * @param string $directory
  448. *
  449. * @return bool
  450. */
  451. public function isSymlinkedDirectory($directory)
  452. {
  453. if (!is_dir($directory)) {
  454. return false;
  455. }
  456. $resolved = $this->resolveSymlinkedDirectorySymlink($directory);
  457. return is_link($resolved);
  458. }
  459. /**
  460. * @param string $directory
  461. *
  462. * @return bool
  463. */
  464. private function unlinkSymlinkedDirectory($directory)
  465. {
  466. $resolved = $this->resolveSymlinkedDirectorySymlink($directory);
  467. return $this->unlink($resolved);
  468. }
  469. /**
  470. * resolve pathname to symbolic link of a directory
  471. *
  472. * @param string $pathname directory path to resolve
  473. *
  474. * @return string resolved path to symbolic link or original pathname (unresolved)
  475. */
  476. private function resolveSymlinkedDirectorySymlink($pathname)
  477. {
  478. if (!is_dir($pathname)) {
  479. return $pathname;
  480. }
  481. $resolved = rtrim($pathname, '/');
  482. if (!strlen($resolved)) {
  483. return $pathname;
  484. }
  485. return $resolved;
  486. }
  487. }