System_Command
[ class tree: System_Command ] [ index: System_Command ] [ all elements ]

Source for file Command.php

Documentation is available at Command.php

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

Documentation generated on Mon, 11 Mar 2019 15:47:25 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.