3
* Convenience class for handling directories.
7
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
8
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
10
* Licensed under The MIT License
11
* Redistributions of files must retain the above copyright notice.
13
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
14
* @link http://cakephp.org CakePHP(tm) Project
16
* @subpackage cake.cake.libs
17
* @since CakePHP(tm) v 0.2.9
18
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
25
if (!class_exists('Object')) {
26
require LIBS . 'object.php';
30
* Folder structure browser, lists folders and files.
31
* Provides an Object interface for Common directory related tasks.
34
* @subpackage cake.cake.libs
36
class Folder extends Object {
47
* Sortedness. Whether or not list results
48
* should be sorted by name.
56
* Mode to be used on create. Does nothing on windows platforms.
64
* Holds messages from last method.
69
var $__messages = array();
72
* Holds errors from last method.
77
var $__errors = false;
80
* Holds array of complete directory paths.
88
* Holds array of complete file paths.
98
* @param string $path Path to folder
99
* @param boolean $create Create folder if not found
100
* @param mixed $mode Mode (CHMOD) to apply to created folder, false to ignore
102
function __construct($path = false, $create = false, $mode = false) {
103
parent::__construct();
111
if (!file_exists($path) && $create === true) {
112
$this->create($path, $this->mode);
114
if (!Folder::isAbsolute($path)) {
115
$path = realpath($path);
123
* Return current path.
125
* @return string Current path
133
* Change directory to $path.
135
* @param string $path Path to the directory to change to
136
* @return string The new path. Returns false on failure
140
$path = $this->realpath($path);
142
return $this->path = $path;
148
* Returns an array of the contents of the current directory.
149
* The returned array holds two arrays: One of directories and one of files.
151
* @param boolean $sort Whether you want the results sorted, set this and the sort property
152
* to false to get unsorted results.
153
* @param mixed $exceptions Either an array or boolean true will not grab dot files
154
* @param boolean $fullPath True returns the full path
155
* @return mixed Contents of current directory as an array, an empty array on failure
158
function read($sort = true, $exceptions = false, $fullPath = false) {
159
$dirs = $files = array();
162
return array($dirs, $files);
164
if (is_array($exceptions)) {
165
$exceptions = array_flip($exceptions);
167
$skipHidden = isset($exceptions['.']) || $exceptions === true;
169
if (false === ($dir = @opendir($this->path))) {
170
return array($dirs, $files);
173
while (false !== ($item = readdir($dir))) {
174
if ($item === '.' || $item === '..' || ($skipHidden && $item[0] === '.') || isset($exceptions[$item])) {
178
$path = Folder::addPathElement($this->path, $item);
180
$dirs[] = $fullPath ? $path : $item;
182
$files[] = $fullPath ? $path : $item;
186
if ($sort || $this->sort) {
192
return array($dirs, $files);
196
* Returns an array of all matching files in current directory.
198
* @param string $pattern Preg_match pattern (Defaults to: .*)
199
* @param boolean $sort Whether results should be sorted.
200
* @return array Files that match given pattern
203
function find($regexpPattern = '.*', $sort = false) {
204
list($dirs, $files) = $this->read($sort);
205
return array_values(preg_grep('/^' . $regexpPattern . '$/i', $files)); ;
209
* Returns an array of all matching files in and below current directory.
211
* @param string $pattern Preg_match pattern (Defaults to: .*)
212
* @param boolean $sort Whether results should be sorted.
213
* @return array Files matching $pattern
216
function findRecursive($pattern = '.*', $sort = false) {
220
$startsOn = $this->path;
221
$out = $this->_findRecursive($pattern, $sort);
222
$this->cd($startsOn);
227
* Private helper function for findRecursive.
229
* @param string $pattern Pattern to match against
230
* @param boolean $sort Whether results should be sorted.
231
* @return array Files matching pattern
234
function _findRecursive($pattern, $sort = false) {
235
list($dirs, $files) = $this->read($sort);
238
foreach ($files as $file) {
239
if (preg_match('/^' . $pattern . '$/i', $file)) {
240
$found[] = Folder::addPathElement($this->path, $file);
243
$start = $this->path;
245
foreach ($dirs as $dir) {
246
$this->cd(Folder::addPathElement($start, $dir));
247
$found = array_merge($found, $this->findRecursive($pattern, $sort));
253
* Returns true if given $path is a Windows path.
255
* @param string $path Path to check
256
* @return boolean true if windows path, false otherwise
260
function isWindowsPath($path) {
261
return (bool)preg_match('/^[A-Z]:\\\\/i', $path);
265
* Returns true if given $path is an absolute path.
267
* @param string $path Path to check
268
* @return bool true if path is absolute.
272
function isAbsolute($path) {
273
return !empty($path) && ($path[0] === '/' || preg_match('/^[A-Z]:\\\\/i', $path));
277
* Returns a correct set of slashes for given $path. (\\ for Windows paths and / for other paths.)
279
* @param string $path Path to check
280
* @return string Set of slashes ("\\" or "/")
284
function normalizePath($path) {
285
return Folder::correctSlashFor($path);
289
* Returns a correct set of slashes for given $path. (\\ for Windows paths and / for other paths.)
291
* @param string $path Path to check
292
* @return string Set of slashes ("\\" or "/")
296
function correctSlashFor($path) {
297
return (Folder::isWindowsPath($path)) ? '\\' : '/';
301
* Returns $path with added terminating slash (corrected for Windows or other OS).
303
* @param string $path Path to check
304
* @return string Path with ending slash
308
function slashTerm($path) {
309
if (Folder::isSlashTerm($path)) {
312
return $path . Folder::correctSlashFor($path);
316
* Returns $path with $element added, with correct slash in-between.
318
* @param string $path Path
319
* @param string $element Element to and at end of path
320
* @return string Combined path
324
function addPathElement($path, $element) {
325
return rtrim($path, DS) . DS . $element;
329
* Returns true if the File is in a given CakePath.
331
* @param string $path The path to check.
335
function inCakePath($path = '') {
336
$dir = substr(Folder::slashTerm(ROOT), 0, -1);
337
$newdir = $dir . $path;
339
return $this->inPath($newdir);
343
* Returns true if the File is in given path.
345
* @param string $path The path to check that the current pwd() resides with in.
346
* @param boolean $reverse
350
function inPath($path = '', $reverse = false) {
351
$dir = Folder::slashTerm($path);
352
$current = Folder::slashTerm($this->pwd());
355
$return = preg_match('/^(.*)' . preg_quote($dir, '/') . '(.*)/', $current);
357
$return = preg_match('/^(.*)' . preg_quote($current, '/') . '(.*)/', $dir);
359
return (bool)$return;
363
* Change the mode on a directory structure recursively. This includes changing the mode on files as well.
365
* @param string $path The path to chmod
366
* @param integer $mode octal value 0755
367
* @param boolean $recursive chmod recursively, set to false to only change the current directory.
368
* @param array $exceptions array of files, directories to skip
369
* @return boolean Returns TRUE on success, FALSE on failure
372
function chmod($path, $mode = false, $recursive = true, $exceptions = array()) {
377
if ($recursive === false && is_dir($path)) {
378
if (@chmod($path, intval($mode, 8))) {
379
$this->__messages[] = sprintf(__('%s changed to %s', true), $path, $mode);
383
$this->__errors[] = sprintf(__('%s NOT changed to %s', true), $path, $mode);
388
$paths = $this->tree($path);
390
foreach ($paths as $type) {
391
foreach ($type as $key => $fullpath) {
392
$check = explode(DS, $fullpath);
393
$count = count($check);
395
if (in_array($check[$count - 1], $exceptions)) {
399
if (@chmod($fullpath, intval($mode, 8))) {
400
$this->__messages[] = sprintf(__('%s changed to %s', true), $fullpath, $mode);
402
$this->__errors[] = sprintf(__('%s NOT changed to %s', true), $fullpath, $mode);
407
if (empty($this->__errors)) {
415
* Returns an array of nested directories and files in each directory
417
* @param string $path the directory path to build the tree from
418
* @param mixed $exceptions Array of files to exclude, defaults to excluding hidden files.
419
* @param string $type either file or dir. null returns both files and directories
420
* @return mixed array of nested directories and files in each directory
423
function tree($path, $exceptions = true, $type = null) {
424
$original = $this->path;
425
$path = rtrim($path, DS);
426
if (!$this->cd($path)) {
427
if ($type === null) {
428
return array(array(), array());
432
$this->__files = array();
433
$this->__directories = array($this->realpath($path));
434
$directories = array();
436
if ($exceptions === false) {
439
while (!empty($this->__directories)) {
440
$dir = array_pop($this->__directories);
441
$this->__tree($dir, $exceptions);
442
$directories[] = $dir;
445
if ($type === null) {
446
return array($directories, $this->__files);
448
if ($type === 'dir') {
451
$this->cd($original);
453
return $this->__files;
457
* Private method to list directories and files in each directory
459
* @param string $path The Path to read.
460
* @param mixed $exceptions Array of files to exclude from the read that will be performed.
463
function __tree($path, $exceptions) {
465
list($dirs, $files) = $this->read(false, $exceptions, true);
466
$this->__directories = array_merge($this->__directories, $dirs);
467
$this->__files = array_merge($this->__files, $files);
471
* Create a directory structure recursively. Can be used to create
472
* deep path structures like `/foo/bar/baz/shoe/horn`
474
* @param string $pathname The directory structure to create
475
* @param integer $mode octal value 0755
476
* @return boolean Returns TRUE on success, FALSE on failure
479
function create($pathname, $mode = false) {
480
if (is_dir($pathname) || empty($pathname)) {
488
if (is_file($pathname)) {
489
$this->__errors[] = sprintf(__('%s is a file', true), $pathname);
492
$pathname = rtrim($pathname, DS);
493
$nextPathname = substr($pathname, 0, strrpos($pathname, DS));
495
if ($this->create($nextPathname, $mode)) {
496
if (!file_exists($pathname)) {
498
if (mkdir($pathname, $mode)) {
500
$this->__messages[] = sprintf(__('%s created', true), $pathname);
504
$this->__errors[] = sprintf(__('%s NOT created', true), $pathname);
513
* Returns the size in bytes of this Folder and its contents.
515
* @param string $directory Path to directory
516
* @return int size in bytes of current folder
521
$directory = Folder::slashTerm($this->path);
522
$stack = array($directory);
523
$count = count($stack);
524
for ($i = 0, $j = $count; $i < $j; ++$i) {
525
if (is_file($stack[$i])) {
526
$size += filesize($stack[$i]);
527
} elseif (is_dir($stack[$i])) {
528
$dir = dir($stack[$i]);
530
while (false !== ($entry = $dir->read())) {
531
if ($entry === '.' || $entry === '..') {
534
$add = $stack[$i] . $entry;
536
if (is_dir($stack[$i] . $entry)) {
537
$add = Folder::slashTerm($add);
550
* Recursively Remove directories if the system allows.
552
* @param string $path Path of directory to delete
553
* @return boolean Success
556
function delete($path = null) {
558
$path = $this->pwd();
563
$path = Folder::slashTerm($path);
564
if (is_dir($path) === true) {
565
$normalFiles = glob($path . '*');
566
$hiddenFiles = glob($path . '\.?*');
568
$normalFiles = $normalFiles ? $normalFiles : array();
569
$hiddenFiles = $hiddenFiles ? $hiddenFiles : array();
571
$files = array_merge($normalFiles, $hiddenFiles);
572
if (is_array($files)) {
573
foreach ($files as $file) {
574
if (preg_match('/(\.|\.\.)$/', $file)) {
577
if (is_file($file) === true) {
578
if (@unlink($file)) {
579
$this->__messages[] = sprintf(__('%s removed', true), $file);
581
$this->__errors[] = sprintf(__('%s NOT removed', true), $file);
583
} elseif (is_dir($file) === true && $this->delete($file) === false) {
588
$path = substr($path, 0, strlen($path) - 1);
589
if (rmdir($path) === false) {
590
$this->__errors[] = sprintf(__('%s NOT removed', true), $path);
593
$this->__messages[] = sprintf(__('%s removed', true), $path);
600
* Recursive directory copy.
604
* - `to` The directory to copy to.
605
* - `from` The directory to copy from, this will cause a cd() to occur, changing the results of pwd().
606
* - `chmod` The mode to copy the files/directories with.
607
* - `skip` Files/directories to skip.
609
* @param mixed $options Either an array of options (see above) or a string of the destination directory.
610
* @return bool Success
613
function copy($options = array()) {
618
if (is_string($options)) {
622
$options = array_merge(array('to' => $to, 'from' => $this->path, 'mode' => $this->mode, 'skip' => array()), $options);
624
$fromDir = $options['from'];
625
$toDir = $options['to'];
626
$mode = $options['mode'];
628
if (!$this->cd($fromDir)) {
629
$this->__errors[] = sprintf(__('%s not found', true), $fromDir);
633
if (!is_dir($toDir)) {
634
$this->create($toDir, $mode);
637
if (!is_writable($toDir)) {
638
$this->__errors[] = sprintf(__('%s not writable', true), $toDir);
642
$exceptions = array_merge(array('.', '..', '.svn'), $options['skip']);
643
if ($handle = @opendir($fromDir)) {
644
while (false !== ($item = readdir($handle))) {
645
if (!in_array($item, $exceptions)) {
646
$from = Folder::addPathElement($fromDir, $item);
647
$to = Folder::addPathElement($toDir, $item);
648
if (is_file($from)) {
649
if (copy($from, $to)) {
650
chmod($to, intval($mode, 8));
651
touch($to, filemtime($from));
652
$this->__messages[] = sprintf(__('%s copied to %s', true), $from, $to);
654
$this->__errors[] = sprintf(__('%s NOT copied to %s', true), $from, $to);
658
if (is_dir($from) && !file_exists($to)) {
660
if (mkdir($to, $mode)) {
665
$this->__messages[] = sprintf(__('%s created', true), $to);
666
$options = array_merge($options, array('to'=> $to, 'from'=> $from));
667
$this->copy($options);
669
$this->__errors[] = sprintf(__('%s not created', true), $to);
679
if (!empty($this->__errors)) {
686
* Recursive directory move.
690
* - `to` The directory to copy to.
691
* - `from` The directory to copy from, this will cause a cd() to occur, changing the results of pwd().
692
* - `chmod` The mode to copy the files/directories with.
693
* - `skip` Files/directories to skip.
695
* @param array $options (to, from, chmod, skip)
696
* @return boolean Success
699
function move($options) {
701
if (is_string($options)) {
703
$options = (array)$options;
705
$options = array_merge(array('to' => $to, 'from' => $this->path, 'mode' => $this->mode, 'skip' => array()), $options);
707
if ($this->copy($options)) {
708
if ($this->delete($options['from'])) {
709
return $this->cd($options['to']);
716
* get messages from latest method
721
function messages() {
722
return $this->__messages;
726
* get error from latest method
732
return $this->__errors;
736
* Get the real path (taking ".." and such into account)
738
* @param string $path Path to resolve
739
* @return string The resolved path
741
function realpath($path) {
742
$path = str_replace('/', DS, trim($path));
743
if (strpos($path, '..') === false) {
744
if (!Folder::isAbsolute($path)) {
745
$path = Folder::addPathElement($this->path, $path);
749
$parts = explode(DS, $path);
752
if ($path[0] === DS) {
756
while (($part = array_shift($parts)) !== NULL) {
757
if ($part === '.' || $part === '') {
760
if ($part === '..') {
761
if (!empty($newparts)) {
762
array_pop($newparts);
770
$newpath .= implode(DS, $newparts);
772
return Folder::slashTerm($newpath);
776
* Returns true if given $path ends in a slash (i.e. is slash-terminated).
778
* @param string $path Path to check
779
* @return boolean true if path ends with slash, false otherwise
783
function isSlashTerm($path) {
784
$lastChar = $path[strlen($path) - 1];
785
return $lastChar === '/' || $lastChar === '\\';