3  * File/Directory manipulation
 
   9  * @author     Tomas V.V.Cox <cox@idecnet.com>
 
  10  * @copyright  1997-2009 The Authors
 
  11  * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 
  12  * @link       http://pear.php.net/package/PEAR
 
  13  * @since      File available since Release 0.1
 
  19 require_once 'PEAR.php';
 
  20 require_once 'Console/Getopt.php';
 
  22 $GLOBALS['_System_temp_files'] = array();
 
  25 * System offers cross plattform compatible system functions
 
  27 * Static functions for different operations. Should work under
 
  28 * Unix and Windows. The names and usage has been taken from its respectively
 
  29 * GNU commands. The functions will return (bool) false on error and will
 
  30 * trigger the error with the PHP trigger_error() function (you can silence
 
  31 * the error by prefixing a '@' sign after the function call, but this
 
  32 * is not recommended practice.  Instead use an error handler with
 
  33 * {@link set_error_handler()}).
 
  35 * Documentation on this class you can find in:
 
  36 * http://pear.php.net/manual/
 
  39 * if (!@System::rm('-r file1 dir1')) {
 
  40 *    print "could not delete file1 or dir1";
 
  43 * In case you need to to pass file names with spaces,
 
  44 * pass the params as an array:
 
  46 * System::rm(array('-r', $file1, $dir1));
 
  50 * @author     Tomas V.V. Cox <cox@idecnet.com>
 
  51 * @copyright  1997-2006 The PHP Group
 
  52 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 
  53 * @version    Release: 1.10.1
 
  54 * @link       http://pear.php.net/package/PEAR
 
  55 * @since      Class available since Release 0.1
 
  61      * returns the commandline arguments of a function
 
  63      * @param    string  $argv           the commandline
 
  64      * @param    string  $short_options  the allowed option short-tags
 
  65      * @param    string  $long_options   the allowed option long-tags
 
  66      * @return   array   the given options and there values
 
  68     public static function _parseArgs($argv, $short_options, $long_options = null)
 
  70         if (!is_array($argv) && $argv !== null) {
 
  72             // Quote all items that are a short option
 
  73             $av = preg_split('/(\A| )--?[a-z0-9]+[ =]?((?<!\\\\)((,\s*)|((?<!,)\s+))?)/i', $argv, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_OFFSET_CAPTURE);
 
  77                 if ($b{0} == '"' || $b{0} == "'") {
 
  81                 $escape = escapeshellarg($b);
 
  82                 $pos = $a[1] + $offset;
 
  83                 $argv = substr_replace($argv, $escape, $pos, strlen($b));
 
  88             // Find all items, quoted or otherwise
 
  89             preg_match_all("/(?:[\"'])(.*?)(?:['\"])|([^\s]+)/", $argv, $av);
 
  91             foreach ($av[2] as $k => $a) {
 
  95                 $argv[$k] = trim($a) ;
 
  99         return Console_Getopt::getopt2($argv, $short_options, $long_options);
 
 103      * Output errors with PHP trigger_error(). You can silence the errors
 
 104      * with prefixing a "@" sign to the function call: @System::mkdir(..);
 
 106      * @param mixed $error a PEAR error or a string with the error message
 
 109     protected static function raiseError($error)
 
 111         if (PEAR::isError($error)) {
 
 112             $error = $error->getMessage();
 
 114         trigger_error($error, E_USER_WARNING);
 
 119      * Creates a nested array representing the structure of a directory
 
 121      * System::_dirToStruct('dir1', 0) =>
 
 135      * @param    string  $sPath      Name of the directory
 
 136      * @param    integer $maxinst    max. deep of the lookup
 
 137      * @param    integer $aktinst    starting deep of the lookup
 
 138      * @param    bool    $silent     if true, do not emit errors.
 
 139      * @return   array   the structure of the dir
 
 141     protected static function _dirToStruct($sPath, $maxinst, $aktinst = 0, $silent = false)
 
 143         $struct = array('dirs' => array(), 'files' => array());
 
 144         if (($dir = @opendir($sPath)) === false) {
 
 146                 System::raiseError("Could not open dir $sPath");
 
 148             return $struct; // XXX could not open error
 
 151         $struct['dirs'][] = $sPath = realpath($sPath); // XXX don't add if '.' or '..' ?
 
 153         while (false !== ($file = readdir($dir))) {
 
 154             if ($file != '.' && $file != '..') {
 
 161         if ($aktinst < $maxinst || $maxinst == 0) {
 
 162             foreach ($list as $val) {
 
 163                 $path = $sPath . DIRECTORY_SEPARATOR . $val;
 
 164                 if (is_dir($path) && !is_link($path)) {
 
 165                     $tmp    = System::_dirToStruct($path, $maxinst, $aktinst+1, $silent);
 
 166                     $struct = array_merge_recursive($struct, $tmp);
 
 168                     $struct['files'][] = $path;
 
 177      * Creates a nested array representing the structure of a directory and files
 
 179      * @param    array $files Array listing files and dirs
 
 182      * @see System::_dirToStruct()
 
 184     protected static function _multipleToStruct($files)
 
 186         $struct = array('dirs' => array(), 'files' => array());
 
 187         settype($files, 'array');
 
 188         foreach ($files as $file) {
 
 189             if (is_dir($file) && !is_link($file)) {
 
 190                 $tmp    = System::_dirToStruct($file, 0);
 
 191                 $struct = array_merge_recursive($tmp, $struct);
 
 193                 if (!in_array($file, $struct['files'])) {
 
 194                     $struct['files'][] = $file;
 
 202      * The rm command for removing files.
 
 203      * Supports multiple files and dirs and also recursive deletes
 
 205      * @param    string  $args   the arguments for rm
 
 206      * @return   mixed   PEAR_Error or true for success
 
 210     public static function rm($args)
 
 212         $opts = System::_parseArgs($args, 'rf'); // "f" does nothing but I like it :-)
 
 213         if (PEAR::isError($opts)) {
 
 214             return System::raiseError($opts);
 
 216         foreach ($opts[0] as $opt) {
 
 217             if ($opt[0] == 'r') {
 
 218                 $do_recursive = true;
 
 222         if (isset($do_recursive)) {
 
 223             $struct = System::_multipleToStruct($opts[1]);
 
 224             foreach ($struct['files'] as $file) {
 
 225                 if (!@unlink($file)) {
 
 230             rsort($struct['dirs']);
 
 231             foreach ($struct['dirs'] as $dir) {
 
 237             foreach ($opts[1] as $file) {
 
 238                 $delete = (is_dir($file)) ? 'rmdir' : 'unlink';
 
 239                 if (!@$delete($file)) {
 
 250      * The -p option will create parent directories
 
 251      * @param    string  $args    the name of the director(y|ies) to create
 
 252      * @return   bool    True for success
 
 254     public static function mkDir($args)
 
 256         $opts = System::_parseArgs($args, 'pm:');
 
 257         if (PEAR::isError($opts)) {
 
 258             return System::raiseError($opts);
 
 261         $mode = 0777; // default mode
 
 262         foreach ($opts[0] as $opt) {
 
 263             if ($opt[0] == 'p') {
 
 264                 $create_parents = true;
 
 265             } elseif ($opt[0] == 'm') {
 
 266                 // if the mode is clearly an octal number (starts with 0)
 
 267                 // convert it to decimal
 
 268                 if (strlen($opt[1]) && $opt[1]{0} == '0') {
 
 269                     $opt[1] = octdec($opt[1]);
 
 279         if (isset($create_parents)) {
 
 280             foreach ($opts[1] as $dir) {
 
 282                 while ((!file_exists($dir) || !is_dir($dir)) &&
 
 283                         $dir != DIRECTORY_SEPARATOR) {
 
 284                     array_unshift($dirstack, $dir);
 
 285                     $dir = dirname($dir);
 
 288                 while ($newdir = array_shift($dirstack)) {
 
 289                     if (!is_writeable(dirname($newdir))) {
 
 294                     if (!mkdir($newdir, $mode)) {
 
 300             foreach($opts[1] as $dir) {
 
 301                 if ((@file_exists($dir) || !is_dir($dir)) && !mkdir($dir, $mode)) {
 
 314      * 1) $var = System::cat('sample.txt test.txt');
 
 315      * 2) System::cat('sample.txt test.txt > final.txt');
 
 316      * 3) System::cat('sample.txt test.txt >> final.txt');
 
 318      * Note: as the class use fopen, urls should work also (test that)
 
 320      * @param    string  $args   the arguments
 
 321      * @return   boolean true on success
 
 323     public static function &cat($args)
 
 327         if (!is_array($args)) {
 
 328             $args = preg_split('/\s+/', $args, -1, PREG_SPLIT_NO_EMPTY);
 
 331         $count_args = count($args);
 
 332         for ($i = 0; $i < $count_args; $i++) {
 
 333             if ($args[$i] == '>') {
 
 335                 $outputfile = $args[$i+1];
 
 337             } elseif ($args[$i] == '>>') {
 
 339                 $outputfile = $args[$i+1];
 
 342                 $files[] = $args[$i];
 
 347             if (!$outputfd = fopen($outputfile, $mode)) {
 
 348                 $err = System::raiseError("Could not open $outputfile");
 
 353         foreach ($files as $file) {
 
 354             if (!$fd = fopen($file, 'r')) {
 
 355                 System::raiseError("Could not open $file");
 
 358             while ($cont = fread($fd, 2048)) {
 
 359                 if (is_resource($outputfd)) {
 
 360                     fwrite($outputfd, $cont);
 
 367         if (is_resource($outputfd)) {
 
 374      * Creates temporary files or directories. This function will remove
 
 375      * the created files when the scripts finish its execution.
 
 378      *   1) $tempfile = System::mktemp("prefix");
 
 379      *   2) $tempdir  = System::mktemp("-d prefix");
 
 380      *   3) $tempfile = System::mktemp();
 
 381      *   4) $tempfile = System::mktemp("-t /var/tmp prefix");
 
 383      * prefix -> The string that will be prepended to the temp name
 
 384      *           (defaults to "tmp").
 
 385      * -d     -> A temporary dir will be created instead of a file.
 
 386      * -t     -> The target dir where the temporary (file|dir) will be created. If
 
 387      *           this param is missing by default the env vars TMP on Windows or
 
 388      *           TMPDIR in Unix will be used. If these vars are also missing
 
 389      *           c:\windows\temp or /tmp will be used.
 
 391      * @param   string  $args  The arguments
 
 392      * @return  mixed   the full path of the created (file|dir) or false
 
 393      * @see System::tmpdir()
 
 395     public static function mktemp($args = null)
 
 397         static $first_time = true;
 
 398         $opts = System::_parseArgs($args, 't:d');
 
 399         if (PEAR::isError($opts)) {
 
 400             return System::raiseError($opts);
 
 403         foreach ($opts[0] as $opt) {
 
 404             if ($opt[0] == 'd') {
 
 406             } elseif ($opt[0] == 't') {
 
 411         $prefix = (isset($opts[1][0])) ? $opts[1][0] : 'tmp';
 
 412         if (!isset($tmpdir)) {
 
 413             $tmpdir = System::tmpdir();
 
 416         if (!System::mkDir(array('-p', $tmpdir))) {
 
 420         $tmp = tempnam($tmpdir, $prefix);
 
 421         if (isset($tmp_is_dir)) {
 
 422             unlink($tmp); // be careful possible race condition here
 
 423             if (!mkdir($tmp, 0700)) {
 
 424                 return System::raiseError("Unable to create temporary directory $tmpdir");
 
 428         $GLOBALS['_System_temp_files'][] = $tmp;
 
 429         if (isset($tmp_is_dir)) {
 
 430             //$GLOBALS['_System_temp_files'][] = dirname($tmp);
 
 434             PEAR::registerShutdownFunc(array('System', '_removeTmpFiles'));
 
 442      * Remove temporary files created my mkTemp. This function is executed
 
 443      * at script shutdown time
 
 445     public static function _removeTmpFiles()
 
 447         if (count($GLOBALS['_System_temp_files'])) {
 
 448             $delete = $GLOBALS['_System_temp_files'];
 
 449             array_unshift($delete, '-r');
 
 451             $GLOBALS['_System_temp_files'] = array();
 
 456      * Get the path of the temporal directory set in the system
 
 457      * by looking in its environments variables.
 
 458      * Note: php.ini-recommended removes the "E" from the variables_order setting,
 
 459      * making unavaible the $_ENV array, that s why we do tests with _ENV
 
 461      * @return string The temporary directory on the system
 
 463     public static function tmpdir()
 
 466             if ($var = isset($_ENV['TMP']) ? $_ENV['TMP'] : getenv('TMP')) {
 
 469             if ($var = isset($_ENV['TEMP']) ? $_ENV['TEMP'] : getenv('TEMP')) {
 
 472             if ($var = isset($_ENV['USERPROFILE']) ? $_ENV['USERPROFILE'] : getenv('USERPROFILE')) {
 
 475             if ($var = isset($_ENV['windir']) ? $_ENV['windir'] : getenv('windir')) {
 
 478             return getenv('SystemRoot') . '\temp';
 
 480         if ($var = isset($_ENV['TMPDIR']) ? $_ENV['TMPDIR'] : getenv('TMPDIR')) {
 
 483         return realpath('/tmp');
 
 487      * The "which" command (show the full path of a command)
 
 489      * @param string $program The command to search for
 
 490      * @param mixed  $fallback Value to return if $program is not found
 
 492      * @return mixed A string with the full path or false if not found
 
 493      * @author Stig Bakken <ssb@php.net>
 
 495     public static function which($program, $fallback = false)
 
 498         if (!is_string($program) || '' == $program) {
 
 503         if (basename($program) != $program) {
 
 504             $path_elements[] = dirname($program);
 
 505             $program = basename($program);
 
 507             $path = getenv('PATH');
 
 509                 $path = getenv('Path'); // some OSes are just stupid enough to do this
 
 512             $path_elements = explode(PATH_SEPARATOR, $path);
 
 516             $exe_suffixes = getenv('PATHEXT')
 
 517                                 ? explode(PATH_SEPARATOR, getenv('PATHEXT'))
 
 518                                 : array('.exe','.bat','.cmd','.com');
 
 519             // allow passing a command.exe param
 
 520             if (strpos($program, '.') !== false) {
 
 521                 array_unshift($exe_suffixes, '');
 
 524             $exe_suffixes = array('');
 
 527         foreach ($exe_suffixes as $suff) {
 
 528             foreach ($path_elements as $dir) {
 
 529                 $file = $dir . DIRECTORY_SEPARATOR . $program . $suff;
 
 530                 if (is_executable($file)) {
 
 543      * System::find($dir);
 
 544      * System::find("$dir -type d");
 
 545      * System::find("$dir -type f");
 
 546      * System::find("$dir -name *.php");
 
 547      * System::find("$dir -name *.php -name *.htm*");
 
 548      * System::find("$dir -maxdepth 1");
 
 551      * $dir            -> Start the search at this directory
 
 552      * -type d         -> return only directories
 
 553      * -type f         -> return only files
 
 554      * -maxdepth <n>   -> max depth of recursion
 
 555      * -name <pattern> -> search pattern (bash style). Multiple -name param allowed
 
 557      * @param  mixed Either array or string with the command line
 
 558      * @return array Array of found files
 
 560     public static function find($args)
 
 562         if (!is_array($args)) {
 
 563             $args = preg_split('/\s+/', $args, -1, PREG_SPLIT_NO_EMPTY);
 
 565         $dir = realpath(array_shift($args));
 
 571         $do_files = $do_dirs = true;
 
 572         $args_count = count($args);
 
 573         for ($i = 0; $i < $args_count; $i++) {
 
 576                     if (in_array($args[$i+1], array('d', 'f'))) {
 
 577                         if ($args[$i+1] == 'd') {
 
 586                     $name = preg_quote($args[$i+1], '#');
 
 587                     // our magic characters ? and * have just been escaped,
 
 588                     // so now we change the escaped versions to PCRE operators
 
 589                     $name = strtr($name, array('\?' => '.', '\*' => '.*'));
 
 590                     $patterns[] = '('.$name.')';
 
 594                     $depth = $args[$i+1];
 
 598         $path = System::_dirToStruct($dir, $depth, 0, true);
 
 599         if ($do_files && $do_dirs) {
 
 600             $files = array_merge($path['files'], $path['dirs']);
 
 601         } elseif ($do_dirs) {
 
 602             $files = $path['dirs'];
 
 604             $files = $path['files'];
 
 606         if (count($patterns)) {
 
 607             $dsq = preg_quote(DIRECTORY_SEPARATOR, '#');
 
 608             $pattern = '#(^|'.$dsq.')'.implode('|', $patterns).'($|'.$dsq.')#';
 
 610             $files_count = count($files);
 
 611             for ($i = 0; $i < $files_count; $i++) {
 
 612                 // only search in the part of the file below the current directory
 
 613                 $filepart = basename($files[$i]);
 
 614                 if (preg_match($pattern, $filepart)) {