File
[ class tree: File ] [ index: File ] [ all elements ]

Source for file Find.php

Documentation is available at Find.php

  1. <?php
  2. //
  3. // +----------------------------------------------------------------------+
  4. // | PHP Version 4                                                        |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1997-2005 The PHP Group                                |
  7. // +----------------------------------------------------------------------+
  8. // | This source file is subject to version 2.02 of the PHP license,      |
  9. // | that is bundled with this package in the file LICENSE, and is        |
  10. // | available at through the world-wide-web at                           |
  11. // | http://www.php.net/license/2_02.txt.                                 |
  12. // | If you did not receive a copy of the PHP license and are unable to   |
  13. // | obtain it through the world-wide-web, please send a note to          |
  14. // | license@php.net so we can mail you a copy immediately.               |
  15. // +----------------------------------------------------------------------+
  16. // | Author: Sterling Hughes <sterling@php.net>                           |
  17. // +----------------------------------------------------------------------+
  18. //
  19. // $Id: Find.php,v 1.21 2005/09/20 11:33:15 techtonik Exp $
  20. //
  21.  
  22. require_once 'PEAR.php';
  23.  
  24. define('FILE_FIND_VERSION''@package_version@');
  25.  
  26.  
  27. /**
  28. *  Commonly needed functions searching directory trees
  29. *
  30. @access public
  31. @version $Id: Find.php,v 1.21 2005/09/20 11:33:15 techtonik Exp $
  32. @package File
  33. @author Sterling Hughes <sterling@php.net>
  34. */
  35. class File_Find
  36. {
  37.     /**
  38.      * internal dir-list
  39.      * @var array 
  40.      */
  41.     var $_dirs = array();
  42.  
  43.     /**
  44.      * found files
  45.      * @var array 
  46.      */
  47.     var $files = array();
  48.  
  49.     /**
  50.      * found dirs
  51.      * @var array 
  52.      */
  53.     var $directories = array();
  54.  
  55.     /**
  56.      * Search the current directory to find matches for the
  57.      * the specified pattern.
  58.      *
  59.      * @param string $pattern a string containing the pattern to search
  60.      *  the directory for.
  61.      *
  62.      * @param string $dirpath a string containing the directory path
  63.      *  to search.
  64.      *
  65.      * @param string $pattern_type a string containing the type of
  66.      *  pattern matching functions to use (can either be 'php' or
  67.      *  'perl').
  68.      *
  69.      * @return array containing all of the files and directories
  70.      *  matching the pattern or null if no matches
  71.      *
  72.      * @author Sterling Hughes <sterling@php.net>
  73.      * @access public
  74.      * @static
  75.      */
  76.     function &glob($pattern$dirpath$pattern_type 'php')
  77.     {
  78.         $dh @opendir($dirpath);
  79.  
  80.         if (!$dh{
  81.             $pe = PEAR::raiseError("Cannot open directory");
  82.             return $pe;
  83.         }
  84.  
  85.         $match_function File_Find::_determineRegex($pattern$pattern_type);
  86.         $matches = array();
  87.         while (false !== ($entry @readdir($dh))) {
  88.             if ($match_function($pattern$entry&&
  89.                 $entry != '.' && $entry != '..'{
  90.                 $matches[$entry;
  91.             }
  92.         }
  93.  
  94.         @closedir($dh);
  95.  
  96.         return (count($matches> 0$matches : null;
  97.     }
  98.  
  99.     /**
  100.      * Map the directory tree given by the directory_path parameter.
  101.      *
  102.      * @param string $directory contains the directory path that you
  103.      *  want to map.
  104.      *
  105.      * @return array a two element array, the first element containing a list
  106.      *  of all the directories, the second element containing a list of all the
  107.      *  files.
  108.      *
  109.      * @author Sterling Hughes <sterling@php.net>
  110.      * @access public
  111.      */
  112.     function &maptree($directory)
  113.     {
  114.  
  115.         /* if called statically */
  116.         if (!isset($this)  || !is_a($this"File_Find")) {
  117.             $obj &new File_Find();
  118.             return $obj->maptree($directory);
  119.         }
  120.       
  121.         /* clear the results just in case */
  122.         $this->files       = array();
  123.         $this->directories = array();
  124.  
  125.         /* consistency rules - strip out trailing slashes */
  126.         $directory preg_replace('![\\\\/]+$!'''$directory);
  127.         /* use only native system directory delimiters */
  128.         $directory preg_replace("![\\\\/]+!"DIRECTORY_SEPARATOR$directory);
  129.  
  130.         $this->_dirs = array($directory);
  131.  
  132.         while (count($this->_dirs)) {
  133.             $dir array_pop($this->_dirs);
  134.             File_Find::_build($dir);
  135.             array_push($this->directories$dir);
  136.         }
  137.  
  138.         return array($this->directories$this->files);
  139.     }
  140.  
  141.     /**
  142.      * Map the directory tree given by the directory parameter.
  143.      *
  144.      * @param string $directory contains the directory path that you
  145.      *  want to map.
  146.      * @param integer $maxrecursion maximun number of folders to recursive
  147.      *  map
  148.      *
  149.      * @return array a multidimensional array containing all subdirectories
  150.      *  and their files. For example:
  151.      *
  152.      *  Array
  153.      *  (
  154.      *     [0] => file_1.php
  155.      *     [1] => file_2.php
  156.      *     [subdirname] => Array
  157.      *        (
  158.      *           [0] => file_1.php
  159.      *        )
  160.      *  )
  161.      *
  162.      * @author Mika Tuupola <tuupola@appelsiini.net>
  163.      * @access public
  164.      * @static
  165.      */
  166.     function &mapTreeMultiple($directory$maxrecursion = 0$count = 0)
  167.     {   
  168.         $retval = array();
  169.  
  170.         $count++;
  171.  
  172.         $directory .= DIRECTORY_SEPARATOR;
  173.         $dh opendir($directory);
  174.         while (false !== ($entry @readdir($dh))) {
  175.             if ($entry != '.' && $entry != '..'{
  176.                  array_push($retval$entry);
  177.             }
  178.         }
  179.  
  180.         closedir($dh);
  181.      
  182.         while (list($key$valeach($retval)) {
  183.             $path $directory $val;
  184.             $path str_replace(DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR,
  185.                                 DIRECTORY_SEPARATOR$path);
  186.       
  187.             if (!is_array($val&& is_dir($path)) {
  188.                 unset($retval[$key]);
  189.                 if ($maxrecursion == 0 || $count $maxrecursion{
  190.                     $retval[$val&File_Find::mapTreeMultiple($path
  191.                                     $maxrecursion$count);
  192.                 }
  193.             }
  194.         }
  195.  
  196.         return $retval;
  197.     }
  198.  
  199.     /**
  200.      * Search the specified directory tree with the specified pattern.  Return
  201.      * an array containing all matching files (no directories included).
  202.      *
  203.      * @param string $pattern the pattern to match every file with.
  204.      *
  205.      * @param string $directory the directory tree to search in.
  206.      *
  207.      * @param string $type the type of regular expression support to use, either
  208.      *  'php' or 'perl'.
  209.      *
  210.      * @param bool $fullpath whether the regex should be matched against the
  211.      *  full path or only against the filename
  212.      *
  213.      * @param string $match can be either 'files', 'dirs' or 'both' to specify
  214.      *  the kind of list to return
  215.      *
  216.      * @return array a list of files matching the pattern parameter in the the
  217.      *  directory path specified by the directory parameter
  218.      *
  219.      * @author Sterling Hughes <sterling@php.net>
  220.      * @access public
  221.      * @static
  222.      */
  223.     function &search($pattern$directory$type 'php'$fullpath = true$match 'files')
  224.     {
  225.  
  226.         $matches = array();
  227.         list ($directories,$files)  File_Find::maptree($directory);
  228.         switch($match{
  229.             case 'directories'$data $directories; break;
  230.             case 'both'$data array_merge($directories$files); break;
  231.             case 'files':
  232.             default:
  233.                 $data $files;
  234.         }
  235.         unset($files$directories);
  236.  
  237.         $match_function File_Find::_determineRegex($pattern$type);
  238.  
  239.         reset($data);
  240.         while (list(,$entryeach($data)) {
  241.             if ($match_function($pattern
  242.                                 $fullpath $entry basename($entry))) {
  243.                 $matches[$entry;
  244.             }
  245.         }
  246.  
  247.         return ($matches);
  248.     }
  249.  
  250.     /**
  251.      * Determine whether or not a variable is a PEAR error
  252.      *
  253.      * @param object PEAR_Error $var the variable to test.
  254.      *
  255.      * @return boolean returns true if the variable is a PEAR error, otherwise
  256.      *  it returns false.
  257.      * @access public
  258.      */
  259.     function isError(&$var)
  260.     {
  261.         return PEAR::isError($var);
  262.     }
  263.  
  264.     /**
  265.      * internal function to build singular directory trees, used by
  266.      * File_Find::maptree()
  267.      *
  268.      * @param string $directory name of the directory to read
  269.      * @return void 
  270.      */
  271.     function _build($directory)
  272.     {
  273.  
  274.         $dh @opendir($directory);
  275.  
  276.         if (!$dh{
  277.             $pe = PEAR::raiseError("Cannot open directory");
  278.             return $pe;
  279.         }
  280.  
  281.         while (false !== ($entry @readdir($dh))) {
  282.             if ($entry != '.' && $entry != '..'{
  283.  
  284.                 $entry $directory.DIRECTORY_SEPARATOR.$entry;
  285.                 $entry str_replace(DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR,
  286.                                      DIRECTORY_SEPARATOR$entry);
  287.  
  288.                 if (is_dir($entry)) {
  289.                     array_push($this->_dirs$entry);
  290.                 else {
  291.                     array_push($this->files$entry);
  292.                 }
  293.             }
  294.         }
  295.  
  296.         @closedir($dh);
  297.     }
  298.  
  299.     /**
  300.      * internal function to determine the type of regular expression to
  301.      * use, implemented by File_Find::glob() and File_Find::search()
  302.      *
  303.      * @param string $type given RegExp type
  304.      * @return string kind of function ( "eregi", "ereg" or "preg_match") ;
  305.      *
  306.      */
  307.     function _determineRegex($pattern$type)
  308.     {
  309.         if (!strcasecmp($type'shell')) {
  310.             $match_function 'File_Find_match_shell';
  311.         else if (!strcasecmp($type'perl')) {
  312.             $match_function 'preg_match';
  313.         else if (!strcasecmp(substr($pattern-2)'/i')) {
  314.             $match_function 'eregi';
  315.         else {
  316.             $match_function 'ereg';
  317.         }
  318.         return $match_function;
  319.     }
  320.  
  321. }
  322.  
  323. /**
  324. * Package method to match via 'shell' pattern. Provided in global
  325. * scope, because they should be called like 'preg_match' and 'eregi'
  326. * and can be easily copied into other packages
  327. *
  328. @author techtonik <techtonik@php.net>
  329. @return mixed bool on success and PEAR_Error on failure
  330. */ 
  331. function File_Find_match_shell($pattern$filename)
  332. {
  333.     // {{{ convert pattern to positive and negative regexps
  334.         $positive $pattern;
  335.         $negation substr_count($pattern"|");
  336.  
  337.         if ($negation > 1{
  338.             return PEAR::raiseError("Mask string contains errors!");
  339.         elseif ($negation{
  340.             list($positive$negativeexplode("|"$pattern);
  341.             if (strlen($negation== 0{
  342.                 return PEAR::raiseError("Mask string contains errors!");
  343.             }
  344.         }
  345.  
  346.        $positive _File_Find_match_shell_get_pattern($positive);
  347.        if ($negation{
  348.            $negative _File_Find_match_shell_get_pattern($negative);
  349.        }
  350.     // }}} convert end 
  351.  
  352.  
  353.     if (defined("FILE_FIND_DEBUG")) {
  354.         print("Method: $type\nPattern: $pattern\n Converted pattern:");
  355.         print_r($positive);
  356.         if (isset($negative)) print_r($negative);
  357.     }
  358.  
  359.     if (!preg_match($positive$filename)) {
  360.         return FALSE;
  361.     else {
  362.         if (isset($negative
  363.               && preg_match($negative$filename)) {
  364.             return FALSE;
  365.         else {
  366.             return TRUE;
  367.         }
  368.     }
  369. }
  370.  
  371. /**
  372. * function used by File_Find_match_shell to convert 'shell' mask
  373. * into pcre regexp. Some of the rules (see testcases for more):
  374. *  escaping all special chars and replacing
  375. *    . with \.
  376. *    * with .*
  377. *    ? with .{1}
  378. *    also adding ^ and $ as the pattern matches whole filename
  379. *
  380. @author techtonik <techtonik@php.net>
  381. @return string pcre regexp for preg_match
  382. */ 
  383.     // get array of several masks (if any) delimited by comma
  384.     // do not touch commas in char class
  385.     $premasks preg_split("|(\[[^\]]+\])|"$mask-1PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
  386.     if (defined("FILE_FIND_DEBUG")) {
  387.         print("\nPremask: ");
  388.         print_r($premasks);
  389.     }
  390.     $pi = 0;
  391.     foreach($premasks as $pm{
  392.         if (!isset($masks[$pi])) $masks[$pi"";
  393.         if ($pm{0== '[' && $pm{strlen($pm)-1== ']'{
  394.             // strip commas from character class
  395.             $masks[$pi.= str_replace(","""$pm);
  396.         else {
  397.             $tarr explode(","$pm);
  398.             if (sizeof($tarr== 1{
  399.                 $masks[$pi.= $pm;
  400.             else {
  401.                 foreach ($tarr as $te{
  402.                     $masks[$pi++.= $te;
  403.                     $masks[$pi"";
  404.                 }
  405.                 unset($masks[$pi--]);
  406.             }
  407.         }
  408.     }
  409.  
  410.     // convert to preg regexp
  411.     $regexmask implode("|"$masks);
  412.     if (defined("FILE_FIND_DEBUG")) {
  413.         print("regexMask step one(implode): $regexmask");
  414.     }
  415.     $regexmask addcslashes($regexmask'^$}{)(\/.+');
  416.     if (defined("FILE_FIND_DEBUG")) {
  417.         print("\nregexMask step two(addcslashes): $regexmask");
  418.     }
  419.     $regexmask preg_replace("!(\*|\?)!"".$1"$regexmask);
  420.     if (defined("FILE_FIND_DEBUG")) {
  421.         print("\nregexMask step three(*,? -> .*,.?): $regexmask");
  422.     }
  423.     // if no extension supplied - add .* to match partially from filename start
  424.     if (strpos($regexmask"\\."=== FALSE$regexmask .= ".*";
  425.     // file mask match whole name - adding restrictions
  426.     $regexmask preg_replace("!(\|)!"'^'."$1".'$'$regexmask);
  427.     $regexmask '^'.$regexmask.'$';
  428.     if (defined("FILE_FIND_DEBUG")) {
  429.         print("\nregexMask step three(^ and $ to match whole name): $regexmask");
  430.     }
  431.     // wrap regex into + since all + are already escaped
  432.     $regexmask = "+$regexmask+i";
  433.     if (defined("FILE_FIND_DEBUG")) {
  434.         print("\nWrapped regex: $regexmask\n");
  435.     }
  436.     return $regexmask;
  437. }
  438.  
  439. /*
  440.  * Local variables:
  441.  * tab-width: 4
  442.  * c-basic-offset: 4
  443.  * End:
  444.  */
  445.  
  446. ?>

Documentation generated on Mon, 11 Mar 2019 14:13:34 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.