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: Command.php,v 1.8 2006/03/14 21:24:22 cconstantine Exp $
  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: 1.8 $
  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.         );
  153.  
  154.         // prepare the available control operators
  155.         $this->controlOperators = array(
  156.             'PIPE'  => '|',
  157.             'AND'   => '&&',
  158.             'OR'    => '||',
  159.             'GROUP' => ';',
  160.             'LFIFO' => '<',
  161.             'RFIFO' => '>',
  162.         );
  163.                 
  164.         // List of allowed/available shells
  165.         $this->shells = array(
  166.             'sh',
  167.             'bash',
  168.             'zsh',
  169.             'tcsh',
  170.             'csh',
  171.             'ash',
  172.             'sash',
  173.             'esh',
  174.             'ksh'
  175.         );
  176.                                    
  177.         // Find the first available shell
  178.         if (empty($this->options['SHELL'])) {
  179.             foreach ($this->shells as $shell{
  180.                 if ($this->options['SHELL'$this->which($shell)) {
  181.                     break;
  182.                 }
  183.             }
  184.  
  185.             // see if we still have no shell
  186.             if (empty($this->options['SHELL'])) {
  187.                 $this->_initError =PEAR::raiseError(nullSYSTEM_COMMAND_NO_SHELLnullE_USER_WARNINGnull'System_Command_Error'true);
  188.                 return;
  189.             }
  190.         }
  191.  
  192.         // Caputre a temporary directory for capturing stderr from commands
  193.         $this->tmpdir = System::tmpdir();
  194.         if (!System::mkDir("-p {$this->tmpdir}")) {
  195.             $this->_initError =PEAR::raiseError(nullSYSTEM_COMMAND_TMPDIR_ERRORnullE_USER_WARNINGnull'System_Command_Error'true);
  196.             return;
  197.         }
  198.     }
  199.         
  200.     // }}}
  201.     // {{{ setOption()
  202.     /**
  203.      * Sets the value for an option. Each option should be set to true
  204.      * or false; except the 'SHELL' option which should be a string
  205.      * naming a shell. The options are:
  206.      * 
  207.      * 'SEQUENCE'   Allow a sequence command or not (right now this is always on);
  208.      *
  209.      * 'SHUTDOWN'   Execute commands via a shutdown function;
  210.      *
  211.      * 'SHELL'      Path to shell;
  212.      *
  213.      * 'OUTPUT'     Output stdout from process;
  214.      *
  215.      * 'NOHUP'      Use nohup to detach process;
  216.      *
  217.      * 'BACKGROUND' Run as a background process with &;
  218.      *
  219.      * 'STDERR'     Output on stderr will raise an error, even if
  220.      *              the command's exit value is zero. The output from
  221.      *              stderr can be retrieved using the getDebugInfo()
  222.      *              method of the Pear_ERROR object returned by
  223.      *              execute().;
  224.      *
  225.      * @param string $in_option is a case-sensitive string,
  226.      *                          corresponding to the option
  227.      *                          that should be changed
  228.      * @param mixed $in_setting is the new value for the option
  229.      * @access public
  230.      * @return bool true if succes, else false
  231.      */
  232.     function setOption($in_option, $in_setting)
  233.     {
  234.         if ($this->_initError{
  235.             return $this->_initError;
  236.         }
  237.  
  238.         $option = strtoupper($in_option);
  239.  
  240.         if (!isset($this->options[$option])) {
  241.             PEAR::raiseError(null, SYSTEM_COMMAND_ERROR, null, E_USER_NOTICE, null, 'System_Command_Error', true);
  242.             return false;
  243.         }
  244.                 
  245.         switch ($option) {
  246.             case 'OUTPUT':
  247.             case 'SHUTDOWN':
  248.             case 'SEQUENCE':
  249.             case 'BACKGROUND':
  250.             case 'STDERR':
  251.                 $this->options[$option!empty($in_setting);
  252.                 return true;
  253.             break;
  254.                 
  255.             case 'SHELL':
  256.                 if (($shell $this->which($in_setting)) !== false{
  257.                     $this->options[$option$shell;
  258.                     return true;
  259.                 } 
  260.                 else {
  261.                     PEAR::raiseError(null, SYSTEM_COMMAND_NO_SHELL, null, E_USER_NOTICE, $in_setting, 'System_Command_Error', true);
  262.                     return false;
  263.                 }
  264.             break;
  265.                         
  266.             case 'NOHUP':
  267.                 if (empty($in_setting)) {
  268.                     $this->options[$option= false;
  269.                 } 
  270.                 else if ($location = $this->which('nohup')) {
  271.                     $this->options[$option$location;
  272.                 } 
  273.                 else {
  274.                     PEAR::raiseError(null, SYSTEM_COMMAND_NOHUP_MISSING, null, E_USER_NOTICE, null, 'System_Command_Error', true);
  275.                     return false;
  276.                 }
  277.             break;
  278.         }
  279.     }
  280.     
  281.     // }}}
  282.     // {{{ pushCommand()
  283.     /**
  284.      * Used to push a command onto the running command to be executed
  285.      *
  286.      * @param  string $in_command binary to be run
  287.      * @param  string $in_argument either an option or argument value, to be handled appropriately
  288.      * @param  string $in_argument
  289.      * @param  ...
  290.      *
  291.      * @access public
  292.      * @return boolean true on success {or System_Command_Error Exception}
  293.      */
  294.     function pushCommand($in_command)
  295.     {
  296.         if ($this->_initError{
  297.             return $this->_initError;
  298.         }
  299.         
  300.         if (!is_null($this->previousElement&& !in_array($this->previousElement$this->controlOperators)) {
  301.             $this->commandStatus = -1;
  302.             $error = PEAR::raiseError(nullSYSTEM_COMMAND_COMMAND_PLACEMENTnullE_USER_WARNINGnull'System_Command_Error'true);
  303.         }
  304.  
  305.         // check for error here
  306.         $command = escapeshellcmd($this->which($in_command));
  307.         if ($command === false{
  308.             $error = PEAR::raiseError(null, SYSTEM_COMMAND_INVALID_COMMAND, null, E_USER_WARNING, null, 'System_Command_Error', true);
  309.         }
  310.  
  311.         $argv = func_get_args();
  312.         array_shift($argv);
  313.         foreach($argv as $arg) {
  314.             if (strpos($arg, '-') === 0) {
  315.                 $command .= ' ' . $arg
  316.             }
  317.             elseif ($arg != '') {
  318.                 $command .= ' ' . escapeshellarg($arg);
  319.             }
  320.         }
  321.  
  322.         $this->previousElement $command;
  323.         $this->systemCommand .= $command;
  324.  
  325.         return isset($error$error : true;
  326.     }
  327.  
  328.     // }}}
  329.     // {{{ pushOperator()
  330.     /**
  331.      * Used to push an operator onto the running command to be executed
  332.      *
  333.      * @param  string $in_operator Either string reprentation of operator or system character
  334.      *
  335.      * @access public
  336.      * @return boolean true on success {or System_Command_Error Exception}
  337.      */
  338.     function pushOperator($in_operator)
  339.     {
  340.         if ($this->_initError{
  341.             return $this->_initError;
  342.         }
  343.  
  344.         $operator = isset($this->controlOperators[$in_operator]$this->controlOperators[$in_operator$in_operator;
  345.  
  346.         if (is_null($this->previousElement|| in_array($this->previousElement$this->controlOperators)) {
  347.             $this->commandStatus = -1;
  348.             $error = PEAR::raiseError(nullSYSTEM_COMMAND_OPERATOR_PLACEMENTnullE_USER_WARNINGnull'System_Command_Error'true);
  349.         }
  350.         elseif (!in_array($operator, $this->controlOperators)) {
  351.             $this->commandStatus = -1;
  352.             $error = PEAR::raiseError(nullSYSTEM_COMMAND_INVALID_OPERATORnullE_USER_WARNING$operator'System_Command_Error'true);
  353.         }
  354.  
  355.         $this->previousElement $operator;
  356.         $this->systemCommand .= ' ' $operator ' ';
  357.         return isset($error$error : true;
  358.     }
  359.  
  360.     // }}}
  361.     // {{{ execute()
  362.     /**
  363.      * Executes the code according to given options
  364.      *
  365.      * @return bool true if success {or System_Command_Exception}
  366.      *
  367.      * @access public
  368.      */
  369.     function execute() 
  370.     {
  371.         if ($this->_initError{
  372.             return $this->_initError;
  373.         }
  374.  
  375.         // if the command is empty or if the last element was a control operator, we can't continue
  376.         if (is_null($this->previousElement|| $this->commandStatus == -1 || in_array($this->previousElement$this->controlOperators)) {
  377.             return PEAR::raiseError(null, SYSTEM_COMMAND_INVALID_COMMAND, null, E_USER_WARNING, $this->systemCommand'System_Command_Error'true);
  378.         }
  379.  
  380.         // Warning about impossible mix of options
  381.         if (!empty($this->options['OUTPUT'])) {
  382.             if (!empty($this->options['SHUTDOWN']|| !empty($this->options['NOHUP'])) {
  383.                 return PEAR::raiseError(null, SYSTEM_COMMAND_NO_OUTPUT, null, E_USER_WARNING, null, 'System_Command_Error', true);
  384.             }
  385.         }
  386.                 
  387.         // if this is not going to stdout, then redirect to /dev/null
  388.         if (empty($this->options['OUTPUT'])) {
  389.             $this->systemCommand .= ' >/dev/null';
  390.         }
  391.                 
  392.         $suffix = '';
  393.         // run a command immune to hangups, with output to a non-tty
  394.         if (!empty($this->options['NOHUP'])) {
  395.             $this->systemCommand $this->options['NOHUP'$this->systemCommand;
  396.         }
  397.         // run a background process (only if not nohup)
  398.         elseif (!empty($this->options['BACKGROUND'])) {
  399.             $suffix = ' &';
  400.         }
  401.                 
  402.         // Register to be run on shutdown
  403.         if (!empty($this->options['SHUTDOWN'])) {
  404.             $line = "system(\"{$this->systemCommand}$suffix\");";
  405.             $function = create_function('', $line);
  406.             register_shutdown_function($function);
  407.             return true;
  408.         } 
  409.         else {
  410.             // send stderr to a file so that we can reap the error message
  411.             $tmpFile = tempnam($this->tmpDir'System_Command-');
  412.             $this->systemCommand .= ' 2>' $tmpFile $suffix;
  413.             $shellPipe $this->which('echo'' ' . escapeshellarg($this->systemCommand' | ' $this->options['SHELL'];
  414.             exec($shellPipe$result$returnVal);
  415.  
  416.             if ($returnVal !== 0{
  417.                 // command returned nonzero; that's always an error
  418.                 $return = PEAR::raiseError(null, SYSTEM_COMMAND_NONZERO_EXIT, null, E_USER_WARNING, null, 'System_Command_Error', true);
  419.             }
  420.             else if (!$this->options['STDERR']{
  421.                 // caller does not care about stderr; return success
  422.                 $return = implode("\n", $result);
  423.             }
  424.             else {
  425.                 // our caller cares about stderr; check stderr output
  426.                 clearstatcache();
  427.                 if (filesize($tmpFile) > 0) {
  428.                     // the command actually wrote to stderr
  429.                     $stderr_output = file_get_contents($tmpFile);
  430.                     $return = PEAR::raiseError(null, SYSTEM_COMMAND_STDERR, null, E_USER_WARNING, $stderr_output, 'System_Command_Error', true);
  431.                 } else {
  432.                     // total success; return stdout gathered by exec()
  433.                     $return = implode("\n", $result);
  434.                 }
  435.             }
  436.  
  437.             unlink($tmpFile);
  438.             return $return;
  439.         }
  440.     }
  441.  
  442.     // }}}
  443.     // {{{ which()
  444.     /**
  445.      * Functionality similiar to unix 'which'. Searches the path
  446.      * for the specified program. 
  447.      *
  448.      * @param $cmd name of the executable to search for 
  449.      *
  450.      * @access private
  451.      * @return string returns the full path if found, false if not
  452.      */
  453.     function which($in_cmd)
  454.     {
  455.         // only pass non-empty strings to System::which()
  456.         if (!is_string($in_cmd) || '' === $in_cmd) {
  457.             return(false);
  458.         }
  459.  
  460.         // explicitly pass false as fallback value
  461.         return System::which($in_cmd, false);
  462.     }   
  463.  
  464.     // }}}
  465.     // {{{ reset()
  466.     /**
  467.      * Prepare for a new command to be built
  468.      *
  469.      * @access public
  470.      * @return void
  471.      */
  472.     function reset()
  473.     {
  474.         $this->previousElement = null;
  475.         $this->systemCommand = null;
  476.         $this->commandStatus = 0;
  477.     }
  478.  
  479.     // }}}
  480.     // {{{ errorMessage()
  481.     /**
  482.      * Return a textual error message for a System_Command error code
  483.      *
  484.      * @param integer error code
  485.      *
  486.      * @return string error message, or false if the error code was
  487.      * not recognized
  488.      */
  489.     function errorMessage($in_value)
  490.     {
  491.         static $errorMessages;
  492.         if (!isset($errorMessages)) {
  493.             $errorMessages = array(
  494.                 SYSTEM_COMMAND_OK                     => 'no error',
  495.                 SYSTEM_COMMAND_ERROR                  => 'unknown error',
  496.                 SYSTEM_COMMAND_NO_SHELL               => 'no shell found',
  497.                 SYSTEM_COMMAND_INVALID_SHELL          => 'invalid shell',
  498.                 SYSTEM_COMMAND_TMPDIR_ERROR           => 'could not create temporary directory',
  499.                 SYSTEM_COMMAND_INVALID_OPERATOR       => 'control operator invalid',
  500.                 SYSTEM_COMMAND_INVALID_COMMAND        => 'invalid system command',
  501.                 SYSTEM_COMMAND_OPERATOR_PLACEMENT     => 'invalid placement of control operator',
  502.                 SYSTEM_COMMAND_COMMAND_PLACEMENT      => 'invalid placement of command',
  503.                 SYSTEM_COMMAND_NOHUP_MISSING          => 'nohup not found on system',
  504.                 SYSTEM_COMMAND_NO_OUTPUT              => 'output not allowed',
  505.                 SYSTEM_COMMAND_STDERR                 => 'command wrote to stderr',
  506.                 SYSTEM_COMMAND_NONZERO_EXIT           => 'non-zero exit value from command',
  507.             );
  508.         }
  509.  
  510.         if (System_Command::isError($in_value)) {
  511.             $in_value = $in_value->getCode();
  512.         }
  513.  
  514.         return isset($errorMessages[$in_value]) ? $errorMessages[$in_value] : $errorMessages[SYSTEM_COMMAND_ERROR];
  515.     }
  516.  
  517.     // }}}
  518.     // {{{ isError()
  519.     /**
  520.      * Tell whether a result code from a System_Command method is an error
  521.      *
  522.      * @param int result code
  523.      *
  524.      * @return bool whether $in_value is an error
  525.      *
  526.      * @access public
  527.      */
  528.     function isError($in_value)
  529.     {
  530.         return (is_object($in_value) &&
  531.                 (strtolower(get_class($in_value)) == 'system_command_error' ||
  532.                  is_subclass_of($in_value, 'system_command_error')));
  533.     }
  534.     
  535.     // }}}
  536. }
  537.  
  538. // {{{ class System_Command_Error
  539. /**
  540.  * System_Command_Error constructor.
  541.  *
  542.  * @param mixed      System_Command error code, or string with error message.
  543.  * @param integer    what "error mode" to operate in
  544.  * @param integer    what error level to use for $mode & PEAR_ERROR_TRIGGER
  545.  * @param mixed      additional debug info, such as the last query
  546.  *
  547.  * @access public
  548.  *
  549.  * @see PEAR_Error
  550.  */
  551.  
  552. // }}}
  553. class System_Command_Error extends PEAR_Error
  554. {
  555.     // {{{ properties
  556.     /**
  557.      * Message in front of the error message
  558.      * @var string $error_message_prefix
  559.      */
  560.     var $error_message_prefix = 'System_Command Error: ';
  561.  
  562.     // }}}
  563.     // {{{ constructor
  564.     function System_Command_Error($code = SYSTEM_COMMAND_ERROR, $mode = PEAR_ERROR_RETURN,
  565.               $level = E_USER_NOTICE, $debuginfo = null)
  566.     {
  567.         if (is_int($code)) {
  568.             $this->PEAR_Error(System_Command::errorMessage($code)$code$mode$level$debuginfo);
  569.         } else {
  570.             $this->PEAR_Error("Invalid error code: $code", SYSTEM_COMMAND_ERROR, $mode, $level, $debuginfo);
  571.         }
  572.     }
  573.     
  574.     // }}}
  575. }

Documentation generated on Mon, 11 Mar 2019 14:38:24 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.