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. * Concatenate files
  59. *
  60. * Usage:
  61. * 1) $var = System::cat('sample.txt test.txt');
  62. * 2) System::cat('sample.txt test.txt > final.txt');
  63. * 3) System::cat('sample.txt test.txt >> final.txt');
  64. *
  65. * Note: as the class use fopen, urls should work also
  66. *
  67. * @param string $args the arguments
  68. * @return boolean true on success
  69. */
  70. public static function &cat($args)
  71. {
  72. $ret = null;
  73. $files = array();
  74. if (!is_array($args)) {
  75. $args = preg_split('/\s+/', $args, -1, PREG_SPLIT_NO_EMPTY);
  76. }
  77. $count_args = count($args);
  78. for ($i = 0; $i < $count_args; $i++) {
  79. if ($args[$i] == '>') {
  80. $mode = 'wb';
  81. $outputfile = $args[$i + 1];
  82. break;
  83. } elseif ($args[$i] == '>>') {
  84. $mode = 'ab+';
  85. $outputfile = $args[$i + 1];
  86. break;
  87. } else {
  88. $files[] = $args[$i];
  89. }
  90. }
  91. $outputfd = false;
  92. if (isset($mode)) {
  93. if (!$outputfd = fopen($outputfile, $mode)) {
  94. $err = System::raiseError("Could not open $outputfile");
  95. return $err;
  96. }
  97. $ret = true;
  98. }
  99. foreach ($files as $file) {
  100. if (!$fd = fopen($file, 'r')) {
  101. System::raiseError("Could not open $file");
  102. continue;
  103. }
  104. while ($cont = fread($fd, 2048)) {
  105. if (is_resource($outputfd)) {
  106. fwrite($outputfd, $cont);
  107. } else {
  108. $ret .= $cont;
  109. }
  110. }
  111. fclose($fd);
  112. }
  113. if (is_resource($outputfd)) {
  114. fclose($outputfd);
  115. }
  116. return $ret;
  117. }
  118. /**
  119. * Output errors with PHP trigger_error(). You can silence the errors
  120. * with prefixing a "@" sign to the function call: @System::mkdir(..);
  121. *
  122. * @param mixed $error a PEAR error or a string with the error message
  123. * @return bool false
  124. */
  125. protected static function raiseError($error)
  126. {
  127. if (PEAR::isError($error)) {
  128. $error = $error->getMessage();
  129. }
  130. trigger_error($error, E_USER_WARNING);
  131. return false;
  132. }
  133. /**
  134. * Creates temporary files or directories. This function will remove
  135. * the created files when the scripts finish its execution.
  136. *
  137. * Usage:
  138. * 1) $tempfile = System::mktemp("prefix");
  139. * 2) $tempdir = System::mktemp("-d prefix");
  140. * 3) $tempfile = System::mktemp();
  141. * 4) $tempfile = System::mktemp("-t /var/tmp prefix");
  142. *
  143. * prefix -> The string that will be prepended to the temp name
  144. * (defaults to "tmp").
  145. * -d -> A temporary dir will be created instead of a file.
  146. * -t -> The target dir where the temporary (file|dir) will be created. If
  147. * this param is missing by default the env vars TMP on Windows or
  148. * TMPDIR in Unix will be used. If these vars are also missing
  149. * c:\windows\temp or /tmp will be used.
  150. *
  151. * @param string $args The arguments
  152. * @return mixed the full path of the created (file|dir) or false
  153. * @see System::tmpdir()
  154. */
  155. public static function mktemp($args = null)
  156. {
  157. static $first_time = true;
  158. $opts = System::_parseArgs($args, 't:d');
  159. if (PEAR::isError($opts)) {
  160. return System::raiseError($opts);
  161. }
  162. foreach ($opts[0] as $opt) {
  163. if ($opt[0] == 'd') {
  164. $tmp_is_dir = true;
  165. } elseif ($opt[0] == 't') {
  166. $tmpdir = $opt[1];
  167. }
  168. }
  169. $prefix = (isset($opts[1][0])) ? $opts[1][0] : 'tmp';
  170. if (!isset($tmpdir)) {
  171. $tmpdir = System::tmpdir();
  172. }
  173. if (!System::mkDir(['-p', $tmpdir])) {
  174. return false;
  175. }
  176. $tmp = tempnam($tmpdir, $prefix);
  177. if (isset($tmp_is_dir)) {
  178. unlink($tmp); // be careful possible race condition here
  179. if (!mkdir($tmp, 0700)) {
  180. return System::raiseError("Unable to create temporary directory $tmpdir");
  181. }
  182. }
  183. $GLOBALS['_System_temp_files'][] = $tmp;
  184. /*if (isset($tmp_is_dir)) {
  185. //$GLOBALS['_System_temp_files'][] = dirname($tmp);
  186. }*/
  187. if ($first_time) {
  188. PEAR::registerShutdownFunc(array('System', '_removeTmpFiles'));
  189. $first_time = false;
  190. }
  191. return $tmp;
  192. }
  193. /**
  194. * returns the commandline arguments of a function
  195. *
  196. * @param string $argv the commandline
  197. * @param string $short_options the allowed option short-tags
  198. * @param string $long_options the allowed option long-tags
  199. * @return array the given options and there values
  200. */
  201. public static function _parseArgs($argv, $short_options, $long_options = null)
  202. {
  203. if (!is_array($argv) && $argv !== null) {
  204. /*
  205. // Quote all items that are a short option
  206. $av = preg_split('/(\A| )--?[a-z0-9]+[ =]?((?<!\\\\)((,\s*)|((?<!,)\s+))?)/i', $argv, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_OFFSET_CAPTURE);
  207. $offset = 0;
  208. foreach ($av as $a) {
  209. $b = trim($a[0]);
  210. if ($b{0} == '"' || $b{0} == "'") {
  211. continue;
  212. }
  213. $escape = escapeshellarg($b);
  214. $pos = $a[1] + $offset;
  215. $argv = substr_replace($argv, $escape, $pos, strlen($b));
  216. $offset += 2;
  217. }
  218. */
  219. // Find all items, quoted or otherwise
  220. preg_match_all("/(?:[\"'])(.*?)(?:['\"])|([^\s]+)/", $argv, $av);
  221. $argv = $av[1];
  222. foreach ($av[2] as $k => $a) {
  223. if (empty($a)) {
  224. continue;
  225. }
  226. $argv[$k] = trim($a);
  227. }
  228. }
  229. return (new Console_Getopt)->getopt2($argv, $short_options, $long_options);
  230. }
  231. /**
  232. * Get the path of the temporal directory set in the system
  233. * by looking in its environments variables.
  234. * Note: php.ini-recommended removes the "E" from the variables_order setting,
  235. * making unavaible the $_ENV array, that s why we do tests with _ENV
  236. *
  237. * @return string The temporary directory on the system
  238. */
  239. public static function tmpdir()
  240. {
  241. if (OS_WINDOWS) {
  242. if ($var = isset($_ENV['TMP']) ? $_ENV['TMP'] : getenv('TMP')) {
  243. return $var;
  244. }
  245. if ($var = isset($_ENV['TEMP']) ? $_ENV['TEMP'] : getenv('TEMP')) {
  246. return $var;
  247. }
  248. if ($var = isset($_ENV['USERPROFILE']) ? $_ENV['USERPROFILE'] : getenv('USERPROFILE')) {
  249. return $var;
  250. }
  251. if ($var = isset($_ENV['windir']) ? $_ENV['windir'] : getenv('windir')) {
  252. return $var;
  253. }
  254. return getenv('SystemRoot') . '\temp';
  255. }
  256. if ($var = isset($_ENV['TMPDIR']) ? $_ENV['TMPDIR'] : getenv('TMPDIR')) {
  257. return $var;
  258. }
  259. return realpath('/tmp');
  260. }
  261. /**
  262. * Make directories.
  263. *
  264. * The -p option will create parent directories
  265. * @param string $args the name of the director(y|ies) to create
  266. * @return bool True for success
  267. */
  268. public static function mkDir($args)
  269. {
  270. $opts = System::_parseArgs($args, 'pm:');
  271. if (PEAR::isError($opts)) {
  272. return System::raiseError($opts);
  273. }
  274. $mode = 0777; // default mode
  275. foreach ($opts[0] as $opt) {
  276. if ($opt[0] == 'p') {
  277. $create_parents = true;
  278. } elseif ($opt[0] == 'm') {
  279. // if the mode is clearly an octal number (starts with 0)
  280. // convert it to decimal
  281. if (strlen($opt[1]) && $opt[1]{0} == '0') {
  282. $opt[1] = octdec($opt[1]);
  283. } else {
  284. // convert to int
  285. $opt[1] += 0;
  286. }
  287. $mode = $opt[1];
  288. }
  289. }
  290. $ret = true;
  291. if (isset($create_parents)) {
  292. foreach ($opts[1] as $dir) {
  293. $dirstack = array();
  294. while ((!file_exists($dir) || !is_dir($dir)) &&
  295. $dir != DIRECTORY_SEPARATOR) {
  296. array_unshift($dirstack, $dir);
  297. $dir = dirname($dir);
  298. }
  299. while ($newdir = array_shift($dirstack)) {
  300. if (!is_writeable(dirname($newdir))) {
  301. $ret = false;
  302. break;
  303. }
  304. if (!mkdir($newdir, $mode)) {
  305. $ret = false;
  306. }
  307. }
  308. }
  309. } else {
  310. foreach ($opts[1] as $dir) {
  311. if ((@file_exists($dir) || !is_dir($dir)) && !mkdir($dir, $mode)) {
  312. $ret = false;
  313. }
  314. }
  315. }
  316. return $ret;
  317. }
  318. /**
  319. * Remove temporary files created my mkTemp. This function is executed
  320. * at script shutdown time
  321. */
  322. public static function _removeTmpFiles()
  323. {
  324. if (count($GLOBALS['_System_temp_files'])) {
  325. $delete = $GLOBALS['_System_temp_files'];
  326. array_unshift($delete, '-r');
  327. System::rm($delete);
  328. $GLOBALS['_System_temp_files'] = array();
  329. }
  330. }
  331. /**
  332. * The rm command for removing files.
  333. * Supports multiple files and dirs and also recursive deletes
  334. *
  335. * @param string $args the arguments for rm
  336. * @return mixed PEAR_Error or true for success
  337. * @static
  338. * @access public
  339. */
  340. public static function rm($args)
  341. {
  342. $opts = System::_parseArgs($args, 'rf'); // "f" does nothing but I like it :-)
  343. if (PEAR::isError($opts)) {
  344. return System::raiseError($opts);
  345. }
  346. foreach ($opts[0] as $opt) {
  347. if ($opt[0] == 'r') {
  348. $do_recursive = true;
  349. }
  350. }
  351. $ret = true;
  352. if (isset($do_recursive)) {
  353. $struct = System::_multipleToStruct($opts[1]);
  354. foreach ($struct['files'] as $file) {
  355. if (!@unlink($file)) {
  356. $ret = false;
  357. }
  358. }
  359. rsort($struct['dirs']);
  360. foreach ($struct['dirs'] as $dir) {
  361. if (!@rmdir($dir)) {
  362. $ret = false;
  363. }
  364. }
  365. } else {
  366. foreach ($opts[1] as $file) {
  367. $delete = (is_dir($file)) ? 'rmdir' : 'unlink';
  368. if (!@$delete($file)) {
  369. $ret = false;
  370. }
  371. }
  372. }
  373. return $ret;
  374. }
  375. /**
  376. * Creates a nested array representing the structure of a directory and files
  377. *
  378. * @param array $files Array listing files and dirs
  379. * @return array
  380. * @static
  381. * @see System::_dirToStruct()
  382. */
  383. protected static function _multipleToStruct($files)
  384. {
  385. $struct = array('dirs' => array(), 'files' => array());
  386. settype($files, 'array');
  387. foreach ($files as $file) {
  388. if (is_dir($file) && !is_link($file)) {
  389. $tmp = System::_dirToStruct($file, 0);
  390. $struct = array_merge_recursive($tmp, $struct);
  391. } else {
  392. if (!in_array($file, $struct['files'])) {
  393. $struct['files'][] = $file;
  394. }
  395. }
  396. }
  397. return $struct;
  398. }
  399. /**
  400. * Creates a nested array representing the structure of a directory
  401. *
  402. * System::_dirToStruct('dir1', 0) =>
  403. * Array
  404. * (
  405. * [dirs] => Array
  406. * (
  407. * [0] => dir1
  408. * )
  409. *
  410. * [files] => Array
  411. * (
  412. * [0] => dir1/file2
  413. * [1] => dir1/file3
  414. * )
  415. * )
  416. * @param string $sPath Name of the directory
  417. * @param integer $maxinst max. deep of the lookup
  418. * @param integer $aktinst starting deep of the lookup
  419. * @param bool $silent if true, do not emit errors.
  420. * @return array the structure of the dir
  421. */
  422. protected static function _dirToStruct($sPath, $maxinst, $aktinst = 0, $silent = false)
  423. {
  424. $struct = array('dirs' => array(), 'files' => array());
  425. if (($dir = @opendir($sPath)) === false) {
  426. if (!$silent) {
  427. System::raiseError("Could not open dir $sPath");
  428. }
  429. return $struct; // XXX could not open error
  430. }
  431. $struct['dirs'][] = $sPath = realpath($sPath); // XXX don't add if '.' or '..' ?
  432. $list = array();
  433. while (false !== ($file = readdir($dir))) {
  434. if ($file != '.' && $file != '..') {
  435. $list[] = $file;
  436. }
  437. }
  438. closedir($dir);
  439. natsort($list);
  440. if ($aktinst < $maxinst || $maxinst == 0) {
  441. foreach ($list as $val) {
  442. $path = $sPath . DIRECTORY_SEPARATOR . $val;
  443. if (is_dir($path) && !is_link($path)) {
  444. $tmp = System::_dirToStruct($path, $maxinst, $aktinst + 1, $silent);
  445. $struct = array_merge_recursive($struct, $tmp);
  446. } else {
  447. $struct['files'][] = $path;
  448. }
  449. }
  450. }
  451. return $struct;
  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. }