folder.php

Go to the documentation of this file.
00001 <?php
00002 /* SVN FILE: $Id: folder_8php-source.html 580 2008-07-01 14:45:49Z gwoo $ */
00003 /**
00004  * Convenience class for handling directories.
00005  *
00006  * PHP versions 4 and 5
00007  *
00008  * CakePHP(tm) :  Rapid Development Framework <http://www.cakephp.org/>
00009  * Copyright 2005-2008, Cake Software Foundation, Inc.
00010  *                              1785 E. Sahara Avenue, Suite 490-204
00011  *                              Las Vegas, Nevada 89104
00012  *
00013  * Licensed under The MIT License
00014  * Redistributions of files must retain the above copyright notice.
00015  *
00016  * @filesource
00017  * @copyright       Copyright 2005-2008, Cake Software Foundation, Inc.
00018  * @link                http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
00019  * @package         cake
00020  * @subpackage      cake.cake.libs
00021  * @since           CakePHP(tm) v 0.2.9
00022  * @version         $Revision: 580 $
00023  * @modifiedby      $LastChangedBy: gwoo $
00024  * @lastmodified    $Date: 2008-07-01 09:45:49 -0500 (Tue, 01 Jul 2008) $
00025  * @license         http://www.opensource.org/licenses/mit-license.php The MIT License
00026  */
00027 /**
00028  * Included libraries.
00029  *
00030  */
00031     if (!class_exists('Object')) {
00032         uses ('object');
00033     }
00034 /**
00035  * Folder structure browser, lists folders and files.
00036  *
00037  * Long description for class
00038  *
00039  * @package     cake
00040  * @subpackage  cake.cake.libs
00041  */
00042 class Folder extends Object{
00043 /**
00044  * Path to Folder.
00045  *
00046  * @var string
00047  * @access public
00048  */
00049     var $path = null;
00050 /**
00051  * Sortedness.
00052  *
00053  * @var boolean
00054  * @access public
00055  */
00056     var $sort = false;
00057 /**
00058  * mode to be used on create.
00059  *
00060  * @var boolean
00061  * @access public
00062  */
00063     var $mode = '0755';
00064 /**
00065  * holds messages from last method.
00066  *
00067  * @var array
00068  * @access private
00069  */
00070     var $__messages = array();
00071 /**
00072  * holds errors from last method.
00073  *
00074  * @var array
00075  * @access private
00076  */
00077     var $__errors = false;
00078 /**
00079  * holds array of complete directory paths.
00080  *
00081  * @var array
00082  * @access private
00083  */
00084     var $__directories;
00085 /**
00086  * holds array of complete file paths.
00087  *
00088  * @var array
00089  * @access private
00090  */
00091     var $__files;
00092 /**
00093  * Constructor.
00094  *
00095  * @param string $path Path to folder
00096  * @param boolean $create Create folder if not found
00097  * @param mixed $mode Mode (CHMOD) to apply to created folder, false to ignore
00098  */
00099     function __construct($path = false, $create = false, $mode = false) {
00100         parent::__construct();
00101         if (empty($path)) {
00102             $path = TMP;
00103         }
00104         if ($mode) {
00105             $this->mode = intval($mode, 8);
00106         }
00107 
00108         if (!file_exists($path) && $create == true) {
00109             $this->create($path, $this->mode);
00110         }
00111         if (!$this->isAbsolute($path)) {
00112             $path = realpath($path);
00113         }
00114         if (!empty($path)) {
00115             $this->cd($path);
00116         }
00117     }
00118 /**
00119  * Return current path.
00120  *
00121  * @return string Current path
00122  * @access public
00123  */
00124     function pwd() {
00125         return $this->path;
00126     }
00127 /**
00128  * Change directory to $desired_path.
00129  *
00130  * @param string $desired_path Path to the directory to change to
00131  * @return string The new path. Returns false on failure
00132  * @access public
00133  */
00134     function cd($path) {
00135         $path = $this->realpath($path);
00136         if (is_dir($path) && file_exists($path)) {
00137             return $this->path = $path;
00138         }
00139         return false;
00140     }
00141 /**
00142  * Returns an array of the contents of the current directory, or false on failure.
00143  * The returned array holds two arrays: one of dirs and one of files.
00144  *
00145  * @param boolean $sort
00146  * @param mixed $exceptions either an array or boolean true will no grab dot files
00147  * @return mixed Contents of current directory as an array, false on failure
00148  * @access public
00149  */
00150     function read($sort = true, $exceptions = false) {
00151         $dirs = $files = array();
00152 
00153         if ($dir = @opendir($this->path)) {
00154             while (false !== ($n = readdir($dir))) {
00155                 $item = false;
00156                 if (is_array($exceptions)) {
00157                     if (!in_array($n, $exceptions)) {
00158                         $item = $n;
00159                     }
00160                 } elseif ((!preg_match('/^\\.+$/', $n) && $exceptions == false) || ($exceptions == true && !preg_match('/^\\.(.*)$/', $n))) {
00161                     $item = $n;
00162                 }
00163 
00164                 if ($item !== false) {
00165                     if (is_dir($this->addPathElement($this->path, $item))) {
00166                         $dirs[] = $item;
00167                     } else {
00168                         $files[] = $item;
00169                     }
00170                 }
00171             }
00172 
00173             if ($sort || $this->sort) {
00174                 sort ($dirs);
00175                 sort ($files);
00176             }
00177             closedir ($dir);
00178         }
00179         return array($dirs, $files);
00180     }
00181 /**
00182  * Returns an array of all matching files in current directory.
00183  *
00184  * @param string $pattern Preg_match pattern (Defaults to: .*)
00185  * @return array Files that match given pattern
00186  * @access public
00187  */
00188     function find($regexp_pattern = '.*', $sort = false) {
00189         $data = $this->read($sort);
00190 
00191         if (!is_array($data)) {
00192             return array();
00193         }
00194 
00195         list($dirs, $files) = $data;
00196         $found =  array();
00197 
00198         foreach ($files as $file) {
00199             if (preg_match("/^{$regexp_pattern}$/i", $file)) {
00200                 $found[] = $file;
00201             }
00202         }
00203         return $found;
00204     }
00205 /**
00206  * Returns an array of all matching files in and below current directory.
00207  *
00208  * @param string $pattern Preg_match pattern (Defaults to: .*)
00209  * @return array Files matching $pattern
00210  * @access public
00211  */
00212     function findRecursive($pattern = '.*', $sort = false) {
00213         $startsOn = $this->path;
00214         $out = $this->_findRecursive($pattern, $sort);
00215         $this->cd($startsOn);
00216         return $out;
00217     }
00218 /**
00219  * Private helper function for findRecursive.
00220  *
00221  * @param string $pattern Pattern to match against
00222  * @return array Files matching pattern
00223  * @access private
00224  */
00225     function _findRecursive($pattern, $sort = false) {
00226         list($dirs, $files) = $this->read($sort);
00227 
00228         $found = array();
00229         foreach ($files as $file) {
00230             if (preg_match("/^{$pattern}$/i", $file)) {
00231                 $found[] = $this->addPathElement($this->path, $file);
00232             }
00233         }
00234         $start = $this->path;
00235         foreach ($dirs as $dir) {
00236             $this->cd($this->addPathElement($start, $dir));
00237             $found = array_merge($found, $this->findRecursive($pattern));
00238         }
00239         return $found;
00240     }
00241 /**
00242  * Returns true if given $path is a Windows path.
00243  *
00244  * @param string $path Path to check
00245  * @return boolean true if windows path, false otherwise
00246  * @access public
00247  * @static
00248  */
00249     function isWindowsPath($path) {
00250         if (preg_match('/^[A-Z]:\\\\/i', $path)) {
00251             return true;
00252         }
00253         return false;
00254     }
00255 /**
00256  * Returns true if given $path is an absolute path.
00257  *
00258  * @param string $path Path to check
00259  * @return bool
00260  * @access public
00261  * @static
00262  */
00263     function isAbsolute($path) {
00264         $match = preg_match('/^\\//', $path) || preg_match('/^[A-Z]:\\\\/i', $path);
00265         return $match;
00266     }
00267 /**
00268  * Returns a correct set of slashes for given $path. (\\ for Windows paths and / for other paths.)
00269  *
00270  * @param string $path Path to check
00271  * @return string Set of slashes ("\\" or "/")
00272  * @access public
00273  * @static
00274  */
00275     function normalizePath($path) {
00276         if (Folder::isWindowsPath($path)) {
00277             return '\\';
00278         }
00279         return '/';
00280     }
00281 /**
00282  * Returns a correct set of slashes for given $path. (\\ for Windows paths and / for other paths.)
00283  *
00284  * @param string $path Path to check
00285  * @return string Set of slashes ("\\" or "/")
00286  * @access public
00287  * @static
00288  */
00289     function correctSlashFor($path) {
00290         return Folder::normalizePath($path);
00291     }
00292 /**
00293  * Returns $path with added terminating slash (corrected for Windows or other OS).
00294  *
00295  * @param string $path Path to check
00296  * @return string Path with ending slash
00297  * @access public
00298  * @static
00299  */
00300     function slashTerm($path) {
00301         if (Folder::isSlashTerm($path)) {
00302             return $path;
00303         }
00304         return $path . Folder::correctSlashFor($path);
00305     }
00306 /**
00307  * Returns $path with $element added, with correct slash in-between.
00308  *
00309  * @param string $path Path
00310  * @param string $element Element to and at end of path
00311  * @return string Combined path
00312  * @access public
00313  * @static
00314  */
00315     function addPathElement($path, $element) {
00316         return $this->slashTerm($path) . $element;
00317     }
00318 /**
00319  * Returns true if the File is in a given CakePath.
00320  *
00321  * @return bool
00322  * @access public
00323  */
00324     function inCakePath($path = '') {
00325         $dir = substr($this->slashTerm(ROOT), 0, -1);
00326         $newdir = $dir . $path;
00327 
00328         return $this->inPath($newdir);
00329     }
00330 /**
00331  * Returns true if the File is in given path.
00332  *
00333  * @return bool
00334  * @access public
00335  */
00336     function inPath($path = '', $reverse = false) {
00337         $dir = $this->slashTerm($path);
00338         $current = $this->slashTerm($this->pwd());
00339 
00340         if (!$reverse) {
00341             $return = preg_match('/^(.*)' . preg_quote($dir, '/') . '(.*)/', $current);
00342         } else {
00343             $return = preg_match('/^(.*)' . preg_quote($current, '/') . '(.*)/', $dir);
00344         }
00345         if ($return == 1) {
00346             return true;
00347         } else {
00348             return false;
00349         }
00350     }
00351 /**
00352  * Change the mode on a directory structure recursively.
00353  *
00354  * @param string $path The path to chmod
00355  * @param integer $mode octal value 0755
00356  * @param boolean $recursive chmod recursively
00357  * @param array $exceptions array of files, directories to skip
00358  * @return boolean Returns TRUE on success, FALSE on failure
00359  * @access public
00360  */
00361     function chmod($path, $mode = false, $recursive = true, $exceptions = array()) {
00362         if (!$mode) {
00363             $mode = $this->mode;
00364         }
00365 
00366         if ($recursive === false && is_dir($path)) {
00367             if (chmod($path, intval($mode, 8))) {
00368                 $this->__messages[] = sprintf(__('%s changed to %s', true), $path, $mode);
00369                 return true;
00370             } else {
00371                 $this->__errors[] = sprintf(__('%s NOT changed to %s', true), $path, $mode);
00372                 return false;
00373             }
00374         }
00375 
00376         if (is_dir($path)) {
00377             list($paths) = $this->tree($path);
00378 
00379             foreach ($paths as $key => $fullpath) {
00380                 $check = explode(DS, $fullpath);
00381                 $count = count($check);
00382 
00383                 if (in_array($check[$count - 1], $exceptions)) {
00384                     continue;
00385                 }
00386 
00387                 if (chmod($fullpath, intval($mode, 8))) {
00388                     $this->__messages[] = sprintf(__('%s changed to %s', true), $fullpath, $mode);
00389                 } else {
00390                     $this->__errors[] = sprintf(__('%s NOT changed to %s', true), $fullpath, $mode);
00391                 }
00392             }
00393             if (empty($this->__errors)) {
00394                 return true;
00395             }
00396         }
00397         return false;
00398     }
00399 /**
00400  * Returns an array of nested directories and files in each directory
00401  *
00402  * @param string $path the directory path to build the tree from
00403  * @param boolean $hidden return hidden files and directories
00404  * @param string $type either file or dir. null returns both files and directories
00405  * @return mixed array of nested directories and files in each directory
00406  * @access public
00407  */
00408     function tree($path, $hidden = true, $type = null) {
00409         $path = rtrim($path, DS);
00410         $this->__files = array();
00411         $this->__directories = array($path);
00412         $directories = array();
00413 
00414         while (count($this->__directories)) {
00415             $dir = array_pop($this->__directories);
00416             $this->__tree($dir, $hidden);
00417             array_push($directories, $dir);
00418 
00419         }
00420         if ($type === null) {
00421             return array($directories, $this->__files);
00422         }
00423         if ($type === 'dir') {
00424             return $directories;
00425         }
00426         return $this->__files;
00427     }
00428 /**
00429  * Private method to list directories and files in each directory
00430  *
00431  * @param string $path
00432  * @param = boolean $hidden
00433  * @access private
00434  */
00435     function __tree($path, $hidden) {
00436         if (is_dir($path) && $dirHandle = @opendir($path)) {
00437             while (false !== ($item = @readdir($dirHandle))) {
00438                 $found = false;
00439 
00440                 if (($hidden === true && $item != '.' && $item != '..') || ($hidden === false && !preg_match('/^\\.(.*)$/', $item))) {
00441                     $found = $path . DS . $item;
00442                 }
00443 
00444                 if ($found !== false) {
00445                     if (is_dir($found)) {
00446                         array_push($this->__directories, $found);
00447                     } else {
00448                         array_push($this->__files, $found);
00449                     }
00450                 }
00451             }
00452             closedir($dirHandle);
00453         }
00454     }
00455 /**
00456  * Create a directory structure recursively.
00457  *
00458  * @param string $pathname The directory structure to create
00459  * @param integer $mode octal value 0755
00460  * @return boolean Returns TRUE on success, FALSE on failure
00461  * @access public
00462  */
00463     function create($pathname, $mode = false) {
00464         if (is_dir($pathname) || empty($pathname)) {
00465             return true;
00466         }
00467 
00468         if (!$mode) {
00469             $mode = $this->mode;
00470         }
00471 
00472         if (is_file($pathname)) {
00473             $this->__errors[] = sprintf(__('%s is a file', true), $pathname);
00474             return true;
00475         }
00476         $nextPathname = substr($pathname, 0, strrpos($pathname, DS));
00477 
00478         if ($this->create($nextPathname, $mode)) {
00479             if (!file_exists($pathname)) {
00480                 if (mkdir($pathname, intval($mode, 8))) {
00481                     $this->__messages[] = sprintf(__('%s created', true), $pathname);
00482                     return true;
00483                 } else {
00484                     $this->__errors[] = sprintf(__('%s NOT created', true), $pathname);
00485                     return false;
00486                 }
00487             }
00488         }
00489         return true;
00490     }
00491 /**
00492  * Returns the size in bytes of this Folder.
00493  *
00494  * @param string $directory Path to directory
00495  * @access public
00496  */
00497     function dirsize() {
00498         $size = 0;
00499         $directory = $this->slashTerm($this->path);
00500         $stack = array($directory);
00501         $count = count($stack);
00502         for ($i = 0, $j = $count; $i < $j; ++$i) {
00503             if (is_file($stack[$i])) {
00504                 $size += filesize($stack[$i]);
00505             } elseif (is_dir($stack[$i])) {
00506                 $dir = dir($stack[$i]);
00507                 if ($dir) {
00508                     while (false !== ($entry = $dir->read())) {
00509                         if ($entry == '.' || $entry == '..') {
00510                             continue;
00511                         }
00512                         $add = $stack[$i] . $entry;
00513 
00514                         if (is_dir($stack[$i] . $entry)) {
00515                             $add = $this->slashTerm($add);
00516                         }
00517                         $stack[ ]= $add;
00518                     }
00519                     $dir->close();
00520                 }
00521             }
00522             $j = count($stack);
00523         }
00524         return $size;
00525     }
00526 /**
00527  * Recursively Remove directories if system allow.
00528  *
00529  * @param string $path Path of directory to delete
00530  * @return boolean Success
00531  * @access public
00532  */
00533     function delete($path = null) {
00534         if (!$path) {
00535             $path = $this->pwd();
00536         }
00537         $path = $this->slashTerm($path);
00538         if (is_dir($path) === true) {
00539             $files = glob($path . "*", GLOB_NOSORT);
00540             $normal_files = glob($path . "*");
00541             $hidden_files = glob($path . "\.?*");
00542             $files = array_merge($normal_files, $hidden_files);
00543             if (is_array($files)) {
00544                 foreach ($files as $file) {
00545                     if (preg_match("/(\.|\.\.)$/", $file)) {
00546                         continue;
00547                     }
00548                     if (is_file($file) === true) {
00549                         if (@unlink($file)) {
00550                             $this->__messages[] = sprintf(__('%s removed', true), $path);
00551                         } else {
00552                             $this->__errors[] = sprintf(__('%s NOT removed', true), $path);
00553                         }
00554                     } elseif (is_dir($file) === true) {
00555                         if ($this->delete($file) === false) {
00556                             return false;
00557                         }
00558                     }
00559                 }
00560             }
00561             $path = substr($path, 0, strlen($path) - 1);
00562             if (rmdir($path) === false) {
00563                 $this->__errors[] = sprintf(__('%s NOT removed', true), $path);
00564                 return false;
00565             } else {
00566                 $this->__messages[] = sprintf(__('%s removed', true), $path);
00567             }
00568         }
00569         return true;
00570     }
00571 /**
00572  * Recursive directory copy.
00573  *
00574  * @param array $options (to, from, chmod, skip)
00575  * @return bool
00576  * @access public
00577  */
00578     function copy($options = array()) {
00579         $to = null;
00580         if (is_string($options)) {
00581             $to = $options;
00582             $options = array();
00583         }
00584         $options = array_merge(array('to'=> $to, 'from'=> $this->path, 'mode'=> $this->mode, 'skip'=> array()), $options);
00585 
00586         $fromDir = $options['from'];
00587         $toDir = $options['to'];
00588         $mode = $options['mode'];
00589 
00590         if (!$this->cd($fromDir)) {
00591             $this->__errors[] = sprintf(__('%s not found', true), $fromDir);
00592             return false;
00593         }
00594 
00595         if (!is_dir($toDir)) {
00596             $this->mkdir($toDir, $mode);
00597         }
00598 
00599         if (!is_writable($toDir)) {
00600             $this->__errors[] = sprintf(__('%s not writable', true), $toDir);
00601             return false;
00602         }
00603 
00604         $exceptions = array_merge(array('.','..','.svn'), $options['skip']);
00605 
00606         if ($handle = @opendir($fromDir)) {
00607             while (false !== ($item = readdir($handle))) {
00608                 if (!in_array($item, $exceptions)) {
00609                     $from = $this->addPathElement($fromDir, $item);
00610                     $to = $this->addPathElement($toDir, $item);
00611                     if (is_file($from)) {
00612                         if (copy($from, $to)) {
00613                             chmod($to, intval($mode, 8));
00614                             touch($to, filemtime($from));
00615                             $this->__messages[] = sprintf(__('%s copied to %s', true), $from, $to);
00616                         } else {
00617                             $this->__errors[] = sprintf(__('%s NOT copied to %s', true), $from, $to);
00618                         }
00619                     }
00620 
00621                     if (is_dir($from) && !file_exists($to)) {
00622                         if (mkdir($to, intval($mode, 8))) {
00623                             chmod($to, intval($mode, 8));
00624                             $this->__messages[] = sprintf(__('%s created', true), $to);
00625                             $options = array_merge($options, array('to'=> $to, 'from'=> $from));
00626                             $this->copy($options);
00627                         } else {
00628                             $this->__errors[] = sprintf(__('%s not created', true), $to);
00629                         }
00630                     }
00631                 }
00632             }
00633             closedir($handle);
00634         } else {
00635             return false;
00636         }
00637 
00638         if (!empty($this->__errors)) {
00639             return false;
00640         }
00641         return true;
00642     }
00643 /**
00644  * Recursive directory move.
00645  *
00646  * @param array $options (to, from, chmod, skip)
00647  * @return boolean Success
00648  * @access public
00649  */
00650     function move($options) {
00651         $to = null;
00652         if (is_string($options)) {
00653             $to = $options;
00654             $options = (array)$options;
00655         }
00656         $options = array_merge(array('to'=> $to, 'from'=> $this->path, 'mode'=> $this->mode, 'skip'=> array()), $options);
00657 
00658         if ($this->copy($options)) {
00659             if ($this->delete($options['from'])) {
00660                 return $this->cd($options['to']);
00661             }
00662         }
00663         return false;
00664     }
00665 /**
00666  * get messages from latest method
00667  *
00668  * @return array
00669  * @access public
00670  */
00671     function messages() {
00672         return $this->__messages;
00673     }
00674 /**
00675  * get error from latest method
00676  *
00677  * @return array
00678  * @access public
00679  */
00680     function errors() {
00681         return $this->__errors;
00682     }
00683 /**
00684  * nix flavored alias
00685  *
00686  * @see read
00687  * @access public
00688  */
00689     function ls($sort = true, $exceptions = false) {
00690         return $this->read($sort, $exceptions);
00691     }
00692 /**
00693  * nix flavored alias
00694  *
00695  * @see create
00696  * @access public
00697  */
00698     function mkdir($pathname, $mode = 0755) {
00699         return $this->create($pathname, $mode);
00700     }
00701 /**
00702  * nix flavored alias
00703  *
00704  * @see copy
00705  * @access public
00706  */
00707     function cp($options) {
00708         return $this->copy($options);
00709     }
00710 /**
00711  * nix flavored alias
00712  *
00713  * @see move
00714  * @access public
00715  */
00716     function mv($options) {
00717         return $this->move($options);
00718     }
00719 /**
00720  * nix flavored alias
00721  *
00722  * @see delete
00723  * @access public
00724  */
00725     function rm($path) {
00726         return $this->delete($path);
00727     }
00728 /**
00729  * Get the real path (taking ".." and such into account)
00730  *
00731  * @param string $path Path to resolve
00732  * @return string The resolved path
00733  */
00734     function realpath($path) {
00735         $path = str_replace('/', DS, trim($path));
00736         if (strpos($path, '..') === false) {
00737             if (!$this->isAbsolute($path)) {
00738                 $path = $this->addPathElement($this->path, $path);
00739             }
00740             return $path;
00741         }
00742         $parts = explode(DS, $path);
00743         $newparts = array();
00744         $newpath = ife($path[0] == DS, DS, '');
00745 
00746         while (($part = array_shift($parts)) !== NULL) {
00747             if ($part == '.' || $part == '') {
00748                 continue;
00749             }
00750             if ($part == '..') {
00751                 if (count($newparts) > 0) {
00752                     array_pop($newparts);
00753                     continue;
00754                 } else {
00755                     return false;
00756                 }
00757             }
00758             $newparts[] = $part;
00759         }
00760         $newpath .= implode(DS, $newparts);
00761 
00762         if (strlen($path > 1) && $path[strlen($path)-1] == DS) {
00763             $newpath .= DS;
00764         }
00765         return $newpath;
00766     }
00767 /**
00768  * Returns true if given $path ends in a slash (i.e. is slash-terminated).
00769  *
00770  * @param string $path Path to check
00771  * @return boolean true if path ends with slash, false otherwise
00772  * @access public
00773  * @static
00774  */
00775     function isSlashTerm($path) {
00776         if (preg_match('/[\/\\\]$/', $path)) {
00777             return true;
00778         }
00779         return false;
00780     }
00781 }
00782 ?>