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.

449 lines
14 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 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. Note that we use call_user_func('mkdir') to avoid
  198. * a problem with ZE2 calling System::mkDir instead of the native PHP func.
  199. *
  200. * @param string $args the name of the director(y|ies) to create
  201. * @return bool True for success
  202. * @access public
  203. */
  204. function mkDir($args)
  205. {
  206. $opts = System::_parseArgs($args, 'pm:');
  207. if (PEAR::isError($opts)) {
  208. return System::raiseError($opts);
  209. }
  210. $mode = 0777; // default mode
  211. foreach($opts[0] as $opt) {
  212. if ($opt[0] == 'p') {
  213. $create_parents = true;
  214. } elseif($opt[0] == 'm') {
  215. $mode = $opt[1];
  216. }
  217. }
  218. $ret = true;
  219. if (isset($create_parents)) {
  220. foreach($opts[1] as $dir) {
  221. $dirstack = array();
  222. while (!@is_dir($dir) && $dir != DIRECTORY_SEPARATOR) {
  223. array_unshift($dirstack, $dir);
  224. $dir = dirname($dir);
  225. }
  226. while ($newdir = array_shift($dirstack)) {
  227. if (!call_user_func('mkdir', $newdir, $mode)) {
  228. $ret = false;
  229. }
  230. }
  231. }
  232. } else {
  233. foreach($opts[1] as $dir) {
  234. if (!@is_dir($dir) && !call_user_func('mkdir', $dir, $mode)) {
  235. $ret = false;
  236. }
  237. }
  238. }
  239. return $ret;
  240. }
  241. /**
  242. * Concatenate files
  243. *
  244. * Usage:
  245. * 1) $var = System::cat('sample.txt test.txt');
  246. * 2) System::cat('sample.txt test.txt > final.txt');
  247. * 3) System::cat('sample.txt test.txt >> final.txt');
  248. *
  249. * Note: as the class use fopen, urls should work also (test that)
  250. *
  251. * @param string $args the arguments
  252. * @return boolean true on success
  253. * @access public
  254. */
  255. function &cat($args)
  256. {
  257. $ret = null;
  258. $files = array();
  259. if (!is_array($args)) {
  260. $args = preg_split('/\s+/', $args);
  261. }
  262. for($i=0; $i < count($args); $i++) {
  263. if ($args[$i] == '>') {
  264. $mode = 'wb';
  265. $outputfile = $args[$i+1];
  266. break;
  267. } elseif ($args[$i] == '>>') {
  268. $mode = 'ab+';
  269. $outputfile = $args[$i+1];
  270. break;
  271. } else {
  272. $files[] = $args[$i];
  273. }
  274. }
  275. if (isset($mode)) {
  276. if (!$outputfd = fopen($outputfile, $mode)) {
  277. return System::raiseError("Could not open $outputfile");
  278. }
  279. $ret = true;
  280. }
  281. foreach ($files as $file) {
  282. if (!$fd = fopen($file, 'r')) {
  283. System::raiseError("Could not open $file");
  284. continue;
  285. }
  286. while ($cont = fread($fd, 2048)) {
  287. if (isset($outputfd)) {
  288. fwrite($outputfd, $cont);
  289. } else {
  290. $ret .= $cont;
  291. }
  292. }
  293. fclose($fd);
  294. }
  295. if (@is_resource($outputfd)) {
  296. fclose($outputfd);
  297. }
  298. return $ret;
  299. }
  300. /**
  301. * Creates temporary files or directories. This function will remove
  302. * the created files when the scripts finish its execution.
  303. *
  304. * Usage:
  305. * 1) $tempfile = System::mktemp("prefix");
  306. * 2) $tempdir = System::mktemp("-d prefix");
  307. * 3) $tempfile = System::mktemp();
  308. * 4) $tempfile = System::mktemp("-t /var/tmp prefix");
  309. *
  310. * prefix -> The string that will be prepended to the temp name
  311. * (defaults to "tmp").
  312. * -d -> A temporary dir will be created instead of a file.
  313. * -t -> The target dir where the temporary (file|dir) will be created. If
  314. * this param is missing by default the env vars TMP on Windows or
  315. * TMPDIR in Unix will be used. If these vars are also missing
  316. * c:\windows\temp or /tmp will be used.
  317. *
  318. * @param string $args The arguments
  319. * @return mixed the full path of the created (file|dir) or false
  320. * @see System::tmpdir()
  321. * @access public
  322. */
  323. function mktemp($args = null)
  324. {
  325. static $first_time = true;
  326. $opts = System::_parseArgs($args, 't:d');
  327. if (PEAR::isError($opts)) {
  328. return System::raiseError($opts);
  329. }
  330. foreach($opts[0] as $opt) {
  331. if($opt[0] == 'd') {
  332. $tmp_is_dir = true;
  333. } elseif($opt[0] == 't') {
  334. $tmpdir = $opt[1];
  335. }
  336. }
  337. $prefix = (isset($opts[1][0])) ? $opts[1][0] : 'tmp';
  338. if (!isset($tmpdir)) {
  339. $tmpdir = System::tmpdir();
  340. }
  341. if (!System::mkDir("-p $tmpdir")) {
  342. return false;
  343. }
  344. $tmp = tempnam($tmpdir, $prefix);
  345. if (isset($tmp_is_dir)) {
  346. unlink($tmp); // be careful possible race condition here
  347. if (!call_user_func('mkdir', $tmp, 0700)) {
  348. return System::raiseError("Unable to create temporary directory $tmpdir");
  349. }
  350. }
  351. $GLOBALS['_System_temp_files'][] = $tmp;
  352. if ($first_time) {
  353. PEAR::registerShutdownFunc(array('System', '_removeTmpFiles'));
  354. $first_time = false;
  355. }
  356. return $tmp;
  357. }
  358. /**
  359. * Remove temporary files created my mkTemp. This function is executed
  360. * at script shutdown time
  361. *
  362. * @access private
  363. */
  364. function _removeTmpFiles()
  365. {
  366. if (count($GLOBALS['_System_temp_files'])) {
  367. $delete = $GLOBALS['_System_temp_files'];
  368. array_unshift($delete, '-r');
  369. System::rm($delete);
  370. }
  371. }
  372. /**
  373. * Get the path of the temporal directory set in the system
  374. * by looking in its environments variables.
  375. * Note: php.ini-recommended removes the "E" from the variables_order setting,
  376. * making unavaible the $_ENV array, that s why we do tests with _ENV
  377. *
  378. * @return string The temporal directory on the system
  379. */
  380. function tmpdir()
  381. {
  382. if (OS_WINDOWS) {
  383. if ($var = isset($_ENV['TEMP']) ? $_ENV['TEMP'] : getenv('TEMP')) {
  384. return $var;
  385. }
  386. if ($var = isset($_ENV['TMP']) ? $_ENV['TMP'] : getenv('TMP')) {
  387. return $var;
  388. }
  389. if ($var = isset($_ENV['windir']) ? $_ENV['windir'] : getenv('windir')) {
  390. return $var;
  391. }
  392. return getenv('SystemRoot') . '\temp';
  393. }
  394. if ($var = isset($_ENV['TMPDIR']) ? $_ENV['TMPDIR'] : getenv('TMPDIR')) {
  395. return $var;
  396. }
  397. return '/tmp';
  398. }
  399. /**
  400. * The "which" command (show the full path of a command)
  401. *
  402. * @param string $program The command to search for
  403. * @return mixed A string with the full path or false if not found
  404. * @author Stig Bakken <ssb@fast.no>
  405. */
  406. function which($program, $fallback = false)
  407. {
  408. // is_executable() is not available on windows
  409. if (OS_WINDOWS) {
  410. $pear_is_executable = 'is_file';
  411. } else {
  412. $pear_is_executable = 'is_executable';
  413. }
  414. // full path given
  415. if (basename($program) != $program) {
  416. return (@$pear_is_executable($program)) ? $program : $fallback;
  417. }
  418. // XXX FIXME honor safe mode
  419. $path_delim = OS_WINDOWS ? ';' : ':';
  420. $exe_suffixes = OS_WINDOWS ? array('.exe','.bat','.cmd','.com') : array('');
  421. $path_elements = explode($path_delim, getenv('PATH'));
  422. foreach ($exe_suffixes as $suff) {
  423. foreach ($path_elements as $dir) {
  424. $file = $dir . DIRECTORY_SEPARATOR . $program . $suff;
  425. if (@is_file($file) && @$pear_is_executable($file)) {
  426. return $file;
  427. }
  428. }
  429. }
  430. return $fallback;
  431. }
  432. }
  433. ?>