Folder.php 31 KB

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