Command.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. <?php
  2. // {{{ license
  3. // +----------------------------------------------------------------------+
  4. // | PHP Version 4.0 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1997-2003 The PHP Group |
  7. // +----------------------------------------------------------------------+
  8. // | This source file is subject to version 2.02 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. // | Author: Anders Johannsen <anders@johannsen.com> |
  17. // | Author: Dan Allen <dan@mojavelinux.com>
  18. // +----------------------------------------------------------------------+
  19. // $Id: Command.php,v 1.9 2007/04/20 21:08:48 cconstantine Exp $
  20. // }}}
  21. // {{{ includes
  22. require_once 'PEAR.php';
  23. require_once 'System.php';
  24. // }}}
  25. // {{{ constants
  26. define('SYSTEM_COMMAND_OK', 1);
  27. define('SYSTEM_COMMAND_ERROR', -1);
  28. define('SYSTEM_COMMAND_NO_SHELL', -2);
  29. define('SYSTEM_COMMAND_INVALID_SHELL', -3);
  30. define('SYSTEM_COMMAND_TMPDIR_ERROR', -4);
  31. define('SYSTEM_COMMAND_INVALID_OPERATOR', -5);
  32. define('SYSTEM_COMMAND_INVALID_COMMAND', -6);
  33. define('SYSTEM_COMMAND_OPERATOR_PLACEMENT',-7);
  34. define('SYSTEM_COMMAND_COMMAND_PLACEMENT', -8);
  35. define('SYSTEM_COMMAND_NOHUP_MISSING', -9);
  36. define('SYSTEM_COMMAND_NO_OUTPUT', -10);
  37. define('SYSTEM_COMMAND_STDERR', -11);
  38. define('SYSTEM_COMMAND_NONZERO_EXIT', -12);
  39. // }}}
  40. // {{{ class System_Command
  41. /**
  42. * The System_Command:: class implements an abstraction for various ways
  43. * of executing commands (directly using the backtick operator,
  44. * as a background task after the script has terminated using
  45. * register_shutdown_function() or as a detached process using nohup).
  46. *
  47. * @author Anders Johannsen <anders@johannsen.com>
  48. * @author Dan Allen <dan@mojavelinux.com>
  49. * @version $Revision: 1.9 $
  50. */
  51. // }}}
  52. class System_Command {
  53. // {{{ properties
  54. /**
  55. * Array of settings used when creating the shell command
  56. *
  57. * @var array
  58. * @access private
  59. */
  60. var $options = array();
  61. /**
  62. * Array of available shells to use to execute the command
  63. *
  64. * @var array
  65. * @access private
  66. */
  67. var $shells = array();
  68. /**
  69. * Array of available control operators used between commands
  70. *
  71. * @var array
  72. * @access private
  73. */
  74. var $controlOperators = array();
  75. /**
  76. * The system command to be executed
  77. *
  78. * @var string
  79. * @access private
  80. */
  81. var $systemCommand = null;
  82. /**
  83. * Previously added part to the command string
  84. *
  85. * @var string
  86. * @access private
  87. */
  88. var $previousElement = null;
  89. /**
  90. * Directory for writing stderr output
  91. *
  92. * @var string
  93. * @access private
  94. */
  95. var $tmpDir = null;
  96. /**
  97. * To allow the pear error object to accumulate when building
  98. * the command, we use the command status to keep track when
  99. * a pear error is raised
  100. *
  101. * @var int
  102. * @access private
  103. */
  104. var $commandStatus = 0;
  105. /**
  106. * Hold initialization PEAR_Error
  107. *
  108. * @var object
  109. * @access private
  110. **/
  111. var $_initError = null;
  112. // }}}
  113. // {{{ constructor
  114. /**
  115. * Class constructor
  116. *
  117. * Defines all necessary constants and sets defaults
  118. *
  119. * @access public
  120. */
  121. function System_Command($in_shell = null)
  122. {
  123. // Defining constants
  124. $this->options = array(
  125. 'SEQUENCE' => true,
  126. 'SHUTDOWN' => false,
  127. 'SHELL' => $this->which($in_shell),
  128. 'OUTPUT' => true,
  129. 'NOHUP' => false,
  130. 'BACKGROUND' => false,
  131. 'STDERR' => false
  132. );
  133. // prepare the available control operators
  134. $this->controlOperators = array(
  135. 'PIPE' => '|',
  136. 'AND' => '&&',
  137. 'OR' => '||',
  138. 'GROUP' => ';',
  139. 'LFIFO' => '<',
  140. 'RFIFO' => '>',
  141. );
  142. // List of allowed/available shells
  143. $this->shells = array(
  144. 'sh',
  145. 'bash',
  146. 'zsh',
  147. 'tcsh',
  148. 'csh',
  149. 'ash',
  150. 'sash',
  151. 'esh',
  152. 'ksh'
  153. );
  154. // Find the first available shell
  155. if (empty($this->options['SHELL'])) {
  156. foreach ($this->shells as $shell) {
  157. if ($this->options['SHELL'] = $this->which($shell)) {
  158. break;
  159. }
  160. }
  161. // see if we still have no shell
  162. if (empty($this->options['SHELL'])) {
  163. $this->_initError =& PEAR::raiseError(null, SYSTEM_COMMAND_NO_SHELL, null, E_USER_WARNING, null, 'System_Command_Error', true);
  164. return;
  165. }
  166. }
  167. // Caputre a temporary directory for capturing stderr from commands
  168. $this->tmpDir = System::tmpdir();
  169. if (!System::mkDir("-p {$this->tmpDir}")) {
  170. $this->_initError =& PEAR::raiseError(null, SYSTEM_COMMAND_TMPDIR_ERROR, null, E_USER_WARNING, null, 'System_Command_Error', true);
  171. return;
  172. }
  173. }
  174. // }}}
  175. // {{{ setOption()
  176. /**
  177. * Sets the value for an option. Each option should be set to true
  178. * or false; except the 'SHELL' option which should be a string
  179. * naming a shell. The options are:
  180. *
  181. * 'SEQUENCE' Allow a sequence command or not (right now this is always on);
  182. *
  183. * 'SHUTDOWN' Execute commands via a shutdown function;
  184. *
  185. * 'SHELL' Path to shell;
  186. *
  187. * 'OUTPUT' Output stdout from process;
  188. *
  189. * 'NOHUP' Use nohup to detach process;
  190. *
  191. * 'BACKGROUND' Run as a background process with &;
  192. *
  193. * 'STDERR' Output on stderr will raise an error, even if
  194. * the command's exit value is zero. The output from
  195. * stderr can be retrieved using the getDebugInfo()
  196. * method of the Pear_ERROR object returned by
  197. * execute().;
  198. *
  199. * @param string $in_option is a case-sensitive string,
  200. * corresponding to the option
  201. * that should be changed
  202. * @param mixed $in_setting is the new value for the option
  203. * @access public
  204. * @return bool true if succes, else false
  205. */
  206. function setOption($in_option, $in_setting)
  207. {
  208. if ($this->_initError) {
  209. return $this->_initError;
  210. }
  211. $option = strtoupper($in_option);
  212. if (!isset($this->options[$option])) {
  213. PEAR::raiseError(null, SYSTEM_COMMAND_ERROR, null, E_USER_NOTICE, null, 'System_Command_Error', true);
  214. return false;
  215. }
  216. switch ($option) {
  217. case 'OUTPUT':
  218. case 'SHUTDOWN':
  219. case 'SEQUENCE':
  220. case 'BACKGROUND':
  221. case 'STDERR':
  222. $this->options[$option] = !empty($in_setting);
  223. return true;
  224. break;
  225. case 'SHELL':
  226. if (($shell = $this->which($in_setting)) !== false) {
  227. $this->options[$option] = $shell;
  228. return true;
  229. }
  230. else {
  231. PEAR::raiseError(null, SYSTEM_COMMAND_NO_SHELL, null, E_USER_NOTICE, $in_setting, 'System_Command_Error', true);
  232. return false;
  233. }
  234. break;
  235. case 'NOHUP':
  236. if (empty($in_setting)) {
  237. $this->options[$option] = false;
  238. }
  239. else if ($location = $this->which('nohup')) {
  240. $this->options[$option] = $location;
  241. }
  242. else {
  243. PEAR::raiseError(null, SYSTEM_COMMAND_NOHUP_MISSING, null, E_USER_NOTICE, null, 'System_Command_Error', true);
  244. return false;
  245. }
  246. break;
  247. }
  248. }
  249. // }}}
  250. // {{{ pushCommand()
  251. /**
  252. * Used to push a command onto the running command to be executed
  253. *
  254. * @param string $in_command binary to be run
  255. * @param string $in_argument either an option or argument value, to be handled appropriately
  256. * @param string $in_argument
  257. * @param ...
  258. *
  259. * @access public
  260. * @return boolean true on success {or System_Command_Error Exception}
  261. */
  262. function pushCommand($in_command)
  263. {
  264. if ($this->_initError) {
  265. return $this->_initError;
  266. }
  267. if (!is_null($this->previousElement) && !in_array($this->previousElement, $this->controlOperators)) {
  268. $this->commandStatus = -1;
  269. $error = PEAR::raiseError(null, SYSTEM_COMMAND_COMMAND_PLACEMENT, null, E_USER_WARNING, null, 'System_Command_Error', true);
  270. }
  271. // check for error here
  272. $command = escapeshellcmd($this->which($in_command));
  273. if ($command === false) {
  274. $error = PEAR::raiseError(null, SYSTEM_COMMAND_INVALID_COMMAND, null, E_USER_WARNING, null, 'System_Command_Error', true);
  275. }
  276. $argv = func_get_args();
  277. array_shift($argv);
  278. foreach($argv as $arg) {
  279. if (strpos($arg, '-') === 0) {
  280. $command .= ' ' . $arg;
  281. }
  282. elseif ($arg != '') {
  283. $command .= ' ' . escapeshellarg($arg);
  284. }
  285. }
  286. $this->previousElement = $command;
  287. $this->systemCommand .= $command;
  288. return isset($error) ? $error : true;
  289. }
  290. // }}}
  291. // {{{ pushOperator()
  292. /**
  293. * Used to push an operator onto the running command to be executed
  294. *
  295. * @param string $in_operator Either string reprentation of operator or system character
  296. *
  297. * @access public
  298. * @return boolean true on success {or System_Command_Error Exception}
  299. */
  300. function pushOperator($in_operator)
  301. {
  302. if ($this->_initError) {
  303. return $this->_initError;
  304. }
  305. $operator = isset($this->controlOperators[$in_operator]) ? $this->controlOperators[$in_operator] : $in_operator;
  306. if (is_null($this->previousElement) || in_array($this->previousElement, $this->controlOperators)) {
  307. $this->commandStatus = -1;
  308. $error = PEAR::raiseError(null, SYSTEM_COMMAND_OPERATOR_PLACEMENT, null, E_USER_WARNING, null, 'System_Command_Error', true);
  309. }
  310. elseif (!in_array($operator, $this->controlOperators)) {
  311. $this->commandStatus = -1;
  312. $error = PEAR::raiseError(null, SYSTEM_COMMAND_INVALID_OPERATOR, null, E_USER_WARNING, $operator, 'System_Command_Error', true);
  313. }
  314. $this->previousElement = $operator;
  315. $this->systemCommand .= ' ' . $operator . ' ';
  316. return isset($error) ? $error : true;
  317. }
  318. // }}}
  319. // {{{ execute()
  320. /**
  321. * Executes the code according to given options
  322. *
  323. * @return bool true if success {or System_Command_Exception}
  324. *
  325. * @access public
  326. */
  327. function execute()
  328. {
  329. if ($this->_initError) {
  330. return $this->_initError;
  331. }
  332. // if the command is empty or if the last element was a control operator, we can't continue
  333. if (is_null($this->previousElement) || $this->commandStatus == -1 || in_array($this->previousElement, $this->controlOperators)) {
  334. return PEAR::raiseError(null, SYSTEM_COMMAND_INVALID_COMMAND, null, E_USER_WARNING, $this->systemCommand, 'System_Command_Error', true);
  335. }
  336. // Warning about impossible mix of options
  337. if (!empty($this->options['OUTPUT'])) {
  338. if (!empty($this->options['SHUTDOWN']) || !empty($this->options['NOHUP'])) {
  339. return PEAR::raiseError(null, SYSTEM_COMMAND_NO_OUTPUT, null, E_USER_WARNING, null, 'System_Command_Error', true);
  340. }
  341. }
  342. // if this is not going to stdout, then redirect to /dev/null
  343. if (empty($this->options['OUTPUT'])) {
  344. $this->systemCommand .= ' >/dev/null';
  345. }
  346. $suffix = '';
  347. // run a command immune to hangups, with output to a non-tty
  348. if (!empty($this->options['NOHUP'])) {
  349. $this->systemCommand = $this->options['NOHUP'] . $this->systemCommand;
  350. }
  351. // run a background process (only if not nohup)
  352. elseif (!empty($this->options['BACKGROUND'])) {
  353. $suffix = ' &';
  354. }
  355. // Register to be run on shutdown
  356. if (!empty($this->options['SHUTDOWN'])) {
  357. $line = "system(\"{$this->systemCommand}$suffix\");";
  358. $function = create_function('', $line);
  359. register_shutdown_function($function);
  360. return true;
  361. }
  362. else {
  363. // send stderr to a file so that we can reap the error message
  364. $tmpFile = tempnam($this->tmpDir, 'System_Command-');
  365. $this->systemCommand .= ' 2>' . $tmpFile . $suffix;
  366. $shellPipe = $this->which('echo') . ' ' . escapeshellarg($this->systemCommand) . ' | ' . $this->options['SHELL'];
  367. exec($shellPipe, $result, $returnVal);
  368. if ($returnVal !== 0) {
  369. // command returned nonzero; that's always an error
  370. $return = PEAR::raiseError(null, SYSTEM_COMMAND_NONZERO_EXIT, null, E_USER_WARNING, null, 'System_Command_Error', true);
  371. }
  372. else if (!$this->options['STDERR']) {
  373. // caller does not care about stderr; return success
  374. $return = implode("\n", $result);
  375. }
  376. else {
  377. // our caller cares about stderr; check stderr output
  378. clearstatcache();
  379. if (filesize($tmpFile) > 0) {
  380. // the command actually wrote to stderr
  381. $stderr_output = file_get_contents($tmpFile);
  382. $return = PEAR::raiseError(null, SYSTEM_COMMAND_STDERR, null, E_USER_WARNING, $stderr_output, 'System_Command_Error', true);
  383. } else {
  384. // total success; return stdout gathered by exec()
  385. $return = implode("\n", $result);
  386. }
  387. }
  388. unlink($tmpFile);
  389. return $return;
  390. }
  391. }
  392. // }}}
  393. // {{{ which()
  394. /**
  395. * Functionality similiar to unix 'which'. Searches the path
  396. * for the specified program.
  397. *
  398. * @param $cmd name of the executable to search for
  399. *
  400. * @access private
  401. * @return string returns the full path if found, false if not
  402. */
  403. function which($in_cmd)
  404. {
  405. // only pass non-empty strings to System::which()
  406. if (!is_string($in_cmd) || '' === $in_cmd) {
  407. return(false);
  408. }
  409. // explicitly pass false as fallback value
  410. return System::which($in_cmd, false);
  411. }
  412. // }}}
  413. // {{{ reset()
  414. /**
  415. * Prepare for a new command to be built
  416. *
  417. * @access public
  418. * @return void
  419. */
  420. function reset()
  421. {
  422. $this->previousElement = null;
  423. $this->systemCommand = null;
  424. $this->commandStatus = 0;
  425. }
  426. // }}}
  427. // {{{ errorMessage()
  428. /**
  429. * Return a textual error message for a System_Command error code
  430. *
  431. * @param integer error code
  432. *
  433. * @return string error message, or false if the error code was
  434. * not recognized
  435. */
  436. function errorMessage($in_value)
  437. {
  438. static $errorMessages;
  439. if (!isset($errorMessages)) {
  440. $errorMessages = array(
  441. SYSTEM_COMMAND_OK => 'no error',
  442. SYSTEM_COMMAND_ERROR => 'unknown error',
  443. SYSTEM_COMMAND_NO_SHELL => 'no shell found',
  444. SYSTEM_COMMAND_INVALID_SHELL => 'invalid shell',
  445. SYSTEM_COMMAND_TMPDIR_ERROR => 'could not create temporary directory',
  446. SYSTEM_COMMAND_INVALID_OPERATOR => 'control operator invalid',
  447. SYSTEM_COMMAND_INVALID_COMMAND => 'invalid system command',
  448. SYSTEM_COMMAND_OPERATOR_PLACEMENT => 'invalid placement of control operator',
  449. SYSTEM_COMMAND_COMMAND_PLACEMENT => 'invalid placement of command',
  450. SYSTEM_COMMAND_NOHUP_MISSING => 'nohup not found on system',
  451. SYSTEM_COMMAND_NO_OUTPUT => 'output not allowed',
  452. SYSTEM_COMMAND_STDERR => 'command wrote to stderr',
  453. SYSTEM_COMMAND_NONZERO_EXIT => 'non-zero exit value from command',
  454. );
  455. }
  456. if (System_Command::isError($in_value)) {
  457. $in_value = $in_value->getCode();
  458. }
  459. return isset($errorMessages[$in_value]) ? $errorMessages[$in_value] : $errorMessages[SYSTEM_COMMAND_ERROR];
  460. }
  461. // }}}
  462. // {{{ isError()
  463. /**
  464. * Tell whether a result code from a System_Command method is an error
  465. *
  466. * @param int result code
  467. *
  468. * @return bool whether $in_value is an error
  469. *
  470. * @access public
  471. */
  472. function isError($in_value)
  473. {
  474. return (is_object($in_value) &&
  475. (strtolower(get_class($in_value)) == 'system_command_error' ||
  476. is_subclass_of($in_value, 'system_command_error')));
  477. }
  478. // }}}
  479. }
  480. // {{{ class System_Command_Error
  481. /**
  482. * System_Command_Error constructor.
  483. *
  484. * @param mixed System_Command error code, or string with error message.
  485. * @param integer what "error mode" to operate in
  486. * @param integer what error level to use for $mode & PEAR_ERROR_TRIGGER
  487. * @param mixed additional debug info, such as the last query
  488. *
  489. * @access public
  490. *
  491. * @see PEAR_Error
  492. */
  493. // }}}
  494. class System_Command_Error extends PEAR_Error
  495. {
  496. // {{{ properties
  497. /**
  498. * Message in front of the error message
  499. * @var string $error_message_prefix
  500. */
  501. var $error_message_prefix = 'System_Command Error: ';
  502. // }}}
  503. // {{{ constructor
  504. function System_Command_Error($code = SYSTEM_COMMAND_ERROR, $mode = PEAR_ERROR_RETURN,
  505. $level = E_USER_NOTICE, $debuginfo = null)
  506. {
  507. if (is_int($code)) {
  508. $this->PEAR_Error(System_Command::errorMessage($code), $code, $mode, $level, $debuginfo);
  509. } else {
  510. $this->PEAR_Error("Invalid error code: $code", SYSTEM_COMMAND_ERROR, $mode, $level, $debuginfo);
  511. }
  512. }
  513. // }}}
  514. }
  515. ?>