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.

531 lines
17 KiB

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