Folder.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 0.2.9
  13. * @license http://www.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 http://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 = null;
  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. * http://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|bool $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 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 = call_user_func_array('array_merge', $dirs);
  214. }
  215. if ($files) {
  216. $files = call_user_func_array('array_merge', $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('/^[A-Z]+(?=:\/\/)/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. $dir = substr(Folder::slashTerm(ROOT), 0, -1);
  365. $newdir = $dir . $path;
  366. return $this->inPath($newdir);
  367. }
  368. /**
  369. * Returns true if the Folder is in the given path.
  370. *
  371. * @param string $path The absolute path to check that the current `pwd()` resides within.
  372. * @param bool $reverse Reverse the search, check if the given `$path` resides within the current `pwd()`.
  373. * @return bool
  374. * @throws \InvalidArgumentException When the given `$path` argument is not an absolute path.
  375. */
  376. public function inPath($path, $reverse = false)
  377. {
  378. if (!Folder::isAbsolute($path)) {
  379. throw new InvalidArgumentException('The $path argument is expected to be an absolute path.');
  380. }
  381. $dir = Folder::slashTerm($path);
  382. $current = Folder::slashTerm($this->pwd());
  383. if (!$reverse) {
  384. $return = preg_match('/^' . preg_quote($dir, '/') . '(.*)/', $current);
  385. } else {
  386. $return = preg_match('/^' . preg_quote($current, '/') . '(.*)/', $dir);
  387. }
  388. return (bool)$return;
  389. }
  390. /**
  391. * Change the mode on a directory structure recursively. This includes changing the mode on files as well.
  392. *
  393. * @param string $path The path to chmod.
  394. * @param int|bool $mode Octal value, e.g. 0755.
  395. * @param bool $recursive Chmod recursively, set to false to only change the current directory.
  396. * @param array $exceptions Array of files, directories to skip.
  397. * @return bool Success.
  398. */
  399. public function chmod($path, $mode = false, $recursive = true, array $exceptions = [])
  400. {
  401. if (!$mode) {
  402. $mode = $this->mode;
  403. }
  404. if ($recursive === false && is_dir($path)) {
  405. //@codingStandardsIgnoreStart
  406. if (@chmod($path, intval($mode, 8))) {
  407. //@codingStandardsIgnoreEnd
  408. $this->_messages[] = sprintf('%s changed to %s', $path, $mode);
  409. return true;
  410. }
  411. $this->_errors[] = sprintf('%s NOT changed to %s', $path, $mode);
  412. return false;
  413. }
  414. if (is_dir($path)) {
  415. $paths = $this->tree($path);
  416. foreach ($paths as $type) {
  417. foreach ($type as $fullpath) {
  418. $check = explode(DIRECTORY_SEPARATOR, $fullpath);
  419. $count = count($check);
  420. if (in_array($check[$count - 1], $exceptions)) {
  421. continue;
  422. }
  423. //@codingStandardsIgnoreStart
  424. if (@chmod($fullpath, intval($mode, 8))) {
  425. //@codingStandardsIgnoreEnd
  426. $this->_messages[] = sprintf('%s changed to %s', $fullpath, $mode);
  427. } else {
  428. $this->_errors[] = sprintf('%s NOT changed to %s', $fullpath, $mode);
  429. }
  430. }
  431. }
  432. if (empty($this->_errors)) {
  433. return true;
  434. }
  435. }
  436. return false;
  437. }
  438. /**
  439. * Returns an array of subdirectories for the provided or current path.
  440. *
  441. * @param string|null $path The directory path to get subdirectories for.
  442. * @param bool $fullPath Whether to return the full path or only the directory name.
  443. * @return array Array of subdirectories for the provided or current path.
  444. */
  445. public function subdirectories($path = null, $fullPath = true)
  446. {
  447. if (!$path) {
  448. $path = $this->path;
  449. }
  450. $subdirectories = [];
  451. try {
  452. $iterator = new DirectoryIterator($path);
  453. } catch (Exception $e) {
  454. return [];
  455. }
  456. foreach ($iterator as $item) {
  457. if (!$item->isDir() || $item->isDot()) {
  458. continue;
  459. }
  460. $subdirectories[] = $fullPath ? $item->getRealPath() : $item->getFilename();
  461. }
  462. return $subdirectories;
  463. }
  464. /**
  465. * Returns an array of nested directories and files in each directory
  466. *
  467. * @param string|null $path the directory path to build the tree from
  468. * @param array|bool $exceptions Either an array of files/folder to exclude
  469. * or boolean true to not grab dot files/folders
  470. * @param string|null $type either 'file' or 'dir'. Null returns both files and directories
  471. * @return array Array of nested directories and files in each directory
  472. */
  473. public function tree($path = null, $exceptions = false, $type = null)
  474. {
  475. if (!$path) {
  476. $path = $this->path;
  477. }
  478. $files = [];
  479. $directories = [$path];
  480. if (is_array($exceptions)) {
  481. $exceptions = array_flip($exceptions);
  482. }
  483. $skipHidden = false;
  484. if ($exceptions === true) {
  485. $skipHidden = true;
  486. } elseif (isset($exceptions['.'])) {
  487. $skipHidden = true;
  488. unset($exceptions['.']);
  489. }
  490. try {
  491. $directory = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_PATHNAME | RecursiveDirectoryIterator::CURRENT_AS_SELF);
  492. $iterator = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
  493. } catch (Exception $e) {
  494. if ($type === null) {
  495. return [[], []];
  496. }
  497. return [];
  498. }
  499. foreach ($iterator as $itemPath => $fsIterator) {
  500. if ($skipHidden) {
  501. $subPathName = $fsIterator->getSubPathname();
  502. if ($subPathName{0} === '.' || strpos($subPathName, DIRECTORY_SEPARATOR . '.') !== false) {
  503. continue;
  504. }
  505. }
  506. $item = $fsIterator->current();
  507. if (!empty($exceptions) && isset($exceptions[$item->getFilename()])) {
  508. continue;
  509. }
  510. if ($item->isFile()) {
  511. $files[] = $itemPath;
  512. } elseif ($item->isDir() && !$item->isDot()) {
  513. $directories[] = $itemPath;
  514. }
  515. }
  516. if ($type === null) {
  517. return [$directories, $files];
  518. }
  519. if ($type === 'dir') {
  520. return $directories;
  521. }
  522. return $files;
  523. }
  524. /**
  525. * Create a directory structure recursively.
  526. *
  527. * Can be used to create deep path structures like `/foo/bar/baz/shoe/horn`
  528. *
  529. * @param string $pathname The directory structure to create. Either an absolute or relative
  530. * path. If the path is relative and exists in the process' cwd it will not be created.
  531. * Otherwise relative paths will be prefixed with the current pwd().
  532. * @param int|bool $mode octal value 0755
  533. * @return bool Returns TRUE on success, FALSE on failure
  534. */
  535. public function create($pathname, $mode = false)
  536. {
  537. if (is_dir($pathname) || empty($pathname)) {
  538. return true;
  539. }
  540. if (!self::isAbsolute($pathname)) {
  541. $pathname = self::addPathElement($this->pwd(), $pathname);
  542. }
  543. if (!$mode) {
  544. $mode = $this->mode;
  545. }
  546. if (is_file($pathname)) {
  547. $this->_errors[] = sprintf('%s is a file', $pathname);
  548. return false;
  549. }
  550. $pathname = rtrim($pathname, DIRECTORY_SEPARATOR);
  551. $nextPathname = substr($pathname, 0, strrpos($pathname, DIRECTORY_SEPARATOR));
  552. if ($this->create($nextPathname, $mode)) {
  553. if (!file_exists($pathname)) {
  554. $old = umask(0);
  555. if (mkdir($pathname, $mode, true)) {
  556. umask($old);
  557. $this->_messages[] = sprintf('%s created', $pathname);
  558. return true;
  559. }
  560. umask($old);
  561. $this->_errors[] = sprintf('%s NOT created', $pathname);
  562. return false;
  563. }
  564. }
  565. return false;
  566. }
  567. /**
  568. * Returns the size in bytes of this Folder and its contents.
  569. *
  570. * @return int size in bytes of current folder
  571. */
  572. public function dirsize()
  573. {
  574. $size = 0;
  575. $directory = Folder::slashTerm($this->path);
  576. $stack = [$directory];
  577. $count = count($stack);
  578. for ($i = 0, $j = $count; $i < $j; ++$i) {
  579. if (is_file($stack[$i])) {
  580. $size += filesize($stack[$i]);
  581. } elseif (is_dir($stack[$i])) {
  582. $dir = dir($stack[$i]);
  583. if ($dir) {
  584. while (($entry = $dir->read()) !== false) {
  585. if ($entry === '.' || $entry === '..') {
  586. continue;
  587. }
  588. $add = $stack[$i] . $entry;
  589. if (is_dir($stack[$i] . $entry)) {
  590. $add = Folder::slashTerm($add);
  591. }
  592. $stack[] = $add;
  593. }
  594. $dir->close();
  595. }
  596. }
  597. $j = count($stack);
  598. }
  599. return $size;
  600. }
  601. /**
  602. * Recursively Remove directories if the system allows.
  603. *
  604. * @param string|null $path Path of directory to delete
  605. * @return bool Success
  606. */
  607. public function delete($path = null)
  608. {
  609. if (!$path) {
  610. $path = $this->pwd();
  611. }
  612. if (!$path) {
  613. return false;
  614. }
  615. $path = Folder::slashTerm($path);
  616. if (is_dir($path)) {
  617. try {
  618. $directory = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::CURRENT_AS_SELF);
  619. $iterator = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::CHILD_FIRST);
  620. } catch (Exception $e) {
  621. return false;
  622. }
  623. foreach ($iterator as $item) {
  624. $filePath = $item->getPathname();
  625. if ($item->isFile() || $item->isLink()) {
  626. //@codingStandardsIgnoreStart
  627. if (@unlink($filePath)) {
  628. //@codingStandardsIgnoreEnd
  629. $this->_messages[] = sprintf('%s removed', $filePath);
  630. } else {
  631. $this->_errors[] = sprintf('%s NOT removed', $filePath);
  632. }
  633. } elseif ($item->isDir() && !$item->isDot()) {
  634. //@codingStandardsIgnoreStart
  635. if (@rmdir($filePath)) {
  636. //@codingStandardsIgnoreEnd
  637. $this->_messages[] = sprintf('%s removed', $filePath);
  638. } else {
  639. $this->_errors[] = sprintf('%s NOT removed', $filePath);
  640. return false;
  641. }
  642. }
  643. }
  644. $path = rtrim($path, DIRECTORY_SEPARATOR);
  645. //@codingStandardsIgnoreStart
  646. if (@rmdir($path)) {
  647. //@codingStandardsIgnoreEnd
  648. $this->_messages[] = sprintf('%s removed', $path);
  649. } else {
  650. $this->_errors[] = sprintf('%s NOT removed', $path);
  651. return false;
  652. }
  653. }
  654. return true;
  655. }
  656. /**
  657. * Recursive directory copy.
  658. *
  659. * ### Options
  660. *
  661. * - `to` The directory to copy to.
  662. * - `from` The directory to copy from, this will cause a cd() to occur, changing the results of pwd().
  663. * - `mode` The mode to copy the files/directories with as integer, e.g. 0775.
  664. * - `skip` Files/directories to skip.
  665. * - `scheme` Folder::MERGE, Folder::OVERWRITE, Folder::SKIP
  666. * - `recursive` Whether to copy recursively or not (default: true - recursive)
  667. *
  668. * @param array|string $options Either an array of options (see above) or a string of the destination directory.
  669. * @return bool Success.
  670. */
  671. public function copy($options)
  672. {
  673. if (!$this->pwd()) {
  674. return false;
  675. }
  676. $to = null;
  677. if (is_string($options)) {
  678. $to = $options;
  679. $options = [];
  680. }
  681. $options += [
  682. 'to' => $to,
  683. 'from' => $this->path,
  684. 'mode' => $this->mode,
  685. 'skip' => [],
  686. 'scheme' => Folder::MERGE,
  687. 'recursive' => true
  688. ];
  689. $fromDir = $options['from'];
  690. $toDir = $options['to'];
  691. $mode = $options['mode'];
  692. if (!$this->cd($fromDir)) {
  693. $this->_errors[] = sprintf('%s not found', $fromDir);
  694. return false;
  695. }
  696. if (!is_dir($toDir)) {
  697. $this->create($toDir, $mode);
  698. }
  699. if (!is_writable($toDir)) {
  700. $this->_errors[] = sprintf('%s not writable', $toDir);
  701. return false;
  702. }
  703. $exceptions = array_merge(['.', '..', '.svn'], $options['skip']);
  704. //@codingStandardsIgnoreStart
  705. if ($handle = @opendir($fromDir)) {
  706. //@codingStandardsIgnoreEnd
  707. while (($item = readdir($handle)) !== false) {
  708. $to = Folder::addPathElement($toDir, $item);
  709. if (($options['scheme'] != Folder::SKIP || !is_dir($to)) && !in_array($item, $exceptions)) {
  710. $from = Folder::addPathElement($fromDir, $item);
  711. if (is_file($from) && (!is_file($to) || $options['scheme'] != Folder::SKIP)) {
  712. if (copy($from, $to)) {
  713. chmod($to, intval($mode, 8));
  714. touch($to, filemtime($from));
  715. $this->_messages[] = sprintf('%s copied to %s', $from, $to);
  716. } else {
  717. $this->_errors[] = sprintf('%s NOT copied to %s', $from, $to);
  718. }
  719. }
  720. if (is_dir($from) && file_exists($to) && $options['scheme'] === Folder::OVERWRITE) {
  721. $this->delete($to);
  722. }
  723. if (is_dir($from) && $options['recursive'] === false) {
  724. continue;
  725. }
  726. if (is_dir($from) && !file_exists($to)) {
  727. $old = umask(0);
  728. if (mkdir($to, $mode, true)) {
  729. umask($old);
  730. $old = umask(0);
  731. chmod($to, $mode);
  732. umask($old);
  733. $this->_messages[] = sprintf('%s created', $to);
  734. $options = ['to' => $to, 'from' => $from] + $options;
  735. $this->copy($options);
  736. } else {
  737. $this->_errors[] = sprintf('%s not created', $to);
  738. }
  739. } elseif (is_dir($from) && $options['scheme'] === Folder::MERGE) {
  740. $options = ['to' => $to, 'from' => $from] + $options;
  741. $this->copy($options);
  742. }
  743. }
  744. }
  745. closedir($handle);
  746. } else {
  747. return false;
  748. }
  749. return empty($this->_errors);
  750. }
  751. /**
  752. * Recursive directory move.
  753. *
  754. * ### Options
  755. *
  756. * - `to` The directory to copy to.
  757. * - `from` The directory to copy from, this will cause a cd() to occur, changing the results of pwd().
  758. * - `chmod` The mode to copy the files/directories with.
  759. * - `skip` Files/directories to skip.
  760. * - `scheme` Folder::MERGE, Folder::OVERWRITE, Folder::SKIP
  761. * - `recursive` Whether to copy recursively or not (default: true - recursive)
  762. *
  763. * @param array|string $options (to, from, chmod, skip, scheme)
  764. * @return bool Success
  765. */
  766. public function move($options)
  767. {
  768. $to = null;
  769. if (is_string($options)) {
  770. $to = $options;
  771. $options = (array)$options;
  772. }
  773. $options += ['to' => $to, 'from' => $this->path, 'mode' => $this->mode, 'skip' => [], 'recursive' => true];
  774. if ($this->copy($options)) {
  775. if ($this->delete($options['from'])) {
  776. return (bool)$this->cd($options['to']);
  777. }
  778. }
  779. return false;
  780. }
  781. /**
  782. * get messages from latest method
  783. *
  784. * @param bool $reset Reset message stack after reading
  785. * @return array
  786. */
  787. public function messages($reset = true)
  788. {
  789. $messages = $this->_messages;
  790. if ($reset) {
  791. $this->_messages = [];
  792. }
  793. return $messages;
  794. }
  795. /**
  796. * get error from latest method
  797. *
  798. * @param bool $reset Reset error stack after reading
  799. * @return array
  800. */
  801. public function errors($reset = true)
  802. {
  803. $errors = $this->_errors;
  804. if ($reset) {
  805. $this->_errors = [];
  806. }
  807. return $errors;
  808. }
  809. /**
  810. * Get the real path (taking ".." and such into account)
  811. *
  812. * @param string $path Path to resolve
  813. * @return string The resolved path
  814. */
  815. public function realpath($path)
  816. {
  817. if (strpos($path, '..') === false) {
  818. if (!Folder::isAbsolute($path)) {
  819. $path = Folder::addPathElement($this->path, $path);
  820. }
  821. return $path;
  822. }
  823. $path = str_replace('/', DIRECTORY_SEPARATOR, trim($path));
  824. $parts = explode(DIRECTORY_SEPARATOR, $path);
  825. $newparts = [];
  826. $newpath = '';
  827. if ($path[0] === DIRECTORY_SEPARATOR) {
  828. $newpath = DIRECTORY_SEPARATOR;
  829. }
  830. while (($part = array_shift($parts)) !== null) {
  831. if ($part === '.' || $part === '') {
  832. continue;
  833. }
  834. if ($part === '..') {
  835. if (!empty($newparts)) {
  836. array_pop($newparts);
  837. continue;
  838. }
  839. return false;
  840. }
  841. $newparts[] = $part;
  842. }
  843. $newpath .= implode(DIRECTORY_SEPARATOR, $newparts);
  844. return Folder::slashTerm($newpath);
  845. }
  846. /**
  847. * Returns true if given $path ends in a slash (i.e. is slash-terminated).
  848. *
  849. * @param string $path Path to check
  850. * @return bool true if path ends with slash, false otherwise
  851. */
  852. public static function isSlashTerm($path)
  853. {
  854. $lastChar = $path[strlen($path) - 1];
  855. return $lastChar === '/' || $lastChar === '\\';
  856. }
  857. }