Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 23rd, 2012  |  syntax: None  |  size: 6.06 KB  |  hits: 6  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. <?php
  2.     class AppCmdShell
  3.     {
  4.         const OS_UNIX = 1;
  5.         const OS_WIN  = 2;
  6.  
  7.         /**
  8.          * Output produced by the last executed shell command.
  9.          *
  10.          * @var string
  11.          */
  12.         public $output = '';
  13.  
  14.         /**
  15.          * Result/exit code from the last executed shell command.
  16.          *
  17.          * @var int|null
  18.          */
  19.         public $result;
  20.  
  21.         /**
  22.          * Current OS. See OS_* constants.
  23.          *
  24.          * @var int
  25.          */
  26.         public $os;
  27.  
  28.         /**
  29.          * Get current work dir.
  30.          *
  31.          * @return string
  32.          * @throws AppCmdShellCommandFailedException
  33.          */
  34.         public function pwd()
  35.         {
  36.             $command = null;
  37.             if ($this->os == self::OS_WIN) {
  38.                 $command = 'echo %CD%';
  39.             }
  40.             else {
  41.                 $command = 'pwd';
  42.             }
  43.  
  44.             $this->execute($command);
  45.  
  46.             return rtrim($this->path($this->output, self::OS_UNIX), '/').'/';
  47.         }
  48.  
  49.         /**
  50.          * Just a reminder stub.
  51.          *
  52.          * @param string $dir
  53.          */
  54.         public function cd($dir)
  55.         {
  56.             throw new AppCheckException('Don\'t use cd in shell. It has no effect under PHP!');
  57.         }
  58.  
  59.         /**
  60.          * Execute a shell command.
  61.          * Saves output and result to $this->ouput and $this->result respectively.
  62.          *
  63.          * @param string $command               Command string to execute
  64.          *
  65.          * @param bool   $collectStdErrOuput    By default PHP returns contents of only STDOUT descriptor which is OK
  66.          *                                      for successful calls. But if some errors occured in the shell command
  67.          *                                      during its execution then in most of the cases STDOUT will be empty but
  68.          *                                      STDERR may be not. So pass true here if you want to receive STDERR
  69.          *                                      descriptor contents as well as STDOUT.
  70.          *
  71.          * @param bool   $checkExecutionResult  If true and command execution has failed (i.e. command reports an error)
  72.          *                                      then exception will be thrown
  73.          *
  74.          * @return int|null                     Command exit/result code
  75.          *                                      of null if something went worng with PHP (e.g. shell commands execution
  76.          *                                      is disabled by current PHP configuration).
  77.          *                                      Usually 0 means no errors while non-zero value represents code
  78.          *                                      of the error occurred.
  79.          *
  80.          * @throws AppCheckException            If shell command execution failed due to various reasons(related to PHP)
  81.          *                                      such as disabled exec() function and/or safe_mode enabled.
  82.          *
  83.          * @throws AppCmdShellCommandFailedException  If shell command execution failed and $checkExecutionResult is true.
  84.          */
  85.         public function execute($command, $collectStdErrOuput = true, $checkExecutionResult = true)
  86.         {
  87.             // Reseet last call data
  88.             $this->output = null;
  89.             $this->result = null;
  90.  
  91.             // Check for safe_mode enabled
  92.             if (ini_get('safe_mode')) {
  93.                 throw new AppCheckException('Could not execute a shell command: PHP safe mode is On.');
  94.             }
  95.  
  96.             // Some unix magic here ro redirect STDERR to STDOUT.
  97.             $stdErrRedirect = ($collectStdErrOuput ? " 2>&1" : '');
  98.  
  99.             // Remember last error occurred before exec(). So we can check whether exec() failed after its execution.
  100.             $lastError = error_get_last();
  101.  
  102.             // Execute
  103.             $output = array();
  104.             $result = null;
  105.             @exec("{$command}{$stdErrRedirect}", $output, $result);
  106.  
  107.             // Detect whether exec() has failed.
  108.             // Get current last error and compare with previously saved one.
  109.             // Note: safe_mode is not detected this way. We are checking for safe_mode enabled above.
  110.             $error = error_get_last();
  111.             if ($error != $lastError)
  112.             {
  113.                 throw new AppCheckException('Could not execute a shell command. Ensure PHP configuration allows '.
  114.                                             'running shell commands, e.g. exec() function is not disabled.');
  115.             }
  116.  
  117.             // Work with output
  118.             $output = join("\n", $output);
  119.  
  120.             // For the windows machine we need to convert cp866 -> utf-8 to be able to read Cyrillic output.
  121.             if (strtolower(substr(PHP_OS, 0, 3)) == 'win')
  122.             {
  123.                 if (function_exists('iconv')) {
  124.                     $output = iconv('cp866', 'utf-8', $output);
  125.                 }
  126.             }
  127.  
  128.             // Check for errors
  129.             if ($checkExecutionResult)
  130.             {
  131.                 if ($result != 0) {
  132.                     throw new AppCmdShellCommandFailedException($command, $output, $result);
  133.                 }
  134.             }
  135.  
  136.             // Store last call data
  137.             $this->output = $output;
  138.             $this->result = $result;
  139.  
  140.             // Done
  141.             return $result;
  142.         }
  143.  
  144.         public function escape($argument)
  145.         {
  146.             return escapeshellarg($argument);
  147.         }
  148.  
  149.         public function path($path, $targetOs = null)
  150.         {
  151.             if (!isset($targetOs)) {
  152.                 $targetOs = $this->os;
  153.             }
  154.  
  155.             if ($targetOs == self::OS_WIN) {
  156.                 $path = str_replace('/', '\\', $path);
  157.             }
  158.             else {
  159.                 $path = str_replace('\\', '/', $path);
  160.             }
  161.  
  162.             return $path;
  163.         }
  164.  
  165.         public function __construct()
  166.         {
  167.             $this->os = (substr(strtolower(PHP_OS), 0, 3) == 'win' ? self::OS_WIN : self::OS_UNIX);
  168.         }
  169.     }
  170. ?>