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 platform 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: @package_version@
54 * @link http://pear.php.net/package/PEAR
55 * @since Class available since Release 0.1
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');
68 * Note: as the class use fopen, urls should work also
70 * @param string $args the arguments
71 * @return boolean true on success
73 public static function &cat($args)
77 if (!is_array($args)) {
78 $args = preg_split('/\s+/', $args, -1, PREG_SPLIT_NO_EMPTY);
81 $count_args = count($args);
82 for ($i = 0; $i < $count_args; $i++) {
83 if ($args[$i] == '>') {
85 $outputfile = $args[$i + 1];
87 } elseif ($args[$i] == '>>') {
89 $outputfile = $args[$i + 1];
97 if (!$outputfd = fopen($outputfile, $mode)) {
98 $err = System::raiseError("Could not open $outputfile");
103 foreach ($files as $file) {
104 if (!$fd = fopen($file, 'r')) {
105 System::raiseError("Could not open $file");
108 while ($cont = fread($fd, 2048)) {
109 if (is_resource($outputfd)) {
110 fwrite($outputfd, $cont);
117 if (is_resource($outputfd)) {
124 * Output errors with PHP trigger_error(). You can silence the errors
125 * with prefixing a "@" sign to the function call: @System::mkdir(..);
127 * @param mixed $error a PEAR error or a string with the error message
130 protected static function raiseError($error)
132 if (PEAR::isError($error)) {
133 $error = $error->getMessage();
135 trigger_error($error, E_USER_WARNING);
140 * Creates temporary files or directories. This function will remove
141 * the created files when the scripts finish its execution.
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");
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.
157 * @param string $args The arguments
158 * @return mixed the full path of the created (file|dir) or false
159 * @see System::tmpdir()
161 public static function mktemp($args = null)
163 static $first_time = true;
164 $opts = System::_parseArgs($args, 't:d');
165 if (PEAR::isError($opts)) {
166 return System::raiseError($opts);
169 foreach ($opts[0] as $opt) {
170 if ($opt[0] == 'd') {
172 } elseif ($opt[0] == 't') {
177 $prefix = (isset($opts[1][0])) ? $opts[1][0] : 'tmp';
178 if (!isset($tmpdir)) {
179 $tmpdir = System::tmpdir();
182 if (!System::mkDir(['-p', $tmpdir])) {
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");
194 $GLOBALS['_System_temp_files'][] = $tmp;
195 /*if (isset($tmp_is_dir)) {
196 //$GLOBALS['_System_temp_files'][] = dirname($tmp);
200 PEAR::registerShutdownFunc(array('System', '_removeTmpFiles'));
208 * returns the commandline arguments of a function
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
215 public static function _parseArgs($argv, $short_options, $long_options = null)
217 if (!is_array($argv) && $argv !== null) {
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);
222 foreach ($av as $a) {
224 if ($b{0} == '"' || $b{0} == "'") {
228 $escape = escapeshellarg($b);
229 $pos = $a[1] + $offset;
230 $argv = substr_replace($argv, $escape, $pos, strlen($b));
235 // Find all items, quoted or otherwise
236 preg_match_all("/(?:[\"'])(.*?)(?:['\"])|([^\s]+)/", $argv, $av);
238 foreach ($av[2] as $k => $a) {
242 $argv[$k] = trim($a);
246 return (new Console_Getopt)->getopt2($argv, $short_options, $long_options);
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
255 * @return string The temporary directory on the system
257 public static function tmpdir()
260 if ($var = isset($_ENV['TMP']) ? $_ENV['TMP'] : getenv('TMP')) {
263 if ($var = isset($_ENV['TEMP']) ? $_ENV['TEMP'] : getenv('TEMP')) {
266 if ($var = isset($_ENV['USERPROFILE']) ? $_ENV['USERPROFILE'] : getenv('USERPROFILE')) {
269 if ($var = isset($_ENV['windir']) ? $_ENV['windir'] : getenv('windir')) {
272 return getenv('SystemRoot') . '\temp';
274 if ($var = isset($_ENV['TMPDIR']) ? $_ENV['TMPDIR'] : getenv('TMPDIR')) {
277 return realpath('/tmp');
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
287 public static function mkDir($args)
289 $opts = System::_parseArgs($args, 'pm:');
290 if (PEAR::isError($opts)) {
291 return System::raiseError($opts);
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]);
312 if (isset($create_parents)) {
313 foreach ($opts[1] as $dir) {
315 while ((!file_exists($dir) || !is_dir($dir)) &&
316 $dir != DIRECTORY_SEPARATOR) {
317 array_unshift($dirstack, $dir);
318 $dir = dirname($dir);
321 while ($newdir = array_shift($dirstack)) {
322 if (!is_writeable(dirname($newdir))) {
327 if (!mkdir($newdir, $mode)) {
333 foreach ($opts[1] as $dir) {
334 if ((@file_exists($dir) || !is_dir($dir)) && !mkdir($dir, $mode)) {
344 * Remove temporary files created my mkTemp. This function is executed
345 * at script shutdown time
347 public static function _removeTmpFiles()
349 if (count($GLOBALS['_System_temp_files'])) {
350 $delete = $GLOBALS['_System_temp_files'];
351 array_unshift($delete, '-r');
353 $GLOBALS['_System_temp_files'] = array();
358 * The rm command for removing files.
359 * Supports multiple files and dirs and also recursive deletes
361 * @param string $args the arguments for rm
362 * @return mixed PEAR_Error or true for success
366 public static function rm($args)
368 $opts = System::_parseArgs($args, 'rf'); // "f" does nothing but I like it :-)
369 if (PEAR::isError($opts)) {
370 return System::raiseError($opts);
372 foreach ($opts[0] as $opt) {
373 if ($opt[0] == 'r') {
374 $do_recursive = true;
378 if (isset($do_recursive)) {
379 $struct = System::_multipleToStruct($opts[1]);
380 foreach ($struct['files'] as $file) {
381 if (!@unlink($file)) {
386 rsort($struct['dirs']);
387 foreach ($struct['dirs'] as $dir) {
393 foreach ($opts[1] as $file) {
394 $delete = (is_dir($file)) ? 'rmdir' : 'unlink';
395 if (!@$delete($file)) {
404 * Creates a nested array representing the structure of a directory and files
406 * @param array $files Array listing files and dirs
409 * @see System::_dirToStruct()
411 protected static function _multipleToStruct($files)
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);
420 if (!in_array($file, $struct['files'])) {
421 $struct['files'][] = $file;
429 * Creates a nested array representing the structure of a directory
431 * System::_dirToStruct('dir1', 0) =>
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
451 protected static function _dirToStruct($sPath, $maxinst, $aktinst = 0, $silent = false)
453 $struct = array('dirs' => array(), 'files' => array());
454 if (($dir = @opendir($sPath)) === false) {
456 System::raiseError("Could not open dir $sPath");
458 return $struct; // XXX could not open error
461 $struct['dirs'][] = $sPath = realpath($sPath); // XXX don't add if '.' or '..' ?
463 while (false !== ($file = readdir($dir))) {
464 if ($file != '.' && $file != '..') {
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);
478 $struct['files'][] = $path;
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 // It's possible to run a .bat on Windows that is_executable
531 // would return false for. The is_executable check is meaningless...
535 if (is_executable($file)) {
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");
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
563 * @param mixed Either array or string with the command line
564 * @return array Array of found files
566 public static function find($args)
568 if (!is_array($args)) {
569 $args = preg_split('/\s+/', $args, -1, PREG_SPLIT_NO_EMPTY);
571 $dir = realpath(array_shift($args));
577 $do_files = $do_dirs = true;
578 $args_count = count($args);
579 for ($i = 0; $i < $args_count; $i++) {
582 if (in_array($args[$i + 1], array('d', 'f'))) {
583 if ($args[$i + 1] == 'd') {
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 . ')';
600 $depth = $args[$i + 1];
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'];
610 $files = $path['files'];
612 if (count($patterns)) {
613 $dsq = preg_quote(DIRECTORY_SEPARATOR, '#');
614 $pattern = '#(^|' . $dsq . ')' . implode('|', $patterns) . '($|' . $dsq . ')#';
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)) {