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