You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

532 lines
17 KiB

24 years ago
  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 2.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$
  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$
  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. $mode = $opt[1];
  221. }
  222. }
  223. $ret = true;
  224. if (isset($create_parents)) {
  225. foreach($opts[1] as $dir) {
  226. $dirstack = array();
  227. while (!@is_dir($dir) && $dir != DIRECTORY_SEPARATOR) {
  228. array_unshift($dirstack, $dir);
  229. $dir = dirname($dir);
  230. }
  231. while ($newdir = array_shift($dirstack)) {
  232. if (!call_user_func('mkdir', $newdir, $mode)) {
  233. $ret = false;
  234. }
  235. }
  236. }
  237. } else {
  238. foreach($opts[1] as $dir) {
  239. if (!@is_dir($dir) && !call_user_func('mkdir', $dir, $mode)) {
  240. $ret = false;
  241. }
  242. }
  243. }
  244. return $ret;
  245. }
  246. /**
  247. * Concatenate files
  248. *
  249. * Usage:
  250. * 1) $var = System::cat('sample.txt test.txt');
  251. * 2) System::cat('sample.txt test.txt > final.txt');
  252. * 3) System::cat('sample.txt test.txt >> final.txt');
  253. *
  254. * Note: as the class use fopen, urls should work also (test that)
  255. *
  256. * @param string $args the arguments
  257. * @return boolean true on success
  258. * @access public
  259. */
  260. function &cat($args)
  261. {
  262. $ret = null;
  263. $files = array();
  264. if (!is_array($args)) {
  265. $args = preg_split('/\s+/', $args);
  266. }
  267. for($i=0; $i < count($args); $i++) {
  268. if ($args[$i] == '>') {
  269. $mode = 'wb';
  270. $outputfile = $args[$i+1];
  271. break;
  272. } elseif ($args[$i] == '>>') {
  273. $mode = 'ab+';
  274. $outputfile = $args[$i+1];
  275. break;
  276. } else {
  277. $files[] = $args[$i];
  278. }
  279. }
  280. if (isset($mode)) {
  281. if (!$outputfd = fopen($outputfile, $mode)) {
  282. $err = System::raiseError("Could not open $outputfile");
  283. return $err;
  284. }
  285. $ret = true;
  286. }
  287. foreach ($files as $file) {
  288. if (!$fd = fopen($file, 'r')) {
  289. System::raiseError("Could not open $file");
  290. continue;
  291. }
  292. while ($cont = fread($fd, 2048)) {
  293. if (isset($outputfd)) {
  294. fwrite($outputfd, $cont);
  295. } else {
  296. $ret .= $cont;
  297. }
  298. }
  299. fclose($fd);
  300. }
  301. if (@is_resource($outputfd)) {
  302. fclose($outputfd);
  303. }
  304. return $ret;
  305. }
  306. /**
  307. * Creates temporary files or directories. This function will remove
  308. * the created files when the scripts finish its execution.
  309. *
  310. * Usage:
  311. * 1) $tempfile = System::mktemp("prefix");
  312. * 2) $tempdir = System::mktemp("-d prefix");
  313. * 3) $tempfile = System::mktemp();
  314. * 4) $tempfile = System::mktemp("-t /var/tmp prefix");
  315. *
  316. * prefix -> The string that will be prepended to the temp name
  317. * (defaults to "tmp").
  318. * -d -> A temporary dir will be created instead of a file.
  319. * -t -> The target dir where the temporary (file|dir) will be created. If
  320. * this param is missing by default the env vars TMP on Windows or
  321. * TMPDIR in Unix will be used. If these vars are also missing
  322. * c:\windows\temp or /tmp will be used.
  323. *
  324. * @param string $args The arguments
  325. * @return mixed the full path of the created (file|dir) or false
  326. * @see System::tmpdir()
  327. * @access public
  328. */
  329. function mktemp($args = null)
  330. {
  331. static $first_time = true;
  332. $opts = System::_parseArgs($args, 't:d');
  333. if (PEAR::isError($opts)) {
  334. return System::raiseError($opts);
  335. }
  336. foreach($opts[0] as $opt) {
  337. if($opt[0] == 'd') {
  338. $tmp_is_dir = true;
  339. } elseif($opt[0] == 't') {
  340. $tmpdir = $opt[1];
  341. }
  342. }
  343. $prefix = (isset($opts[1][0])) ? $opts[1][0] : 'tmp';
  344. if (!isset($tmpdir)) {
  345. $tmpdir = System::tmpdir();
  346. }
  347. if (!System::mkDir("-p $tmpdir")) {
  348. return false;
  349. }
  350. $tmp = tempnam($tmpdir, $prefix);
  351. if (isset($tmp_is_dir)) {
  352. unlink($tmp); // be careful possible race condition here
  353. if (!call_user_func('mkdir', $tmp, 0700)) {
  354. return System::raiseError("Unable to create temporary directory $tmpdir");
  355. }
  356. }
  357. $GLOBALS['_System_temp_files'][] = $tmp;
  358. if ($first_time) {
  359. PEAR::registerShutdownFunc(array('System', '_removeTmpFiles'));
  360. $first_time = false;
  361. }
  362. return $tmp;
  363. }
  364. /**
  365. * Remove temporary files created my mkTemp. This function is executed
  366. * at script shutdown time
  367. *
  368. * @access private
  369. */
  370. function _removeTmpFiles()
  371. {
  372. if (count($GLOBALS['_System_temp_files'])) {
  373. $delete = $GLOBALS['_System_temp_files'];
  374. array_unshift($delete, '-r');
  375. System::rm($delete);
  376. }
  377. }
  378. /**
  379. * Get the path of the temporal directory set in the system
  380. * by looking in its environments variables.
  381. * Note: php.ini-recommended removes the "E" from the variables_order setting,
  382. * making unavaible the $_ENV array, that s why we do tests with _ENV
  383. *
  384. * @return string The temporal directory on the system
  385. */
  386. function tmpdir()
  387. {
  388. if (OS_WINDOWS) {
  389. if ($var = isset($_ENV['TEMP']) ? $_ENV['TEMP'] : getenv('TEMP')) {
  390. return $var;
  391. }
  392. if ($var = isset($_ENV['TMP']) ? $_ENV['TMP'] : getenv('TMP')) {
  393. return $var;
  394. }
  395. if ($var = isset($_ENV['windir']) ? $_ENV['windir'] : getenv('windir')) {
  396. return $var;
  397. }
  398. return getenv('SystemRoot') . '\temp';
  399. }
  400. if ($var = isset($_ENV['TMPDIR']) ? $_ENV['TMPDIR'] : getenv('TMPDIR')) {
  401. return $var;
  402. }
  403. return '/tmp';
  404. }
  405. /**
  406. * The "which" command (show the full path of a command)
  407. *
  408. * @param string $program The command to search for
  409. * @return mixed A string with the full path or false if not found
  410. * @author Stig Bakken <ssb@php.net>
  411. */
  412. function which($program, $fallback = false)
  413. {
  414. // is_executable() is not available on windows
  415. if (OS_WINDOWS) {
  416. $pear_is_executable = 'is_file';
  417. } else {
  418. $pear_is_executable = 'is_executable';
  419. }
  420. // full path given
  421. if (basename($program) != $program) {
  422. return (@$pear_is_executable($program)) ? $program : $fallback;
  423. }
  424. // XXX FIXME honor safe mode
  425. $path_delim = OS_WINDOWS ? ';' : ':';
  426. $exe_suffixes = OS_WINDOWS ? array('.exe','.bat','.cmd','.com') : array('');
  427. $path_elements = explode($path_delim, getenv('PATH'));
  428. foreach ($exe_suffixes as $suff) {
  429. foreach ($path_elements as $dir) {
  430. $file = $dir . DIRECTORY_SEPARATOR . $program . $suff;
  431. if (@is_file($file) && @$pear_is_executable($file)) {
  432. return $file;
  433. }
  434. }
  435. }
  436. return $fallback;
  437. }
  438. /**
  439. * The "find" command
  440. *
  441. * Usage:
  442. *
  443. * System::find($dir);
  444. * System::find("$dir -type d");
  445. * System::find("$dir -type f");
  446. * System::find("$dir -name *.php");
  447. * System::find("$dir -name *.php -name *.htm*");
  448. * System::find("$dir -maxdepth 1");
  449. *
  450. * Params implmented:
  451. * $dir -> Start the search at this directory
  452. * -type d -> return only directories
  453. * -type f -> return only files
  454. * -maxdepth <n> -> max depth of recursion
  455. * -name <pattern> -> search pattern (bash style). Multiple -name param allowed
  456. *
  457. * @param mixed Either array or string with the command line
  458. * @return array Array of found files
  459. *
  460. */
  461. function find($args)
  462. {
  463. if (!is_array($args)) {
  464. $args = preg_split('/\s+/', $args, -1, PREG_SPLIT_NO_EMPTY);
  465. }
  466. $dir = array_shift($args);
  467. $patterns = array();
  468. $depth = 0;
  469. $do_files = $do_dirs = true;
  470. for ($i = 0; $i < count($args); $i++) {
  471. switch ($args[$i]) {
  472. case '-type':
  473. if (in_array($args[$i+1], array('d', 'f'))) {
  474. if ($args[$i+1] == 'd') {
  475. $do_files = false;
  476. } else {
  477. $do_dirs = false;
  478. }
  479. }
  480. $i++;
  481. break;
  482. case '-name':
  483. $patterns[] = "(" . preg_replace(array('/\./', '/\*/'),
  484. array('\.', '.*'),
  485. $args[$i+1])
  486. . ")";
  487. $i++;
  488. break;
  489. case '-maxdepth':
  490. $depth = $args[$i+1];
  491. break;
  492. }
  493. }
  494. $path = System::_dirToStruct($dir, $depth);
  495. if ($do_files && $do_dirs) {
  496. $files = array_merge($path['files'], $path['dirs']);
  497. } elseif ($do_dirs) {
  498. $files = $path['dirs'];
  499. } else {
  500. $files = $path['files'];
  501. }
  502. if (count($patterns)) {
  503. $patterns = implode('|', $patterns);
  504. $ret = array();
  505. for ($i = 0; $i < count($files); $i++) {
  506. if (preg_match("#^$patterns\$#", $files[$i])) {
  507. $ret[] = $files[$i];
  508. }
  509. }
  510. return $ret;
  511. }
  512. return $files;
  513. }
  514. }
  515. ?>