System.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. <?php
  2. //
  3. // +----------------------------------------------------------------------+
  4. // | PHP Version 5 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1997-2004 The PHP Group |
  7. // +----------------------------------------------------------------------+
  8. // | This source file is subject to version 3.0 of the PHP license, |
  9. // | that is bundled with this package in the file LICENSE, and is |
  10. // | available through the world-wide-web at the following url: |
  11. // | http://www.php.net/license/3_0.txt. |
  12. // | If you did not receive a copy of the PHP license and are unable to |
  13. // | obtain it through the world-wide-web, please send a note to |
  14. // | license@php.net so we can mail you a copy immediately. |
  15. // +----------------------------------------------------------------------+
  16. // | Authors: Tomas V.V.Cox <cox@idecnet.com> |
  17. // +----------------------------------------------------------------------+
  18. //
  19. // $Id: System.php,v 1.36 2004/06/15 16:33:46 pajoye Exp $
  20. //
  21. require_once( 'PEAR.php');
  22. require_once( 'Console/Getopt.php');
  23. $GLOBALS['_System_temp_files'] = array();
  24. /**
  25. * System offers cross plattform compatible system functions
  26. *
  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).
  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. * @package System
  47. * @author Tomas V.V.Cox <cox@idecnet.com>
  48. * @version $Revision: 1.36 $
  49. * @access public
  50. * @see http://pear.php.net/manual/
  51. */
  52. class System
  53. {
  54. /**
  55. * returns the commandline arguments of a function
  56. *
  57. * @param string $argv the commandline
  58. * @param string $short_options the allowed option short-tags
  59. * @param string $long_options the allowed option long-tags
  60. * @return array the given options and there values
  61. * @access private
  62. */
  63. function _parseArgs($argv, $short_options, $long_options = null)
  64. {
  65. if (!is_array($argv) && $argv !== null) {
  66. $argv = preg_split('/\s+/', $argv);
  67. }
  68. return Console_Getopt::getopt2($argv, $short_options);
  69. }
  70. /**
  71. * Output errors with PHP trigger_error(). You can silence the errors
  72. * with prefixing a "@" sign to the function call: @System::mkdir(..);
  73. *
  74. * @param mixed $error a PEAR error or a string with the error message
  75. * @return bool false
  76. * @access private
  77. */
  78. function raiseError($error)
  79. {
  80. if (PEAR::isError($error)) {
  81. $error = $error->getMessage();
  82. }
  83. trigger_error($error, E_USER_WARNING);
  84. return false;
  85. }
  86. /**
  87. * Creates a nested array representing the structure of a directory
  88. *
  89. * System::_dirToStruct('dir1', 0) =>
  90. * Array
  91. * (
  92. * [dirs] => Array
  93. * (
  94. * [0] => dir1
  95. * )
  96. *
  97. * [files] => Array
  98. * (
  99. * [0] => dir1/file2
  100. * [1] => dir1/file3
  101. * )
  102. * )
  103. * @param string $sPath Name of the directory
  104. * @param integer $maxinst max. deep of the lookup
  105. * @param integer $aktinst starting deep of the lookup
  106. * @return array the structure of the dir
  107. * @access private
  108. */
  109. function _dirToStruct($sPath, $maxinst, $aktinst = 0)
  110. {
  111. $struct = array('dirs' => array(), 'files' => array());
  112. if (($dir = @opendir($sPath)) === false) {
  113. System::raiseError("Could not open dir $sPath");
  114. return $struct; // XXX could not open error
  115. }
  116. $struct['dirs'][] = $sPath; // XXX don't add if '.' or '..' ?
  117. $list = array();
  118. while ($file = readdir($dir)) {
  119. if ($file != '.' && $file != '..') {
  120. $list[] = $file;
  121. }
  122. }
  123. closedir($dir);
  124. sort($list);
  125. if ($aktinst < $maxinst || $maxinst == 0) {
  126. foreach($list as $val) {
  127. $path = $sPath . DIRECTORY_SEPARATOR . $val;
  128. if (is_dir($path)) {
  129. $tmp = System::_dirToStruct($path, $maxinst, $aktinst+1);
  130. $struct = array_merge_recursive($tmp, $struct);
  131. } else {
  132. $struct['files'][] = $path;
  133. }
  134. }
  135. }
  136. return $struct;
  137. }
  138. /**
  139. * Creates a nested array representing the structure of a directory and files
  140. *
  141. * @param array $files Array listing files and dirs
  142. * @return array
  143. * @see System::_dirToStruct()
  144. */
  145. function _multipleToStruct($files)
  146. {
  147. $struct = array('dirs' => array(), 'files' => array());
  148. settype($files, 'array');
  149. foreach ($files as $file) {
  150. if (is_dir($file)) {
  151. $tmp = System::_dirToStruct($file, 0);
  152. $struct = array_merge_recursive($tmp, $struct);
  153. } else {
  154. $struct['files'][] = $file;
  155. }
  156. }
  157. return $struct;
  158. }
  159. /**
  160. * The rm command for removing files.
  161. * Supports multiple files and dirs and also recursive deletes
  162. *
  163. * @param string $args the arguments for rm
  164. * @return mixed PEAR_Error or true for success
  165. * @access public
  166. */
  167. function rm($args)
  168. {
  169. $opts = System::_parseArgs($args, 'rf'); // "f" do nothing but like it :-)
  170. if (PEAR::isError($opts)) {
  171. return System::raiseError($opts);
  172. }
  173. foreach($opts[0] as $opt) {
  174. if ($opt[0] == 'r') {
  175. $do_recursive = true;
  176. }
  177. }
  178. $ret = true;
  179. if (isset($do_recursive)) {
  180. $struct = System::_multipleToStruct($opts[1]);
  181. foreach($struct['files'] as $file) {
  182. if (!@unlink($file)) {
  183. $ret = false;
  184. }
  185. }
  186. foreach($struct['dirs'] as $dir) {
  187. if (!@rmdir($dir)) {
  188. $ret = false;
  189. }
  190. }
  191. } else {
  192. foreach ($opts[1] as $file) {
  193. $delete = (is_dir($file)) ? 'rmdir' : 'unlink';
  194. if (!@$delete($file)) {
  195. $ret = false;
  196. }
  197. }
  198. }
  199. return $ret;
  200. }
  201. /**
  202. * Make directories. Note that we use call_user_func('mkdir') to avoid
  203. * a problem with ZE2 calling System::mkDir instead of the native PHP func.
  204. *
  205. * @param string $args the name of the director(y|ies) to create
  206. * @return bool True for success
  207. * @access public
  208. */
  209. function mkDir($args)
  210. {
  211. $opts = System::_parseArgs($args, 'pm:');
  212. if (PEAR::isError($opts)) {
  213. return System::raiseError($opts);
  214. }
  215. $mode = 0777; // default mode
  216. foreach($opts[0] as $opt) {
  217. if ($opt[0] == 'p') {
  218. $create_parents = true;
  219. } elseif($opt[0] == 'm') {
  220. // if the mode is clearly an octal number (starts with 0)
  221. // convert it to decimal
  222. if (strlen($opt[1]) && $opt[1]{0} == '0') {
  223. $opt[1] = octdec($opt[1]);
  224. } else {
  225. // convert to int
  226. $opt[1] += 0;
  227. }
  228. $mode = $opt[1];
  229. }
  230. }
  231. $ret = true;
  232. if (isset($create_parents)) {
  233. foreach($opts[1] as $dir) {
  234. $dirstack = array();
  235. while (!@is_dir($dir) && $dir != DIRECTORY_SEPARATOR) {
  236. array_unshift($dirstack, $dir);
  237. $dir = dirname($dir);
  238. }
  239. while ($newdir = array_shift($dirstack)) {
  240. if (!call_user_func('mkdir', $newdir, $mode)) {
  241. $ret = false;
  242. }
  243. }
  244. }
  245. } else {
  246. foreach($opts[1] as $dir) {
  247. if (!@is_dir($dir) && !call_user_func('mkdir', $dir, $mode)) {
  248. $ret = false;
  249. }
  250. }
  251. }
  252. return $ret;
  253. }
  254. /**
  255. * Concatenate files
  256. *
  257. * Usage:
  258. * 1) $var = System::cat('sample.txt test.txt');
  259. * 2) System::cat('sample.txt test.txt > final.txt');
  260. * 3) System::cat('sample.txt test.txt >> final.txt');
  261. *
  262. * Note: as the class use fopen, urls should work also (test that)
  263. *
  264. * @param string $args the arguments
  265. * @return boolean true on success
  266. * @access public
  267. */
  268. function &cat($args)
  269. {
  270. $ret = null;
  271. $files = array();
  272. if (!is_array($args)) {
  273. $args = preg_split('/\s+/', $args);
  274. }
  275. for($i=0; $i < count($args); $i++) {
  276. if ($args[$i] == '>') {
  277. $mode = 'wb';
  278. $outputfile = $args[$i+1];
  279. break;
  280. } elseif ($args[$i] == '>>') {
  281. $mode = 'ab+';
  282. $outputfile = $args[$i+1];
  283. break;
  284. } else {
  285. $files[] = $args[$i];
  286. }
  287. }
  288. if (isset($mode)) {
  289. if (!$outputfd = fopen($outputfile, $mode)) {
  290. $err = System::raiseError("Could not open $outputfile");
  291. return $err;
  292. }
  293. $ret = true;
  294. }
  295. foreach ($files as $file) {
  296. if (!$fd = fopen($file, 'r')) {
  297. System::raiseError("Could not open $file");
  298. continue;
  299. }
  300. while ($cont = fread($fd, 2048)) {
  301. if (isset($outputfd)) {
  302. fwrite($outputfd, $cont);
  303. } else {
  304. $ret .= $cont;
  305. }
  306. }
  307. fclose($fd);
  308. }
  309. if (@is_resource($outputfd)) {
  310. fclose($outputfd);
  311. }
  312. return $ret;
  313. }
  314. /**
  315. * Creates temporary files or directories. This function will remove
  316. * the created files when the scripts finish its execution.
  317. *
  318. * Usage:
  319. * 1) $tempfile = System::mktemp("prefix");
  320. * 2) $tempdir = System::mktemp("-d prefix");
  321. * 3) $tempfile = System::mktemp();
  322. * 4) $tempfile = System::mktemp("-t /var/tmp prefix");
  323. *
  324. * prefix -> The string that will be prepended to the temp name
  325. * (defaults to "tmp").
  326. * -d -> A temporary dir will be created instead of a file.
  327. * -t -> The target dir where the temporary (file|dir) will be created. If
  328. * this param is missing by default the env vars TMP on Windows or
  329. * TMPDIR in Unix will be used. If these vars are also missing
  330. * c:\windows\temp or /tmp will be used.
  331. *
  332. * @param string $args The arguments
  333. * @return mixed the full path of the created (file|dir) or false
  334. * @see System::tmpdir()
  335. * @access public
  336. */
  337. function mktemp($args = null)
  338. {
  339. static $first_time = true;
  340. $opts = System::_parseArgs($args, 't:d');
  341. if (PEAR::isError($opts)) {
  342. return System::raiseError($opts);
  343. }
  344. foreach($opts[0] as $opt) {
  345. if($opt[0] == 'd') {
  346. $tmp_is_dir = true;
  347. } elseif($opt[0] == 't') {
  348. $tmpdir = $opt[1];
  349. }
  350. }
  351. $prefix = (isset($opts[1][0])) ? $opts[1][0] : 'tmp';
  352. if (!isset($tmpdir)) {
  353. $tmpdir = System::tmpdir();
  354. }
  355. if (!System::mkDir("-p $tmpdir")) {
  356. return false;
  357. }
  358. $tmp = tempnam($tmpdir, $prefix);
  359. if (isset($tmp_is_dir)) {
  360. unlink($tmp); // be careful possible race condition here
  361. if (!call_user_func('mkdir', $tmp, 0700)) {
  362. return System::raiseError("Unable to create temporary directory $tmpdir");
  363. }
  364. }
  365. $GLOBALS['_System_temp_files'][] = $tmp;
  366. if ($first_time) {
  367. PEAR::registerShutdownFunc(array('System', '_removeTmpFiles'));
  368. $first_time = false;
  369. }
  370. return $tmp;
  371. }
  372. /**
  373. * Remove temporary files created my mkTemp. This function is executed
  374. * at script shutdown time
  375. *
  376. * @access private
  377. */
  378. function _removeTmpFiles()
  379. {
  380. if (count($GLOBALS['_System_temp_files'])) {
  381. $delete = $GLOBALS['_System_temp_files'];
  382. array_unshift($delete, '-r');
  383. System::rm($delete);
  384. }
  385. }
  386. /**
  387. * Get the path of the temporal directory set in the system
  388. * by looking in its environments variables.
  389. * Note: php.ini-recommended removes the "E" from the variables_order setting,
  390. * making unavaible the $_ENV array, that s why we do tests with _ENV
  391. *
  392. * @return string The temporal directory on the system
  393. */
  394. function tmpdir()
  395. {
  396. if (OS_WINDOWS) {
  397. if ($var = isset($_ENV['TEMP']) ? $_ENV['TEMP'] : getenv('TEMP')) {
  398. return $var;
  399. }
  400. if ($var = isset($_ENV['TMP']) ? $_ENV['TMP'] : getenv('TMP')) {
  401. return $var;
  402. }
  403. if ($var = isset($_ENV['windir']) ? $_ENV['windir'] : getenv('windir')) {
  404. return $var;
  405. }
  406. return getenv('SystemRoot') . '\temp';
  407. }
  408. if ($var = isset($_ENV['TMPDIR']) ? $_ENV['TMPDIR'] : getenv('TMPDIR')) {
  409. return $var;
  410. }
  411. return '/tmp';
  412. }
  413. /**
  414. * The "which" command (show the full path of a command)
  415. *
  416. * @param string $program The command to search for
  417. * @return mixed A string with the full path or false if not found
  418. * @author Stig Bakken <ssb@php.net>
  419. */
  420. function which($program, $fallback = false)
  421. {
  422. // is_executable() is not available on windows
  423. if (OS_WINDOWS) {
  424. $pear_is_executable = 'is_file';
  425. } else {
  426. $pear_is_executable = 'is_executable';
  427. }
  428. // full path given
  429. if (basename($program) != $program) {
  430. return (@$pear_is_executable($program)) ? $program : $fallback;
  431. }
  432. // XXX FIXME honor safe mode
  433. $path_delim = OS_WINDOWS ? ';' : ':';
  434. $exe_suffixes = OS_WINDOWS ? array('.exe','.bat','.cmd','.com') : array('');
  435. $path_elements = explode($path_delim, getenv('PATH'));
  436. foreach ($exe_suffixes as $suff) {
  437. foreach ($path_elements as $dir) {
  438. $file = $dir . DIRECTORY_SEPARATOR . $program . $suff;
  439. if (@is_file($file) && @$pear_is_executable($file)) {
  440. return $file;
  441. }
  442. }
  443. }
  444. return $fallback;
  445. }
  446. /**
  447. * The "find" command
  448. *
  449. * Usage:
  450. *
  451. * System::find($dir);
  452. * System::find("$dir -type d");
  453. * System::find("$dir -type f");
  454. * System::find("$dir -name *.php");
  455. * System::find("$dir -name *.php -name *.htm*");
  456. * System::find("$dir -maxdepth 1");
  457. *
  458. * Params implmented:
  459. * $dir -> Start the search at this directory
  460. * -type d -> return only directories
  461. * -type f -> return only files
  462. * -maxdepth <n> -> max depth of recursion
  463. * -name <pattern> -> search pattern (bash style). Multiple -name param allowed
  464. *
  465. * @param mixed Either array or string with the command line
  466. * @return array Array of found files
  467. *
  468. */
  469. function find($args)
  470. {
  471. if (!is_array($args)) {
  472. $args = preg_split('/\s+/', $args, -1, PREG_SPLIT_NO_EMPTY);
  473. }
  474. $dir = array_shift($args);
  475. $patterns = array();
  476. $depth = 0;
  477. $do_files = $do_dirs = true;
  478. for ($i = 0; $i < count($args); $i++) {
  479. switch ($args[$i]) {
  480. case '-type':
  481. if (in_array($args[$i+1], array('d', 'f'))) {
  482. if ($args[$i+1] == 'd') {
  483. $do_files = false;
  484. } else {
  485. $do_dirs = false;
  486. }
  487. }
  488. $i++;
  489. break;
  490. case '-name':
  491. $patterns[] = "(" . preg_replace(array('/\./', '/\*/'),
  492. array('\.', '.*'),
  493. $args[$i+1])
  494. . ")";
  495. $i++;
  496. break;
  497. case '-maxdepth':
  498. $depth = $args[$i+1];
  499. break;
  500. }
  501. }
  502. $path = System::_dirToStruct($dir, $depth);
  503. if ($do_files && $do_dirs) {
  504. $files = array_merge($path['files'], $path['dirs']);
  505. } elseif ($do_dirs) {
  506. $files = $path['dirs'];
  507. } else {
  508. $files = $path['files'];
  509. }
  510. if (count($patterns)) {
  511. $patterns = implode('|', $patterns);
  512. $ret = array();
  513. for ($i = 0; $i < count($files); $i++) {
  514. if (preg_match("#^$patterns\$#", $files[$i])) {
  515. $ret[] = $files[$i];
  516. }
  517. }
  518. return $ret;
  519. }
  520. return $files;
  521. }
  522. }
  523. ?>