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.

435 lines
14 KiB

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