Folder.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 0.2.9
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Filesystem;
  16. use DirectoryIterator;
  17. use Exception;
  18. use InvalidArgumentException;
  19. use RecursiveDirectoryIterator;
  20. use RecursiveIteratorIterator;
  21. /**
  22. * Folder structure browser, lists folders and files.
  23. * Provides an Object interface for Common directory related tasks.
  24. *
  25. * @link https://book.cakephp.org/3.0/en/core-libraries/file-folder.html#folder-api
  26. */
  27. class Folder
  28. {
  29. /**
  30. * Default scheme for Folder::copy
  31. * Recursively merges subfolders with the same name
  32. *
  33. * @var string
  34. */
  35. const MERGE = 'merge';
  36. /**
  37. * Overwrite scheme for Folder::copy
  38. * subfolders with the same name will be replaced
  39. *
  40. * @var string
  41. */
  42. const OVERWRITE = 'overwrite';
  43. /**
  44. * Skip scheme for Folder::copy
  45. * if a subfolder with the same name exists it will be skipped
  46. *
  47. * @var string
  48. */
  49. const SKIP = 'skip';
  50. /**
  51. * Sort mode by name
  52. *
  53. * @var string
  54. */
  55. const SORT_NAME = 'name';
  56. /**
  57. * Sort mode by time
  58. *
  59. * @var string
  60. */
  61. const SORT_TIME = 'time';
  62. /**
  63. * Path to Folder.
  64. *
  65. * @var string
  66. */
  67. public $path;
  68. /**
  69. * Sortedness. Whether or not list results
  70. * should be sorted by name.
  71. *
  72. * @var bool
  73. */
  74. public $sort = false;
  75. /**
  76. * Mode to be used on create. Does nothing on windows platforms.
  77. *
  78. * @var int
  79. * https://book.cakephp.org/3.0/en/core-libraries/file-folder.html#Cake\Filesystem\Folder::$mode
  80. */
  81. public $mode = 0755;
  82. /**
  83. * Functions array to be called depending on the sort type chosen.
  84. */
  85. protected $_fsorts = [
  86. self::SORT_NAME => 'getPathname',
  87. self::SORT_TIME => 'getCTime'
  88. ];
  89. /**
  90. * Holds messages from last method.
  91. *
  92. * @var array
  93. */
  94. protected $_messages = [];
  95. /**
  96. * Holds errors from last method.
  97. *
  98. * @var array
  99. */
  100. protected $_errors = [];
  101. /**
  102. * Holds array of complete directory paths.
  103. *
  104. * @var array
  105. */
  106. protected $_directories;
  107. /**
  108. * Holds array of complete file paths.
  109. *
  110. * @var array
  111. */
  112. protected $_files;
  113. /**
  114. * Constructor.
  115. *
  116. * @param string|null $path Path to folder
  117. * @param bool $create Create folder if not found
  118. * @param int|false $mode Mode (CHMOD) to apply to created folder, false to ignore
  119. */
  120. public function __construct($path = null, $create = false, $mode = false)
  121. {
  122. if (empty($path)) {
  123. $path = TMP;
  124. }
  125. if ($mode) {
  126. $this->mode = $mode;
  127. }
  128. if (!file_exists($path) && $create === true) {
  129. $this->create($path, $this->mode);
  130. }
  131. if (!Folder::isAbsolute($path)) {
  132. $path = realpath($path);
  133. }
  134. if (!empty($path)) {
  135. $this->cd($path);
  136. }
  137. }
  138. /**
  139. * Return current path.
  140. *
  141. * @return string Current path
  142. */
  143. public function pwd()
  144. {
  145. return $this->path;
  146. }
  147. /**
  148. * Change directory to $path.
  149. *
  150. * @param string $path Path to the directory to change to
  151. * @return string|bool The new path. Returns false on failure
  152. */
  153. public function cd($path)
  154. {
  155. $path = $this->realpath($path);
  156. if (is_dir($path)) {
  157. return $this->path = $path;
  158. }
  159. return false;
  160. }
  161. /**
  162. * Returns an array of the contents of the current directory.
  163. * The returned array holds two arrays: One of directories and one of files.
  164. *
  165. * @param string|bool $sort Whether you want the results sorted, set this and the sort property
  166. * to false to get unsorted results.
  167. * @param array|bool $exceptions Either an array or boolean true will not grab dot files
  168. * @param bool $fullPath True returns the full path
  169. * @return array Contents of current directory as an array, an empty array on failure
  170. */
  171. public function read($sort = self::SORT_NAME, $exceptions = false, $fullPath = false)
  172. {
  173. $dirs = $files = [];
  174. if (!$this->pwd()) {
  175. return [$dirs, $files];
  176. }
  177. if (is_array($exceptions)) {
  178. $exceptions = array_flip($exceptions);
  179. }
  180. $skipHidden = isset($exceptions['.']) || $exceptions === true;
  181. try {
  182. $iterator = new DirectoryIterator($this->path);
  183. } catch (Exception $e) {
  184. return [$dirs, $files];
  185. }
  186. if (!is_bool($sort) && isset($this->_fsorts[$sort])) {
  187. $methodName = $this->_fsorts[$sort];
  188. } else {
  189. $methodName = $this->_fsorts[self::SORT_NAME];
  190. }
  191. foreach ($iterator as $item) {
  192. if ($item->isDot()) {
  193. continue;
  194. }
  195. $name = $item->getFilename();
  196. if ($skipHidden && $name[0] === '.' || isset($exceptions[$name])) {
  197. continue;
  198. }
  199. if ($fullPath) {
  200. $name = $item->getPathname();
  201. }
  202. if ($item->isDir()) {
  203. $dirs[$item->{$methodName}()][] = $name;
  204. } else {
  205. $files[$item->{$methodName}()][] = $name;
  206. }
  207. }
  208. if ($sort || $this->sort) {
  209. ksort($dirs);
  210. ksort($files);
  211. }
  212. if ($dirs) {
  213. $dirs = array_merge(...array_values($dirs));
  214. }
  215. if ($files) {
  216. $files = array_merge(...array_values($files));
  217. }
  218. return [$dirs, $files];
  219. }
  220. /**
  221. * Returns an array of all matching files in current directory.
  222. *
  223. * @param string $regexpPattern Preg_match pattern (Defaults to: .*)
  224. * @param bool $sort Whether results should be sorted.
  225. * @return array Files that match given pattern
  226. */
  227. public function find($regexpPattern = '.*', $sort = false)
  228. {
  229. list(, $files) = $this->read($sort);
  230. return array_values(preg_grep('/^' . $regexpPattern . '$/i', $files));
  231. }
  232. /**
  233. * Returns an array of all matching files in and below current directory.
  234. *
  235. * @param string $pattern Preg_match pattern (Defaults to: .*)
  236. * @param bool $sort Whether results should be sorted.
  237. * @return array Files matching $pattern
  238. */
  239. public function findRecursive($pattern = '.*', $sort = false)
  240. {
  241. if (!$this->pwd()) {
  242. return [];
  243. }
  244. $startsOn = $this->path;
  245. $out = $this->_findRecursive($pattern, $sort);
  246. $this->cd($startsOn);
  247. return $out;
  248. }
  249. /**
  250. * Private helper function for findRecursive.
  251. *
  252. * @param string $pattern Pattern to match against
  253. * @param bool $sort Whether results should be sorted.
  254. * @return array Files matching pattern
  255. */
  256. protected function _findRecursive($pattern, $sort = false)
  257. {
  258. list($dirs, $files) = $this->read($sort);
  259. $found = [];
  260. foreach ($files as $file) {
  261. if (preg_match('/^' . $pattern . '$/i', $file)) {
  262. $found[] = Folder::addPathElement($this->path, $file);
  263. }
  264. }
  265. $start = $this->path;
  266. foreach ($dirs as $dir) {
  267. $this->cd(Folder::addPathElement($start, $dir));
  268. $found = array_merge($found, $this->findRecursive($pattern, $sort));
  269. }
  270. return $found;
  271. }
  272. /**
  273. * Returns true if given $path is a Windows path.
  274. *
  275. * @param string $path Path to check
  276. * @return bool true if windows path, false otherwise
  277. */
  278. public static function isWindowsPath($path)
  279. {
  280. return (preg_match('/^[A-Z]:\\\\/i', $path) || substr($path, 0, 2) === '\\\\');
  281. }
  282. /**
  283. * Returns true if given $path is an absolute path.
  284. *
  285. * @param string $path Path to check
  286. * @return bool true if path is absolute.
  287. */
  288. public static function isAbsolute($path)
  289. {
  290. if (empty($path)) {
  291. return false;
  292. }
  293. return $path[0] === '/' ||
  294. preg_match('/^[A-Z]:\\\\/i', $path) ||
  295. substr($path, 0, 2) === '\\\\' ||
  296. self::isRegisteredStreamWrapper($path);
  297. }
  298. /**
  299. * Returns true if given $path is a registered stream wrapper.
  300. *
  301. * @param string $path Path to check
  302. * @return bool True if path is registered stream wrapper.
  303. */
  304. public static function isRegisteredStreamWrapper($path)
  305. {
  306. return preg_match('/^[^:\/\/]+?(?=:\/\/)/i', $path, $matches) &&
  307. in_array($matches[0], stream_get_wrappers());
  308. }
  309. /**
  310. * Returns a correct set of slashes for given $path. (\\ for Windows paths and / for other paths.)
  311. *
  312. * @param string $path Path to check
  313. * @return string Set of slashes ("\\" or "/")
  314. */
  315. public static function normalizePath($path)
  316. {
  317. return Folder::correctSlashFor($path);
  318. }
  319. /**
  320. * Returns a correct set of slashes for given $path. (\\ for Windows paths and / for other paths.)
  321. *
  322. * @param string $path Path to check
  323. * @return string Set of slashes ("\\" or "/")
  324. */
  325. public static function correctSlashFor($path)
  326. {
  327. return Folder::isWindowsPath($path) ? '\\' : '/';
  328. }
  329. /**
  330. * Returns $path with added terminating slash (corrected for Windows or other OS).
  331. *
  332. * @param string $path Path to check
  333. * @return string Path with ending slash
  334. */
  335. public static function slashTerm($path)
  336. {
  337. if (Folder::isSlashTerm($path)) {
  338. return $path;
  339. }
  340. return $path . Folder::correctSlashFor($path);
  341. }
  342. /**
  343. * Returns $path with $element added, with correct slash in-between.
  344. *
  345. * @param string $path Path
  346. * @param string|array $element Element to add at end of path
  347. * @return string Combined path
  348. */
  349. public static function addPathElement($path, $element)
  350. {
  351. $element = (array)$element;
  352. array_unshift($element, rtrim($path, DIRECTORY_SEPARATOR));
  353. return implode(DIRECTORY_SEPARATOR, $element);
  354. }
  355. /**
  356. * Returns true if the Folder is in the given Cake path.
  357. *
  358. * @param string $path The path to check.
  359. * @return bool
  360. * @deprecated 3.2.12 This method will be removed in 4.0.0. Use inPath() instead.
  361. */
  362. public function inCakePath($path = '')
  363. {
  364. deprecationWarning('Folder::inCakePath() is deprecated. Use Folder::inPath() instead.');
  365. $dir = substr(Folder::slashTerm(ROOT), 0, -1);
  366. $newdir = $dir . $path;
  367. return $this->inPath($newdir);
  368. }
  369. /**
  370. * Returns true if the Folder is in the given path.
  371. *
  372. * @param string $path The absolute path to check that the current `pwd()` resides within.
  373. * @param bool $reverse Reverse the search, check if the given `$path` resides within the current `pwd()`.
  374. * @return bool
  375. * @throws \InvalidArgumentException When the given `$path` argument is not an absolute path.
  376. */
  377. public function inPath($path, $reverse = false)
  378. {
  379. if (!Folder::isAbsolute($path)) {
  380. throw new InvalidArgumentException('The $path argument is expected to be an absolute path.');
  381. }
  382. $dir = Folder::slashTerm($path);
  383. $current = Folder::slashTerm($this->pwd());
  384. if (!$reverse) {
  385. $return = preg_match('/^' . preg_quote($dir, '/') . '(.*)/', $current);
  386. } else {
  387. $return = preg_match('/^' . preg_quote($current, '/') . '(.*)/', $dir);
  388. }
  389. return (bool)$return;
  390. }
  391. /**
  392. * Change the mode on a directory structure recursively. This includes changing the mode on files as well.
  393. *
  394. * @param string $path The path to chmod.
  395. * @param int|bool $mode Octal value, e.g. 0755.
  396. * @param bool $recursive Chmod recursively, set to false to only change the current directory.
  397. * @param array $exceptions Array of files, directories to skip.
  398. * @return bool Success.
  399. */
  400. public function chmod($path, $mode = false, $recursive = true, array $exceptions = [])
  401. {
  402. if (!$mode) {
  403. $mode = $this->mode;
  404. }
  405. if ($recursive === false && is_dir($path)) {
  406. //@codingStandardsIgnoreStart
  407. if (@chmod($path, intval($mode, 8))) {
  408. //@codingStandardsIgnoreEnd
  409. $this->_messages[] = sprintf('%s changed to %s', $path, $mode);
  410. return true;
  411. }
  412. $this->_errors[] = sprintf('%s NOT changed to %s', $path, $mode);
  413. return false;
  414. }
  415. if (is_dir($path)) {
  416. $paths = $this->tree($path);
  417. foreach ($paths as $type) {
  418. foreach ($type as $fullpath) {
  419. $check = explode(DIRECTORY_SEPARATOR, $fullpath);
  420. $count = count($check);
  421. if (in_array($check[$count - 1], $exceptions)) {
  422. continue;
  423. }
  424. //@codingStandardsIgnoreStart
  425. if (@chmod($fullpath, intval($mode, 8))) {
  426. //@codingStandardsIgnoreEnd
  427. $this->_messages[] = sprintf('%s changed to %s', $fullpath, $mode);
  428. } else {
  429. $this->_errors[] = sprintf('%s NOT changed to %s', $fullpath, $mode);
  430. }
  431. }
  432. }
  433. if (empty($this->_errors)) {
  434. return true;
  435. }
  436. }
  437. return false;
  438. }
  439. /**
  440. * Returns an array of subdirectories for the provided or current path.
  441. *
  442. * @param string|null $path The directory path to get subdirectories for.
  443. * @param bool $fullPath Whether to return the full path or only the directory name.
  444. * @return array Array of subdirectories for the provided or current path.
  445. */
  446. public function subdirectories($path = null, $fullPath = true)
  447. {
  448. if (!$path) {
  449. $path = $this->path;
  450. }
  451. $subdirectories = [];
  452. try {
  453. $iterator = new DirectoryIterator($path);
  454. } catch (Exception $e) {
  455. return [];
  456. }
  457. foreach ($iterator as $item) {
  458. if (!$item->isDir() || $item->isDot()) {
  459. continue;
  460. }
  461. $subdirectories[] = $fullPath ? $item->getRealPath() : $item->getFilename();
  462. }
  463. return $subdirectories;
  464. }
  465. /**
  466. * Returns an array of nested directories and files in each directory
  467. *
  468. * @param string|null $path the directory path to build the tree from
  469. * @param array|bool $exceptions Either an array of files/folder to exclude
  470. * or boolean true to not grab dot files/folders
  471. * @param string|null $type either 'file' or 'dir'. Null returns both files and directories
  472. * @return array Array of nested directories and files in each directory
  473. */
  474. public function tree($path = null, $exceptions = false, $type = null)
  475. {
  476. if (!$path) {
  477. $path = $this->path;
  478. }
  479. $files = [];
  480. $directories = [$path];
  481. if (is_array($exceptions)) {
  482. $exceptions = array_flip($exceptions);
  483. }
  484. $skipHidden = false;
  485. if ($exceptions === true) {
  486. $skipHidden = true;
  487. } elseif (isset($exceptions['.'])) {
  488. $skipHidden = true;
  489. unset($exceptions['.']);
  490. }
  491. try {
  492. $directory = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_PATHNAME | RecursiveDirectoryIterator::CURRENT_AS_SELF);
  493. $iterator = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
  494. } catch (Exception $e) {
  495. if ($type === null) {
  496. return [[], []];
  497. }
  498. return [];
  499. }
  500. foreach ($iterator as $itemPath => $fsIterator) {
  501. if ($skipHidden) {
  502. $subPathName = $fsIterator->getSubPathname();
  503. if ($subPathName{0} === '.' || strpos($subPathName, DIRECTORY_SEPARATOR . '.') !== false) {
  504. continue;
  505. }
  506. }
  507. $item = $fsIterator->current();
  508. if (!empty($exceptions) && isset($exceptions[$item->getFilename()])) {
  509. continue;
  510. }
  511. if ($item->isFile()) {
  512. $files[] = $itemPath;
  513. } elseif ($item->isDir() && !$item->isDot()) {
  514. $directories[] = $itemPath;
  515. }
  516. }
  517. if ($type === null) {
  518. return [$directories, $files];
  519. }
  520. if ($type === 'dir') {
  521. return $directories;
  522. }
  523. return $files;
  524. }
  525. /**
  526. * Create a directory structure recursively.
  527. *
  528. * Can be used to create deep path structures like `/foo/bar/baz/shoe/horn`
  529. *
  530. * @param string $pathname The directory structure to create. Either an absolute or relative
  531. * path. If the path is relative and exists in the process' cwd it will not be created.
  532. * Otherwise relative paths will be prefixed with the current pwd().
  533. * @param int|bool $mode octal value 0755
  534. * @return bool Returns TRUE on success, FALSE on failure
  535. */
  536. public function create($pathname, $mode = false)
  537. {
  538. if (is_dir($pathname) || empty($pathname)) {
  539. return true;
  540. }
  541. if (!self::isAbsolute($pathname)) {
  542. $pathname = self::addPathElement($this->pwd(), $pathname);
  543. }
  544. if (!$mode) {
  545. $mode = $this->mode;
  546. }
  547. if (is_file($pathname)) {
  548. $this->_errors[] = sprintf('%s is a file', $pathname);
  549. return false;
  550. }
  551. $pathname = rtrim($pathname, DIRECTORY_SEPARATOR);
  552. $nextPathname = substr($pathname, 0, strrpos($pathname, DIRECTORY_SEPARATOR));
  553. if ($this->create($nextPathname, $mode)) {
  554. if (!file_exists($pathname)) {
  555. $old = umask(0);
  556. if (mkdir($pathname, $mode, true)) {
  557. umask($old);
  558. $this->_messages[] = sprintf('%s created', $pathname);
  559. return true;
  560. }
  561. umask($old);
  562. $this->_errors[] = sprintf('%s NOT created', $pathname);
  563. return false;
  564. }
  565. }
  566. return false;
  567. }
  568. /**
  569. * Returns the size in bytes of this Folder and its contents.
  570. *
  571. * @return int size in bytes of current folder
  572. */
  573. public function dirsize()
  574. {
  575. $size = 0;
  576. $directory = Folder::slashTerm($this->path);
  577. $stack = [$directory];
  578. $count = count($stack);
  579. for ($i = 0, $j = $count; $i < $j; ++$i) {
  580. if (is_file($stack[$i])) {
  581. $size += filesize($stack[$i]);
  582. } elseif (is_dir($stack[$i])) {
  583. $dir = dir($stack[$i]);
  584. if ($dir) {
  585. while (($entry = $dir->read()) !== false) {
  586. if ($entry === '.' || $entry === '..') {
  587. continue;
  588. }
  589. $add = $stack[$i] . $entry;
  590. if (is_dir($stack[$i] . $entry)) {
  591. $add = Folder::slashTerm($add);
  592. }
  593. $stack[] = $add;
  594. }
  595. $dir->close();
  596. }
  597. }
  598. $j = count($stack);
  599. }
  600. return $size;
  601. }
  602. /**
  603. * Recursively Remove directories if the system allows.
  604. *
  605. * @param string|null $path Path of directory to delete
  606. * @return bool Success
  607. */
  608. public function delete($path = null)
  609. {
  610. if (!$path) {
  611. $path = $this->pwd();
  612. }
  613. if (!$path) {
  614. return false;
  615. }
  616. $path = Folder::slashTerm($path);
  617. if (is_dir($path)) {
  618. try {
  619. $directory = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::CURRENT_AS_SELF);
  620. $iterator = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::CHILD_FIRST);
  621. } catch (Exception $e) {
  622. return false;
  623. }
  624. foreach ($iterator as $item) {
  625. $filePath = $item->getPathname();
  626. if ($item->isFile() || $item->isLink()) {
  627. //@codingStandardsIgnoreStart
  628. if (@unlink($filePath)) {
  629. //@codingStandardsIgnoreEnd
  630. $this->_messages[] = sprintf('%s removed', $filePath);
  631. } else {
  632. $this->_errors[] = sprintf('%s NOT removed', $filePath);
  633. }
  634. } elseif ($item->isDir() && !$item->isDot()) {
  635. //@codingStandardsIgnoreStart
  636. if (@rmdir($filePath)) {
  637. //@codingStandardsIgnoreEnd
  638. $this->_messages[] = sprintf('%s removed', $filePath);
  639. } else {
  640. $this->_errors[] = sprintf('%s NOT removed', $filePath);
  641. return false;
  642. }
  643. }
  644. }
  645. $path = rtrim($path, DIRECTORY_SEPARATOR);
  646. //@codingStandardsIgnoreStart
  647. if (@rmdir($path)) {
  648. //@codingStandardsIgnoreEnd
  649. $this->_messages[] = sprintf('%s removed', $path);
  650. } else {
  651. $this->_errors[] = sprintf('%s NOT removed', $path);
  652. return false;
  653. }
  654. }
  655. return true;
  656. }
  657. /**
  658. * Recursive directory copy.
  659. *
  660. * ### Options
  661. *
  662. * - `to` The directory to copy to.
  663. * - `from` The directory to copy from, this will cause a cd() to occur, changing the results of pwd().
  664. * - `mode` The mode to copy the files/directories with as integer, e.g. 0775.
  665. * - `skip` Files/directories to skip.
  666. * - `scheme` Folder::MERGE, Folder::OVERWRITE, Folder::SKIP
  667. * - `recursive` Whether to copy recursively or not (default: true - recursive)
  668. *
  669. * @param array|string $options Either an array of options (see above) or a string of the destination directory.
  670. * @return bool Success.
  671. */
  672. public function copy($options)
  673. {
  674. if (!$this->pwd()) {
  675. return false;
  676. }
  677. $to = null;
  678. if (is_string($options)) {
  679. $to = $options;
  680. $options = [];
  681. }
  682. $options += [
  683. 'to' => $to,
  684. 'from' => $this->path,
  685. 'mode' => $this->mode,
  686. 'skip' => [],
  687. 'scheme' => Folder::MERGE,
  688. 'recursive' => true
  689. ];
  690. $fromDir = $options['from'];
  691. $toDir = $options['to'];
  692. $mode = $options['mode'];
  693. if (!$this->cd($fromDir)) {
  694. $this->_errors[] = sprintf('%s not found', $fromDir);
  695. return false;
  696. }
  697. if (!is_dir($toDir)) {
  698. $this->create($toDir, $mode);
  699. }
  700. if (!is_writable($toDir)) {
  701. $this->_errors[] = sprintf('%s not writable', $toDir);
  702. return false;
  703. }
  704. $exceptions = array_merge(['.', '..', '.svn'], $options['skip']);
  705. //@codingStandardsIgnoreStart
  706. if ($handle = @opendir($fromDir)) {
  707. //@codingStandardsIgnoreEnd
  708. while (($item = readdir($handle)) !== false) {
  709. $to = Folder::addPathElement($toDir, $item);
  710. if (($options['scheme'] != Folder::SKIP || !is_dir($to)) && !in_array($item, $exceptions)) {
  711. $from = Folder::addPathElement($fromDir, $item);
  712. if (is_file($from) && (!is_file($to) || $options['scheme'] != Folder::SKIP)) {
  713. if (copy($from, $to)) {
  714. chmod($to, intval($mode, 8));
  715. touch($to, filemtime($from));
  716. $this->_messages[] = sprintf('%s copied to %s', $from, $to);
  717. } else {
  718. $this->_errors[] = sprintf('%s NOT copied to %s', $from, $to);
  719. }
  720. }
  721. if (is_dir($from) && file_exists($to) && $options['scheme'] === Folder::OVERWRITE) {
  722. $this->delete($to);
  723. }
  724. if (is_dir($from) && $options['recursive'] === false) {
  725. continue;
  726. }
  727. if (is_dir($from) && !file_exists($to)) {
  728. $old = umask(0);
  729. if (mkdir($to, $mode, true)) {
  730. umask($old);
  731. $old = umask(0);
  732. chmod($to, $mode);
  733. umask($old);
  734. $this->_messages[] = sprintf('%s created', $to);
  735. $options = ['to' => $to, 'from' => $from] + $options;
  736. $this->copy($options);
  737. } else {
  738. $this->_errors[] = sprintf('%s not created', $to);
  739. }
  740. } elseif (is_dir($from) && $options['scheme'] === Folder::MERGE) {
  741. $options = ['to' => $to, 'from' => $from] + $options;
  742. $this->copy($options);
  743. }
  744. }
  745. }
  746. closedir($handle);
  747. } else {
  748. return false;
  749. }
  750. return empty($this->_errors);
  751. }
  752. /**
  753. * Recursive directory move.
  754. *
  755. * ### Options
  756. *
  757. * - `to` The directory to copy to.
  758. * - `from` The directory to copy from, this will cause a cd() to occur, changing the results of pwd().
  759. * - `chmod` The mode to copy the files/directories with.
  760. * - `skip` Files/directories to skip.
  761. * - `scheme` Folder::MERGE, Folder::OVERWRITE, Folder::SKIP
  762. * - `recursive` Whether to copy recursively or not (default: true - recursive)
  763. *
  764. * @param array|string $options (to, from, chmod, skip, scheme)
  765. * @return bool Success
  766. */
  767. public function move($options)
  768. {
  769. $to = null;
  770. if (is_string($options)) {
  771. $to = $options;
  772. $options = (array)$options;
  773. }
  774. $options += ['to' => $to, 'from' => $this->path, 'mode' => $this->mode, 'skip' => [], 'recursive' => true];
  775. if ($this->copy($options) && $this->delete($options['from'])) {
  776. return (bool)$this->cd($options['to']);
  777. }
  778. return false;
  779. }
  780. /**
  781. * get messages from latest method
  782. *
  783. * @param bool $reset Reset message stack after reading
  784. * @return array
  785. */
  786. public function messages($reset = true)
  787. {
  788. $messages = $this->_messages;
  789. if ($reset) {
  790. $this->_messages = [];
  791. }
  792. return $messages;
  793. }
  794. /**
  795. * get error from latest method
  796. *
  797. * @param bool $reset Reset error stack after reading
  798. * @return array
  799. */
  800. public function errors($reset = true)
  801. {
  802. $errors = $this->_errors;
  803. if ($reset) {
  804. $this->_errors = [];
  805. }
  806. return $errors;
  807. }
  808. /**
  809. * Get the real path (taking ".." and such into account)
  810. *
  811. * @param string $path Path to resolve
  812. * @return string|bool The resolved path
  813. */
  814. public function realpath($path)
  815. {
  816. if (strpos($path, '..') === false) {
  817. if (!Folder::isAbsolute($path)) {
  818. $path = Folder::addPathElement($this->path, $path);
  819. }
  820. return $path;
  821. }
  822. $path = str_replace('/', DIRECTORY_SEPARATOR, trim($path));
  823. $parts = explode(DIRECTORY_SEPARATOR, $path);
  824. $newparts = [];
  825. $newpath = '';
  826. if ($path[0] === DIRECTORY_SEPARATOR) {
  827. $newpath = DIRECTORY_SEPARATOR;
  828. }
  829. while (($part = array_shift($parts)) !== null) {
  830. if ($part === '.' || $part === '') {
  831. continue;
  832. }
  833. if ($part === '..') {
  834. if (!empty($newparts)) {
  835. array_pop($newparts);
  836. continue;
  837. }
  838. return false;
  839. }
  840. $newparts[] = $part;
  841. }
  842. $newpath .= implode(DIRECTORY_SEPARATOR, $newparts);
  843. return Folder::slashTerm($newpath);
  844. }
  845. /**
  846. * Returns true if given $path ends in a slash (i.e. is slash-terminated).
  847. *
  848. * @param string $path Path to check
  849. * @return bool true if path ends with slash, false otherwise
  850. */
  851. public static function isSlashTerm($path)
  852. {
  853. $lastChar = $path[strlen($path) - 1];
  854. return $lastChar === '/' || $lastChar === '\\';
  855. }
  856. }