Filesystem.php 17 KB

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