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 * @version CVS: $Id: System.php 307683 2011-01-23 21:56:12Z dufuz $
13 * @link http://pear.php.net/package/PEAR
14 * @since File available since Release 0.1
20 require_once 'PEAR.php';
21 require_once 'Console/Getopt.php';
23 $GLOBALS['_System_temp_files'] = array();
26 * System offers cross plattform compatible system functions
28 * Static functions for different operations. Should work under
29 * Unix and Windows. The names and usage has been taken from its respectively
30 * GNU commands. The functions will return (bool) false on error and will
31 * trigger the error with the PHP trigger_error() function (you can silence
32 * the error by prefixing a '@' sign after the function call, but this
33 * is not recommended practice. Instead use an error handler with
34 * {@link set_error_handler()}).
36 * Documentation on this class you can find in:
37 * http://pear.php.net/manual/
40 * if (!@System::rm('-r file1 dir1')) {
41 * print "could not delete file1 or dir1";
44 * In case you need to to pass file names with spaces,
45 * pass the params as an array:
47 * System::rm(array('-r', $file1, $dir1));
51 * @author Tomas V.V. Cox <cox@idecnet.com>
52 * @copyright 1997-2006 The PHP Group
53 * @license http://opensource.org/licenses/bsd-license.php New BSD License
54 * @version Release: 1.9.2
55 * @link http://pear.php.net/package/PEAR
56 * @since Class available since Release 0.1
62 * returns the commandline arguments of a function
64 * @param string $argv the commandline
65 * @param string $short_options the allowed option short-tags
66 * @param string $long_options the allowed option long-tags
67 * @return array the given options and there values
71 function _parseArgs($argv, $short_options, $long_options = null)
73 if (!is_array($argv) && $argv !== null) {
74 $argv = preg_split('/\s+/', $argv, -1, PREG_SPLIT_NO_EMPTY);
76 return Console_Getopt::getopt2($argv, $short_options);
80 * Output errors with PHP trigger_error(). You can silence the errors
81 * with prefixing a "@" sign to the function call: @System::mkdir(..);
83 * @param mixed $error a PEAR error or a string with the error message
88 function raiseError($error)
90 if (PEAR::isError($error)) {
91 $error = $error->getMessage();
93 trigger_error($error, E_USER_WARNING);
98 * Creates a nested array representing the structure of a directory
100 * System::_dirToStruct('dir1', 0) =>
114 * @param string $sPath Name of the directory
115 * @param integer $maxinst max. deep of the lookup
116 * @param integer $aktinst starting deep of the lookup
117 * @param bool $silent if true, do not emit errors.
118 * @return array the structure of the dir
122 function _dirToStruct($sPath, $maxinst, $aktinst = 0, $silent = false)
124 $struct = array('dirs' => array(), 'files' => array());
125 if (($dir = @opendir($sPath)) === false) {
127 System::raiseError("Could not open dir $sPath");
129 return $struct; // XXX could not open error
132 $struct['dirs'][] = $sPath = realpath($sPath); // XXX don't add if '.' or '..' ?
134 while (false !== ($file = readdir($dir))) {
135 if ($file != '.' && $file != '..') {
142 if ($aktinst < $maxinst || $maxinst == 0) {
143 foreach ($list as $val) {
144 $path = $sPath . DIRECTORY_SEPARATOR . $val;
145 if (is_dir($path) && !is_link($path)) {
146 $tmp = System::_dirToStruct($path, $maxinst, $aktinst+1, $silent);
147 $struct = array_merge_recursive($struct, $tmp);
149 $struct['files'][] = $path;
158 * Creates a nested array representing the structure of a directory and files
160 * @param array $files Array listing files and dirs
163 * @see System::_dirToStruct()
165 function _multipleToStruct($files)
167 $struct = array('dirs' => array(), 'files' => array());
168 settype($files, 'array');
169 foreach ($files as $file) {
170 if (is_dir($file) && !is_link($file)) {
171 $tmp = System::_dirToStruct($file, 0);
172 $struct = array_merge_recursive($tmp, $struct);
174 if (!in_array($file, $struct['files'])) {
175 $struct['files'][] = $file;
183 * The rm command for removing files.
184 * Supports multiple files and dirs and also recursive deletes
186 * @param string $args the arguments for rm
187 * @return mixed PEAR_Error or true for success
193 $opts = System::_parseArgs($args, 'rf'); // "f" does nothing but I like it :-)
194 if (PEAR::isError($opts)) {
195 return System::raiseError($opts);
197 foreach ($opts[0] as $opt) {
198 if ($opt[0] == 'r') {
199 $do_recursive = true;
203 if (isset($do_recursive)) {
204 $struct = System::_multipleToStruct($opts[1]);
205 foreach ($struct['files'] as $file) {
206 if (!@unlink($file)) {
211 rsort($struct['dirs']);
212 foreach ($struct['dirs'] as $dir) {
218 foreach ($opts[1] as $file) {
219 $delete = (is_dir($file)) ? 'rmdir' : 'unlink';
220 if (!@$delete($file)) {
231 * The -p option will create parent directories
232 * @param string $args the name of the director(y|ies) to create
233 * @return bool True for success
237 function mkDir($args)
239 $opts = System::_parseArgs($args, 'pm:');
240 if (PEAR::isError($opts)) {
241 return System::raiseError($opts);
244 $mode = 0777; // default mode
245 foreach ($opts[0] as $opt) {
246 if ($opt[0] == 'p') {
247 $create_parents = true;
248 } elseif ($opt[0] == 'm') {
249 // if the mode is clearly an octal number (starts with 0)
250 // convert it to decimal
251 if (strlen($opt[1]) && $opt[1]{0} == '0') {
252 $opt[1] = octdec($opt[1]);
262 if (isset($create_parents)) {
263 foreach ($opts[1] as $dir) {
265 while ((!file_exists($dir) || !is_dir($dir)) &&
266 $dir != DIRECTORY_SEPARATOR) {
267 array_unshift($dirstack, $dir);
268 $dir = dirname($dir);
271 while ($newdir = array_shift($dirstack)) {
272 if (!is_writeable(dirname($newdir))) {
277 if (!mkdir($newdir, $mode)) {
283 foreach($opts[1] as $dir) {
284 if ((@file_exists($dir) || !is_dir($dir)) && !mkdir($dir, $mode)) {
297 * 1) $var = System::cat('sample.txt test.txt');
298 * 2) System::cat('sample.txt test.txt > final.txt');
299 * 3) System::cat('sample.txt test.txt >> final.txt');
301 * Note: as the class use fopen, urls should work also (test that)
303 * @param string $args the arguments
304 * @return boolean true on success
312 if (!is_array($args)) {
313 $args = preg_split('/\s+/', $args, -1, PREG_SPLIT_NO_EMPTY);
316 $count_args = count($args);
317 for ($i = 0; $i < $count_args; $i++) {
318 if ($args[$i] == '>') {
320 $outputfile = $args[$i+1];
322 } elseif ($args[$i] == '>>') {
324 $outputfile = $args[$i+1];
327 $files[] = $args[$i];
332 if (!$outputfd = fopen($outputfile, $mode)) {
333 $err = System::raiseError("Could not open $outputfile");
338 foreach ($files as $file) {
339 if (!$fd = fopen($file, 'r')) {
340 System::raiseError("Could not open $file");
343 while ($cont = fread($fd, 2048)) {
344 if (is_resource($outputfd)) {
345 fwrite($outputfd, $cont);
352 if (is_resource($outputfd)) {
359 * Creates temporary files or directories. This function will remove
360 * the created files when the scripts finish its execution.
363 * 1) $tempfile = System::mktemp("prefix");
364 * 2) $tempdir = System::mktemp("-d prefix");
365 * 3) $tempfile = System::mktemp();
366 * 4) $tempfile = System::mktemp("-t /var/tmp prefix");
368 * prefix -> The string that will be prepended to the temp name
369 * (defaults to "tmp").
370 * -d -> A temporary dir will be created instead of a file.
371 * -t -> The target dir where the temporary (file|dir) will be created. If
372 * this param is missing by default the env vars TMP on Windows or
373 * TMPDIR in Unix will be used. If these vars are also missing
374 * c:\windows\temp or /tmp will be used.
376 * @param string $args The arguments
377 * @return mixed the full path of the created (file|dir) or false
378 * @see System::tmpdir()
382 function mktemp($args = null)
384 static $first_time = true;
385 $opts = System::_parseArgs($args, 't:d');
386 if (PEAR::isError($opts)) {
387 return System::raiseError($opts);
390 foreach ($opts[0] as $opt) {
391 if ($opt[0] == 'd') {
393 } elseif ($opt[0] == 't') {
398 $prefix = (isset($opts[1][0])) ? $opts[1][0] : 'tmp';
399 if (!isset($tmpdir)) {
400 $tmpdir = System::tmpdir();
403 if (!System::mkDir(array('-p', $tmpdir))) {
407 $tmp = tempnam($tmpdir, $prefix);
408 if (isset($tmp_is_dir)) {
409 unlink($tmp); // be careful possible race condition here
410 if (!mkdir($tmp, 0700)) {
411 return System::raiseError("Unable to create temporary directory $tmpdir");
415 $GLOBALS['_System_temp_files'][] = $tmp;
416 if (isset($tmp_is_dir)) {
417 //$GLOBALS['_System_temp_files'][] = dirname($tmp);
421 PEAR::registerShutdownFunc(array('System', '_removeTmpFiles'));
429 * Remove temporary files created my mkTemp. This function is executed
430 * at script shutdown time
435 function _removeTmpFiles()
437 if (count($GLOBALS['_System_temp_files'])) {
438 $delete = $GLOBALS['_System_temp_files'];
439 array_unshift($delete, '-r');
441 $GLOBALS['_System_temp_files'] = array();
446 * Get the path of the temporal directory set in the system
447 * by looking in its environments variables.
448 * Note: php.ini-recommended removes the "E" from the variables_order setting,
449 * making unavaible the $_ENV array, that s why we do tests with _ENV
452 * @return string The temporary directory on the system
457 if ($var = isset($_ENV['TMP']) ? $_ENV['TMP'] : getenv('TMP')) {
460 if ($var = isset($_ENV['TEMP']) ? $_ENV['TEMP'] : getenv('TEMP')) {
463 if ($var = isset($_ENV['USERPROFILE']) ? $_ENV['USERPROFILE'] : getenv('USERPROFILE')) {
466 if ($var = isset($_ENV['windir']) ? $_ENV['windir'] : getenv('windir')) {
469 return getenv('SystemRoot') . '\temp';
471 if ($var = isset($_ENV['TMPDIR']) ? $_ENV['TMPDIR'] : getenv('TMPDIR')) {
474 return realpath('/tmp');
478 * The "which" command (show the full path of a command)
480 * @param string $program The command to search for
481 * @param mixed $fallback Value to return if $program is not found
483 * @return mixed A string with the full path or false if not found
485 * @author Stig Bakken <ssb@php.net>
487 function which($program, $fallback = false)
490 if (!is_string($program) || '' == $program) {
495 if (basename($program) != $program) {
496 $path_elements[] = dirname($program);
497 $program = basename($program);
500 if (!ini_get('safe_mode') || !$path = ini_get('safe_mode_exec_dir')) {
501 $path = getenv('PATH');
503 $path = getenv('Path'); // some OSes are just stupid enough to do this
506 $path_elements = explode(PATH_SEPARATOR, $path);
510 $exe_suffixes = getenv('PATHEXT')
511 ? explode(PATH_SEPARATOR, getenv('PATHEXT'))
512 : array('.exe','.bat','.cmd','.com');
513 // allow passing a command.exe param
514 if (strpos($program, '.') !== false) {
515 array_unshift($exe_suffixes, '');
517 // is_executable() is not available on windows for PHP4
518 $pear_is_executable = (function_exists('is_executable')) ? 'is_executable' : 'is_file';
520 $exe_suffixes = array('');
521 $pear_is_executable = 'is_executable';
524 foreach ($exe_suffixes as $suff) {
525 foreach ($path_elements as $dir) {
526 $file = $dir . DIRECTORY_SEPARATOR . $program . $suff;
527 if (@$pear_is_executable($file)) {
540 * System::find($dir);
541 * System::find("$dir -type d");
542 * System::find("$dir -type f");
543 * System::find("$dir -name *.php");
544 * System::find("$dir -name *.php -name *.htm*");
545 * System::find("$dir -maxdepth 1");
548 * $dir -> Start the search at this directory
549 * -type d -> return only directories
550 * -type f -> return only files
551 * -maxdepth <n> -> max depth of recursion
552 * -name <pattern> -> search pattern (bash style). Multiple -name param allowed
554 * @param mixed Either array or string with the command line
555 * @return array Array of found files
561 if (!is_array($args)) {
562 $args = preg_split('/\s+/', $args, -1, PREG_SPLIT_NO_EMPTY);
564 $dir = realpath(array_shift($args));
570 $do_files = $do_dirs = true;
571 $args_count = count($args);
572 for ($i = 0; $i < $args_count; $i++) {
575 if (in_array($args[$i+1], array('d', 'f'))) {
576 if ($args[$i+1] == 'd') {
585 $name = preg_quote($args[$i+1], '#');
586 // our magic characters ? and * have just been escaped,
587 // so now we change the escaped versions to PCRE operators
588 $name = strtr($name, array('\?' => '.', '\*' => '.*'));
589 $patterns[] = '('.$name.')';
593 $depth = $args[$i+1];
597 $path = System::_dirToStruct($dir, $depth, 0, true);
598 if ($do_files && $do_dirs) {
599 $files = array_merge($path['files'], $path['dirs']);
600 } elseif ($do_dirs) {
601 $files = $path['dirs'];
603 $files = $path['files'];
605 if (count($patterns)) {
606 $dsq = preg_quote(DIRECTORY_SEPARATOR, '#');
607 $pattern = '#(^|'.$dsq.')'.implode('|', $patterns).'($|'.$dsq.')#';
609 $files_count = count($files);
610 for ($i = 0; $i < $files_count; $i++) {
611 // only search in the part of the file below the current directory
612 $filepart = basename($files[$i]);
613 if (preg_match($pattern, $filepart)) {