]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - extlib/System.php
Update PEAR to v1.10.9 and patch it so it works quietly
[quix0rs-gnu-social.git] / extlib / System.php
1 <?php
2 /**
3  * File/Directory manipulation
4  *
5  * PHP versions 4 and 5
6  *
7  * @category   pear
8  * @package    System
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
14  */
15
16 /**
17  * base class
18  */
19 require_once 'PEAR.php';
20 require_once 'Console/Getopt.php';
21
22 $GLOBALS['_System_temp_files'] = array();
23
24 /**
25  * System offers cross platform compatible system functions
26  *
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()}).
34  *
35  * Documentation on this class you can find in:
36  * http://pear.php.net/manual/
37  *
38  * Example usage:
39  * if (!@System::rm('-r file1 dir1')) {
40  *    print "could not delete file1 or dir1";
41  * }
42  *
43  * In case you need to to pass file names with spaces,
44  * pass the params as an array:
45  *
46  * System::rm(array('-r', $file1, $dir1));
47  *
48  * @category   pear
49  * @package    System
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: @package_version@
54  * @link       http://pear.php.net/package/PEAR
55  * @since      Class available since Release 0.1
56  * @static
57  */
58 class System
59 {
60     /**
61      * Concatenate files
62      *
63      * Usage:
64      * 1) $var = System::cat('sample.txt test.txt');
65      * 2) System::cat('sample.txt test.txt > final.txt');
66      * 3) System::cat('sample.txt test.txt >> final.txt');
67      *
68      * Note: as the class use fopen, urls should work also
69      *
70      * @param string $args the arguments
71      * @return   boolean true on success
72      */
73     public static function &cat($args)
74     {
75         $ret = null;
76         $files = array();
77         if (!is_array($args)) {
78             $args = preg_split('/\s+/', $args, -1, PREG_SPLIT_NO_EMPTY);
79         }
80
81         $count_args = count($args);
82         for ($i = 0; $i < $count_args; $i++) {
83             if ($args[$i] == '>') {
84                 $mode = 'wb';
85                 $outputfile = $args[$i + 1];
86                 break;
87             } elseif ($args[$i] == '>>') {
88                 $mode = 'ab+';
89                 $outputfile = $args[$i + 1];
90                 break;
91             } else {
92                 $files[] = $args[$i];
93             }
94         }
95         $outputfd = false;
96         if (isset($mode)) {
97             if (!$outputfd = fopen($outputfile, $mode)) {
98                 $err = System::raiseError("Could not open $outputfile");
99                 return $err;
100             }
101             $ret = true;
102         }
103         foreach ($files as $file) {
104             if (!$fd = fopen($file, 'r')) {
105                 System::raiseError("Could not open $file");
106                 continue;
107             }
108             while ($cont = fread($fd, 2048)) {
109                 if (is_resource($outputfd)) {
110                     fwrite($outputfd, $cont);
111                 } else {
112                     $ret .= $cont;
113                 }
114             }
115             fclose($fd);
116         }
117         if (is_resource($outputfd)) {
118             fclose($outputfd);
119         }
120         return $ret;
121     }
122
123     /**
124      * Output errors with PHP trigger_error(). You can silence the errors
125      * with prefixing a "@" sign to the function call: @System::mkdir(..);
126      *
127      * @param mixed $error a PEAR error or a string with the error message
128      * @return bool false
129      */
130     protected static function raiseError($error)
131     {
132         if (PEAR::isError($error)) {
133             $error = $error->getMessage();
134         }
135         trigger_error($error, E_USER_WARNING);
136         return false;
137     }
138
139     /**
140      * Creates temporary files or directories. This function will remove
141      * the created files when the scripts finish its execution.
142      *
143      * Usage:
144      *   1) $tempfile = System::mktemp("prefix");
145      *   2) $tempdir  = System::mktemp("-d prefix");
146      *   3) $tempfile = System::mktemp();
147      *   4) $tempfile = System::mktemp("-t /var/tmp prefix");
148      *
149      * prefix -> The string that will be prepended to the temp name
150      *           (defaults to "tmp").
151      * -d     -> A temporary dir will be created instead of a file.
152      * -t     -> The target dir where the temporary (file|dir) will be created. If
153      *           this param is missing by default the env vars TMP on Windows or
154      *           TMPDIR in Unix will be used. If these vars are also missing
155      *           c:\windows\temp or /tmp will be used.
156      *
157      * @param string $args The arguments
158      * @return  mixed   the full path of the created (file|dir) or false
159      * @see System::tmpdir()
160      */
161     public static function mktemp($args = null)
162     {
163         static $first_time = true;
164         $opts = System::_parseArgs($args, 't:d');
165         if (PEAR::isError($opts)) {
166             return System::raiseError($opts);
167         }
168
169         foreach ($opts[0] as $opt) {
170             if ($opt[0] == 'd') {
171                 $tmp_is_dir = true;
172             } elseif ($opt[0] == 't') {
173                 $tmpdir = $opt[1];
174             }
175         }
176
177         $prefix = (isset($opts[1][0])) ? $opts[1][0] : 'tmp';
178         if (!isset($tmpdir)) {
179             $tmpdir = System::tmpdir();
180         }
181
182         if (!System::mkDir(['-p', $tmpdir])) {
183             return false;
184         }
185
186         $tmp = tempnam($tmpdir, $prefix);
187         if (isset($tmp_is_dir)) {
188             unlink($tmp); // be careful possible race condition here
189             if (!mkdir($tmp, 0700)) {
190                 return System::raiseError("Unable to create temporary directory $tmpdir");
191             }
192         }
193
194         $GLOBALS['_System_temp_files'][] = $tmp;
195         /*if (isset($tmp_is_dir)) {
196             //$GLOBALS['_System_temp_files'][] = dirname($tmp);
197         }*/
198
199         if ($first_time) {
200             PEAR::registerShutdownFunc(array('System', '_removeTmpFiles'));
201             $first_time = false;
202         }
203
204         return $tmp;
205     }
206
207     /**
208      * returns the commandline arguments of a function
209      *
210      * @param string $argv the commandline
211      * @param string $short_options the allowed option short-tags
212      * @param string $long_options the allowed option long-tags
213      * @return   array   the given options and there values
214      */
215     public static function _parseArgs($argv, $short_options, $long_options = null)
216     {
217         if (!is_array($argv) && $argv !== null) {
218             /*
219             // Quote all items that are a short option
220             $av = preg_split('/(\A| )--?[a-z0-9]+[ =]?((?<!\\\\)((,\s*)|((?<!,)\s+))?)/i', $argv, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_OFFSET_CAPTURE);
221             $offset = 0;
222             foreach ($av as $a) {
223                 $b = trim($a[0]);
224                 if ($b{0} == '"' || $b{0} == "'") {
225                     continue;
226                 }
227
228                 $escape = escapeshellarg($b);
229                 $pos = $a[1] + $offset;
230                 $argv = substr_replace($argv, $escape, $pos, strlen($b));
231                 $offset += 2;
232             }
233             */
234
235             // Find all items, quoted or otherwise
236             preg_match_all("/(?:[\"'])(.*?)(?:['\"])|([^\s]+)/", $argv, $av);
237             $argv = $av[1];
238             foreach ($av[2] as $k => $a) {
239                 if (empty($a)) {
240                     continue;
241                 }
242                 $argv[$k] = trim($a);
243             }
244         }
245
246         return (new Console_Getopt)->getopt2($argv, $short_options, $long_options);
247     }
248
249     /**
250      * Get the path of the temporal directory set in the system
251      * by looking in its environments variables.
252      * Note: php.ini-recommended removes the "E" from the variables_order setting,
253      * making unavaible the $_ENV array, that s why we do tests with _ENV
254      *
255      * @return string The temporary directory on the system
256      */
257     public static function tmpdir()
258     {
259         if (OS_WINDOWS) {
260             if ($var = isset($_ENV['TMP']) ? $_ENV['TMP'] : getenv('TMP')) {
261                 return $var;
262             }
263             if ($var = isset($_ENV['TEMP']) ? $_ENV['TEMP'] : getenv('TEMP')) {
264                 return $var;
265             }
266             if ($var = isset($_ENV['USERPROFILE']) ? $_ENV['USERPROFILE'] : getenv('USERPROFILE')) {
267                 return $var;
268             }
269             if ($var = isset($_ENV['windir']) ? $_ENV['windir'] : getenv('windir')) {
270                 return $var;
271             }
272             return getenv('SystemRoot') . '\temp';
273         }
274         if ($var = isset($_ENV['TMPDIR']) ? $_ENV['TMPDIR'] : getenv('TMPDIR')) {
275             return $var;
276         }
277         return realpath('/tmp');
278     }
279
280     /**
281      * Make directories.
282      *
283      * The -p option will create parent directories
284      * @param string $args the name of the director(y|ies) to create
285      * @return   bool    True for success
286      */
287     public static function mkDir($args)
288     {
289         $opts = System::_parseArgs($args, 'pm:');
290         if (PEAR::isError($opts)) {
291             return System::raiseError($opts);
292         }
293
294         $mode = 0777; // default mode
295         foreach ($opts[0] as $opt) {
296             if ($opt[0] == 'p') {
297                 $create_parents = true;
298             } elseif ($opt[0] == 'm') {
299                 // if the mode is clearly an octal number (starts with 0)
300                 // convert it to decimal
301                 if (strlen($opt[1]) && $opt[1]{0} == '0') {
302                     $opt[1] = octdec($opt[1]);
303                 } else {
304                     // convert to int
305                     $opt[1] += 0;
306                 }
307                 $mode = $opt[1];
308             }
309         }
310
311         $ret = true;
312         if (isset($create_parents)) {
313             foreach ($opts[1] as $dir) {
314                 $dirstack = array();
315                 while ((!file_exists($dir) || !is_dir($dir)) &&
316                     $dir != DIRECTORY_SEPARATOR) {
317                     array_unshift($dirstack, $dir);
318                     $dir = dirname($dir);
319                 }
320
321                 while ($newdir = array_shift($dirstack)) {
322                     if (!is_writeable(dirname($newdir))) {
323                         $ret = false;
324                         break;
325                     }
326
327                     if (!mkdir($newdir, $mode)) {
328                         $ret = false;
329                     }
330                 }
331             }
332         } else {
333             foreach ($opts[1] as $dir) {
334                 if ((@file_exists($dir) || !is_dir($dir)) && !mkdir($dir, $mode)) {
335                     $ret = false;
336                 }
337             }
338         }
339
340         return $ret;
341     }
342
343     /**
344      * Remove temporary files created my mkTemp. This function is executed
345      * at script shutdown time
346      */
347     public static function _removeTmpFiles()
348     {
349         if (count($GLOBALS['_System_temp_files'])) {
350             $delete = $GLOBALS['_System_temp_files'];
351             array_unshift($delete, '-r');
352             System::rm($delete);
353             $GLOBALS['_System_temp_files'] = array();
354         }
355     }
356
357     /**
358      * The rm command for removing files.
359      * Supports multiple files and dirs and also recursive deletes
360      *
361      * @param string $args the arguments for rm
362      * @return   mixed   PEAR_Error or true for success
363      * @static
364      * @access   public
365      */
366     public static function rm($args)
367     {
368         $opts = System::_parseArgs($args, 'rf'); // "f" does nothing but I like it :-)
369         if (PEAR::isError($opts)) {
370             return System::raiseError($opts);
371         }
372         foreach ($opts[0] as $opt) {
373             if ($opt[0] == 'r') {
374                 $do_recursive = true;
375             }
376         }
377         $ret = true;
378         if (isset($do_recursive)) {
379             $struct = System::_multipleToStruct($opts[1]);
380             foreach ($struct['files'] as $file) {
381                 if (!@unlink($file)) {
382                     $ret = false;
383                 }
384             }
385
386             rsort($struct['dirs']);
387             foreach ($struct['dirs'] as $dir) {
388                 if (!@rmdir($dir)) {
389                     $ret = false;
390                 }
391             }
392         } else {
393             foreach ($opts[1] as $file) {
394                 $delete = (is_dir($file)) ? 'rmdir' : 'unlink';
395                 if (!@$delete($file)) {
396                     $ret = false;
397                 }
398             }
399         }
400         return $ret;
401     }
402
403     /**
404      * Creates a nested array representing the structure of a directory and files
405      *
406      * @param array $files Array listing files and dirs
407      * @return   array
408      * @static
409      * @see System::_dirToStruct()
410      */
411     protected static function _multipleToStruct($files)
412     {
413         $struct = array('dirs' => array(), 'files' => array());
414         settype($files, 'array');
415         foreach ($files as $file) {
416             if (is_dir($file) && !is_link($file)) {
417                 $tmp = System::_dirToStruct($file, 0);
418                 $struct = array_merge_recursive($tmp, $struct);
419             } else {
420                 if (!in_array($file, $struct['files'])) {
421                     $struct['files'][] = $file;
422                 }
423             }
424         }
425         return $struct;
426     }
427
428     /**
429      * Creates a nested array representing the structure of a directory
430      *
431      * System::_dirToStruct('dir1', 0) =>
432      *   Array
433      *    (
434      *    [dirs] => Array
435      *        (
436      *            [0] => dir1
437      *        )
438      *
439      *    [files] => Array
440      *        (
441      *            [0] => dir1/file2
442      *            [1] => dir1/file3
443      *        )
444      *    )
445      * @param string $sPath Name of the directory
446      * @param integer $maxinst max. deep of the lookup
447      * @param integer $aktinst starting deep of the lookup
448      * @param bool $silent if true, do not emit errors.
449      * @return   array   the structure of the dir
450      */
451     protected static function _dirToStruct($sPath, $maxinst, $aktinst = 0, $silent = false)
452     {
453         $struct = array('dirs' => array(), 'files' => array());
454         if (($dir = @opendir($sPath)) === false) {
455             if (!$silent) {
456                 System::raiseError("Could not open dir $sPath");
457             }
458             return $struct; // XXX could not open error
459         }
460
461         $struct['dirs'][] = $sPath = realpath($sPath); // XXX don't add if '.' or '..' ?
462         $list = array();
463         while (false !== ($file = readdir($dir))) {
464             if ($file != '.' && $file != '..') {
465                 $list[] = $file;
466             }
467         }
468
469         closedir($dir);
470         natsort($list);
471         if ($aktinst < $maxinst || $maxinst == 0) {
472             foreach ($list as $val) {
473                 $path = $sPath . DIRECTORY_SEPARATOR . $val;
474                 if (is_dir($path) && !is_link($path)) {
475                     $tmp = System::_dirToStruct($path, $maxinst, $aktinst + 1, $silent);
476                     $struct = array_merge_recursive($struct, $tmp);
477                 } else {
478                     $struct['files'][] = $path;
479                 }
480             }
481         }
482
483         return $struct;
484     }
485
486     /**
487      * The "which" command (show the full path of a command)
488      *
489      * @param string $program The command to search for
490      * @param mixed $fallback Value to return if $program is not found
491      *
492      * @return mixed A string with the full path or false if not found
493      * @author Stig Bakken <ssb@php.net>
494      */
495     public static function which($program, $fallback = false)
496     {
497         // enforce API
498         if (!is_string($program) || '' == $program) {
499             return $fallback;
500         }
501
502         // full path given
503         if (basename($program) != $program) {
504             $path_elements[] = dirname($program);
505             $program = basename($program);
506         } else {
507             $path = getenv('PATH');
508             if (!$path) {
509                 $path = getenv('Path'); // some OSes are just stupid enough to do this
510             }
511
512             $path_elements = explode(PATH_SEPARATOR, $path);
513         }
514
515         if (OS_WINDOWS) {
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, '');
522             }
523         } else {
524             $exe_suffixes = array('');
525         }
526
527         foreach ($exe_suffixes as $suff) {
528             foreach ($path_elements as $dir) {
529                 $file = $dir . DIRECTORY_SEPARATOR . $program . $suff;
530                 // It's possible to run a .bat on Windows that is_executable
531                 // would return false for. The is_executable check is meaningless...
532                 if (OS_WINDOWS) {
533                     return $file;
534                 } else {
535                     if (is_executable($file)) {
536                         return $file;
537                     }
538                 }
539             }
540         }
541         return $fallback;
542     }
543
544     /**
545      * The "find" command
546      *
547      * Usage:
548      *
549      * System::find($dir);
550      * System::find("$dir -type d");
551      * System::find("$dir -type f");
552      * System::find("$dir -name *.php");
553      * System::find("$dir -name *.php -name *.htm*");
554      * System::find("$dir -maxdepth 1");
555      *
556      * Params implemented:
557      * $dir            -> Start the search at this directory
558      * -type d         -> return only directories
559      * -type f         -> return only files
560      * -maxdepth <n>   -> max depth of recursion
561      * -name <pattern> -> search pattern (bash style). Multiple -name param allowed
562      *
563      * @param mixed Either array or string with the command line
564      * @return array Array of found files
565      */
566     public static function find($args)
567     {
568         if (!is_array($args)) {
569             $args = preg_split('/\s+/', $args, -1, PREG_SPLIT_NO_EMPTY);
570         }
571         $dir = realpath(array_shift($args));
572         if (!$dir) {
573             return array();
574         }
575         $patterns = array();
576         $depth = 0;
577         $do_files = $do_dirs = true;
578         $args_count = count($args);
579         for ($i = 0; $i < $args_count; $i++) {
580             switch ($args[$i]) {
581                 case '-type':
582                     if (in_array($args[$i + 1], array('d', 'f'))) {
583                         if ($args[$i + 1] == 'd') {
584                             $do_files = false;
585                         } else {
586                             $do_dirs = false;
587                         }
588                     }
589                     $i++;
590                     break;
591                 case '-name':
592                     $name = preg_quote($args[$i + 1], '#');
593                     // our magic characters ? and * have just been escaped,
594                     // so now we change the escaped versions to PCRE operators
595                     $name = strtr($name, array('\?' => '.', '\*' => '.*'));
596                     $patterns[] = '(' . $name . ')';
597                     $i++;
598                     break;
599                 case '-maxdepth':
600                     $depth = $args[$i + 1];
601                     break;
602             }
603         }
604         $path = System::_dirToStruct($dir, $depth, 0, true);
605         if ($do_files && $do_dirs) {
606             $files = array_merge($path['files'], $path['dirs']);
607         } elseif ($do_dirs) {
608             $files = $path['dirs'];
609         } else {
610             $files = $path['files'];
611         }
612         if (count($patterns)) {
613             $dsq = preg_quote(DIRECTORY_SEPARATOR, '#');
614             $pattern = '#(^|' . $dsq . ')' . implode('|', $patterns) . '($|' . $dsq . ')#';
615             $ret = array();
616             $files_count = count($files);
617             for ($i = 0; $i < $files_count; $i++) {
618                 // only search in the part of the file below the current directory
619                 $filepart = basename($files[$i]);
620                 if (preg_match($pattern, $filepart)) {
621                     $ret[] = $files[$i];
622                 }
623             }
624             return $ret;
625         }
626         return $files;
627     }
628 }