System.php 20 KB

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