/** * Constructor. * * @param Horde_Vcs_Base $rep A repository object. * @param string $dn Path to the directory. * @param array $opts Any additional options: * * @throws Horde_Vcs_Exception */ public function __construct(Horde_Vcs_Base $rep, $dn, $opts = array()) { parent::__construct($rep, $dn, $opts); $cmd = $rep->getCommand() . ' ls ' . escapeshellarg($rep->sourceroot . $this->_dirName); $dir = proc_open($cmd, array(1 => array('pipe', 'w'), 2 => array('pipe', 'w')), $pipes); if (!$dir) { throw new Horde_Vcs_Exception('Failed to execute svn ls: ' . $cmd); } if ($error = stream_get_contents($pipes[2])) { proc_close($dir); throw new Horde_Vcs_Exception($error); } /* Create two arrays - one of all the files, and the other of all the * dirs. */ $errors = array(); while (!feof($pipes[1])) { $line = chop(fgets($pipes[1], 1024)); if (!strlen($line)) { continue; } if (substr($line, 0, 4) == 'svn:') { $errors[] = $line; } elseif (substr($line, -1) == '/') { $this->_dirs[] = substr($line, 0, -1); } else { $this->_files[] = $rep->getFile($this->_dirName . '/' . $line); } } proc_close($dir); }
function sync_object($object_type, $object_name) { # Should only provide error information on stderr: put stdout to syslog $cmd = "geni-sync-wireless {$object_type} {$object_name}"; error_log("SYNC(cmd) " . $cmd); $descriptors = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")); $process = proc_open($cmd, $descriptors, $pipes); $std_output = stream_get_contents($pipes[1]); # Should be empty $err_output = stream_get_contents($pipes[2]); fclose($pipes[1]); fclose($pipes[2]); $proc_value = proc_close($process); $full_output = $std_output . $err_output; foreach (split("\n", $full_output) as $line) { if (strlen(trim($line)) == 0) { continue; } error_log("SYNC(output) " . $line); } if ($proc_value != RESPONSE_ERROR::NONE) { error_log("WIRELESS SYNC error: {$proc_value}"); } return $proc_value; }
function execi($cmd, $userdir, $timeout) { $starttime = microtime(); $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")); $cwd = getcwd() . "/" . $userdir; $env = null; $output = ""; $proc = proc_open($cmd, $descriptorspec, $pipes, $cwd, $env); $handle = fopen($userdir . "tempi.txt", "r"); if ($handle) { while (($line = fgets($handle)) !== false) { fwrite($pipes[0], $line); } fclose($pipes[0]); fclose($handle); } while (microtime() < $starttime + $timeout) { $status = proc_get_status($proc); if ($status['running']) { if (is_resource($proc)) { $output = $output . "<pre>" . stream_get_contents($pipes[1]) . "</pre>"; $output = $output . "<pre>" . stream_get_contents($pipes[2]) . "</pre>"; } } else { $time = microtime() - $starttime; return $output . " time to execute = " . $time; //command completed :) } } proc_terminate($proc); return 'timeout !!'; // fwrite($pipes[0], '10'); // fclose($pipes[0]); // $return_value = proc_close($proc); }
/** * Execute a command which takes over stdin, stdout and stderr, similar to * passthru(), but which preserves TTY semantics, escapes arguments, and is * traceable. * * @param string sprintf()-style command pattern to execute. * @param ... Arguments to sprintf pattern. * @return int Return code. * @group exec */ function phutil_passthru($cmd) { $args = func_get_args(); $command = call_user_func_array('csprintf', $args); $profiler = PhutilServiceProfiler::getInstance(); $call_id = $profiler->beginServiceCall(array('type' => 'exec', 'subtype' => 'passthru', 'command' => $command)); $spec = array(STDIN, STDOUT, STDERR); $pipes = array(); if (phutil_is_windows()) { // Without 'bypass_shell', things like launching vim don't work properly, // and we can't execute commands with spaces in them, and all commands // invoked from git bash fail horridly, and everything is a mess in general. $options = array('bypass_shell' => true); $proc = @proc_open($command, $spec, $pipes, null, null, $options); } else { $proc = @proc_open($command, $spec, $pipes); } if ($proc === false) { $err = 1; } else { $err = proc_close($proc); } $profiler->endServiceCall($call_id, array('err' => $err)); return $err; }
/** * */ public function execute() { $this->process = proc_open($this->command, array(array("pipe", "r"), array("pipe", "w"), array("pipe", "w")), $pipes); stream_set_blocking($pipes[1], 0); stream_set_blocking($pipes[2], 0); $this->pipes = $pipes; }
/** * Evaluates the constraint for parameter $other. Returns TRUE if the * constraint is met, FALSE otherwise. * * @param mixed $other Filename of the image to compare. * @return bool * @abstract */ public function evaluate($other) { if (!is_string($other) || !is_file($other) || !is_readable($other)) { throw new ezcBaseFileNotFoundException($other); } $descriptors = array(array('pipe', 'r'), array('pipe', 'w'), array('pipe', 'w')); $command = sprintf('compare -metric MAE %s %s null:', escapeshellarg($this->filename), escapeshellarg($other)); $imageProcess = proc_open($command, $descriptors, $pipes); // Close STDIN pipe fclose($pipes[0]); $errorString = ''; // Read STDERR do { $errorString .= rtrim(fgets($pipes[2], 1024), "\n"); } while (!feof($pipes[2])); $resultString = ''; // Read STDOUT do { $resultString .= rtrim(fgets($pipes[1], 1024), "\n"); } while (!feof($pipes[1])); // Wait for process to terminate and store return value $return = proc_close($imageProcess); // Some versions output to STDERR if (empty($resultString) && !empty($errorString)) { $resultString = $errorString; } // Different versuions of ImageMagick seem to output "dB" or not if (preg_match('/([\\d.,e]+)(\\s+dB)?/', $resultString, $match)) { $this->difference = (int) $match[1]; return $this->difference <= $this->delta; } return false; }
/** * Execute a command and kill it if the timeout limit fired to prevent long php execution * * @see http://stackoverflow.com/questions/2603912/php-set-timeout-for-script-with-system-call-set-time-limit-not-working * * @param string $cmd Command to exec (you should use 2>&1 at the end to pipe all output) * @param integer $timeout * @return string Returns command output */ function ExecWaitTimeout($cmd, $timeout = 5) { echo $cmd . "\n"; $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")); $pipes = array(); $timeout += time(); $process = proc_open($cmd, $descriptorspec, $pipes); if (!is_resource($process)) { throw new Exception("proc_open failed on: " . $cmd); } $output = ''; do { $timeleft = $timeout - time(); $read = array($pipes[1]); // if($timeleft > 0) stream_select($read, $write = NULL, $exeptions = NULL, $timeleft, NULL); if (!empty($read)) { $output .= fread($pipes[1], 8192); } } while (!feof($pipes[1]) && $timeleft > 0); if ($timeleft <= 0) { proc_terminate($process); throw new Exception("command timeout on: " . $cmd); } else { return $output; } }
/** * Start the process. * * After the process is started, the standard IO streams will be constructed * and available via public properties. STDIN will be paused upon creation. * * @param LoopInterface $loop Loop interface for stream construction * @param float $interval Interval to periodically monitor process state (seconds) * @throws RuntimeException If the process is already running or fails to start */ public function start(LoopInterface $loop, $interval = 0.1) { if ($this->isRunning()) { throw new \RuntimeException('Process is already running'); } $cmd = $this->cmd; $fdSpec = array(array('pipe', 'r'), array('pipe', 'w'), array('pipe', 'w')); // Read exit code through fourth pipe to work around --enable-sigchild if ($this->isSigchildEnabled() && $this->enhanceSigchildCompatibility) { $fdSpec[] = array('pipe', 'w'); $cmd = sprintf('(%s) 3>/dev/null; code=$?; echo $code >&3; exit $code', $cmd); } $this->process = proc_open($cmd, $fdSpec, $this->pipes, $this->cwd, $this->env, $this->options); if (!is_resource($this->process)) { throw new \RuntimeException('Unable to launch a new process.'); } $this->stdin = new Stream($this->pipes[0], $loop); $this->stdin->pause(); $this->stdout = new Stream($this->pipes[1], $loop); $this->stderr = new Stream($this->pipes[2], $loop); foreach ($this->pipes as $pipe) { stream_set_blocking($pipe, 0); } $loop->addPeriodicTimer($interval, function (Timer $timer) { if (!$this->isRunning()) { $this->close(); $timer->cancel(); $this->emit('exit', array($this->getExitCode(), $this->getTermSignal())); } }); }
function printFax($fax_id) { $data = $GLOBALS['hylax_storage']->getFaxData($fax_id); $command = $GLOBALS['conf']['fax']['print']; $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")); /* Set up the process. */ $process = proc_open($command, $descriptorspec, $pipes); if (!is_resource($process)) { return PEAR::raiseError('fail'); } fwrite($pipes[0], $data); fclose($pipes[0]); $output = ''; while (!feof($pipes[1])) { $output .= fgets($pipes[1], 1024); } fclose($pipes[1]); $stderr = ''; while (!feof($pipes[2])) { $stderr .= fgets($pipes[2], 1024); } fclose($pipes[2]); proc_close($process); if ($stderr) { return PEAR::raiseError($stderr); } return true; }
/** * Execute this command. * * @return int Error code returned by the subprocess. * * @task command */ public function execute() { $command = $this->command; $profiler = PhutilServiceProfiler::getInstance(); $call_id = $profiler->beginServiceCall(array('type' => 'exec', 'subtype' => 'passthru', 'command' => $command)); $spec = array(STDIN, STDOUT, STDERR); $pipes = array(); if ($command instanceof PhutilCommandString) { $unmasked_command = $command->getUnmaskedString(); } else { $unmasked_command = $command; } $env = $this->env; $cwd = $this->cwd; $options = array(); if (phutil_is_windows()) { // Without 'bypass_shell', things like launching vim don't work properly, // and we can't execute commands with spaces in them, and all commands // invoked from git bash fail horridly, and everything is a mess in // general. $options['bypass_shell'] = true; } $trap = new PhutilErrorTrap(); $proc = @proc_open($unmasked_command, $spec, $pipes, $cwd, $env, $options); $errors = $trap->getErrorsAsString(); $trap->destroy(); if (!is_resource($proc)) { throw new Exception(pht('Failed to passthru %s: %s', 'proc_open()', $errors)); } $err = proc_close($proc); $profiler->endServiceCall($call_id, array('err' => $err)); return $err; }
public function listen($host, $port) { self::$host_port = $host . ':' . $port; // partly borrowed from https://github.com/php/php-src/blob/master/ext/curl/tests/server.inc // but make it more simple $php_executable = getenv('TEST_PHP_EXECUTABLE'); $php_executable = $php_executable ?: getenv('_'); $doc_root = __DIR__ . DIRECTORY_SEPARATOR . 'server'; $descriptorspec = array(0 => STDIN, 1 => STDOUT, 2 => STDERR); echo "start local server\n"; if (substr(PHP_OS, 0, 3) == 'WIN') { $cmd = "{$php_executable} -t {$doc_root} -n -S " . self::$host_port; $this->_server = proc_open(addslashes($cmd), $descriptorspec, $pipes, $doc_root, NULL, array("bypass_shell" => true, "suppress_errors" => true)); } else { $cmd = "exec {$php_executable} -t {$doc_root} -n -S " . self::$host_port; $cmd .= " 2>/dev/null"; $this->_server = proc_open($cmd, $descriptorspec, $pipes, $doc_root); } if (is_resource($this->_server)) { $fp = 0; $i = 0; while ($i++ < 30 && !($fp = @fsockopen($host, $port))) { usleep(10000); } if ($fp) { fclose($fp); } echo "local server started\n"; } else { echo "start local server failed\n"; exit; } }
/** * @param $userid int * @param $action string * @param $data array * @throws Exception * @returns stdClass */ function call_cfadmin($userid, $action, $data = array()) { if (!is_int($userid)) { throw new Exception('Invalid userid passed to `call_cfadmin`'); } if (!is_string($action) || !$action) { throw new Exception('Invalid action passed to `call_cfadmin`'); } if (!is_array($data)) { throw new Exception('Invalid data passed to `call_cfadmin`'); } $stdin = "{$userid} {$action} "; foreach ($data as $key => $value) { $stdin .= "{$key} {$value} "; } $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w")); $process = proc_open("/usr/local/cpanel/bin/cfadmin", $descriptorspec, $pipes); if (!is_resource($process)) { throw new Exception('Unable to open process to cfadmin'); } // write necessary data to cfadmin for it to run fwrite($pipes[0], $stdin . "\n"); fclose($pipes[0]); $response = stream_get_contents($pipes[1]); fclose($pipes[1]); $return_value = proc_close($process); if ($return_value !== 0) { throw new Exception('Error code returned from cfadmin'); } // try to parse out the javascript response // cfadmin adds a period on its own line to make cpanel happy, so we need to trim that off to get valid json. $json_string = trim($response, ". \t\n\r"); $response_object = json_decode($json_string); return $response_object; }
function setDomainAddress($domain, $address, $server, $ttl = 86400) { $process = proc_open('/usr/bin/nsupdate', array(array('pipe', 'r'), array('pipe', 'w'), array('pipe', 'w')), $pipes); if (is_resource($process)) { fwrite($pipes[0], "server {$server}\n"); fwrite($pipes[0], "update delete {$domain}.\n"); if ($address !== false) { fwrite($pipes[0], "update add {$domain}. {$ttl} IN A {$address}\n"); } fwrite($pipes[0], "\n"); fclose($pipes[0]); $result = true; if (fgetc($pipes[1]) !== false) { $result = false; } fclose($pipes[1]); if (fgetc($pipes[2]) !== false) { $result = false; } fclose($pipes[2]); proc_close($process); return $result; } return false; }
public function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Starting server on port 5000'); $descriptorspec = array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w')); $port = $input->getOption('port'); // Start server process $process = proc_open("php -S localhost:{$port} -t public/ " . getcwd() . "/scripts/normal-server/router.php", $descriptorspec, $pipes, getcwd(), $_ENV); if (!is_resource($process)) { throw new Exception("popen error"); } stream_set_blocking($pipes[0], 0); stream_set_blocking($pipes[1], 0); stream_set_blocking($pipes[2], 0); // Redirect all output while (!feof($pipes[1])) { foreach ($pipes as $pipe) { $line = fread($pipe, 128); if ($line) { $output->writeln($line); } } sleep(0.5); } foreach ($pipes as $pipe) { fclose($pipe); } }
function pleac_Controlling_Input_and_Output_of_Another_Program() { // Connect to input and output of a process. $proc = proc_open($program, array(0 => array('pipe', 'r'), 1 => array('pipe', 'w')), $pipes); if (is_resource($proc)) { fwrite($pipes[0], "here's your input\n"); fclose($pipes[0]); echo stream_get_contents($pipes[1]); fclose($pipes[1]); $result_code = proc_close($proc); echo "{$result_code}\n"; } // ----------------------------- $all = array(); $outlines = array(); $errlines = array(); exec("( {$cmd} | sed -e 's/^/stdout: /' ) 2>&1", $all); foreach ($all as $line) { $pos = strpos($line, 'stdout: '); if ($pos !== false && $pos == 0) { $outlines[] = substr($line, 8); } else { $errlines[] = $line; } } print "STDOUT:\n"; print_r($outlines); print "\n"; print "STDERR:\n"; print_r($errlines); print "\n"; }
/** */ protected function _changePassword($user, $oldpass, $newpass) { $descr = array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w')); $output = ''; $process = @proc_open($this->_params['program'], $descr, $pipes); if (is_resource($process)) { fwrite($pipes[0], "{$user}\n"); fwrite($pipes[0], "{$oldpass}\n"); fwrite($pipes[0], "{$newpass}\n"); fclose($pipes[0]); while (!feof($pipes[1])) { $output .= fgets($pipes[1], 1024); } fclose($pipes[1]); while (!feof($pipes[2])) { $output .= fgets($pipes[2], 1024); } fclose($pipes[2]); $return_value = proc_close($process); } else { $return_value = -1; } $output .= " (Exit Status: {$return_value})"; if ($return_value != 0) { throw new Passwd_Exception($output); } }
/** * Execute the given command * * @param string $command Command to execute * @param array $args Arguments for command * * @return mixed $return Command output */ public function run($command, $args = null) { Output::msg('Executing command: "' . $command . '"'); // filter the command $command = escapeshellcmd($command); $descSpec = array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w')); $pipes = null; $return = null; $process = proc_open($command, $descSpec, $pipes); if (is_resource($process)) { $return = stream_get_contents($pipes[1]); if (empty($return)) { // probably some sort of error if (is_resource($pipes[2])) { $err = trim(stream_get_contents($pipes[2])); fclose($pipes[2]); throw new \Exception($err); } } fclose($pipes[1]); $returnCode = proc_close($process); Output::msg("Execution result:\n" . $return); } return $return; }
/** * @param string $router * @param array $env * @return UrlScript * @throws \RuntimeException */ public function start($router, $env = array()) { $this->slaughter(); static $port; if ($port === NULL) { do { $port = rand(8000, 10000); if (isset($lock)) { @fclose($lock); } $lock = fopen(dirname(TEMP_DIR) . '/http-server-' . $port . '.lock', 'w'); } while (!flock($lock, LOCK_EX | LOCK_NB, $wouldBlock) || $wouldBlock); } $ini = NULL; if (($pid = getmypid()) && ($myprocess = `ps -ww -fp {$pid}`)) { $fullArgs = preg_split('~[ \\t]+~', explode("\n", $myprocess)[1], 8)[7]; if (preg_match('~\\s\\-c\\s(?P<ini>[^ \\t]+)\\s~i', $fullArgs, $m)) { $ini = '-c ' . $m['ini'] . ' -n'; } } $executable = new PhpExecutableFinder(); $cmd = sprintf('%s %s -d register_argc_argv=on -t %s -S %s:%d %s', escapeshellcmd($executable->find()), $ini, escapeshellarg(dirname($router)), $ip = '127.0.0.1', $port, escapeshellarg($router)); if (!is_resource($this->process = proc_open($cmd, self::$spec, $this->pipes, dirname($router), $env))) { throw new HttpServerException("Could not execute: `{$cmd}`"); } sleep(1); // give him some time to boot up $status = proc_get_status($this->process); if (!$status['running']) { throw new HttpServerException("Failed to start php server: " . stream_get_contents($this->pipes[2])); } $this->url = new UrlScript('http://' . $ip . ':' . $port); return $this->getUrl(); }
protected function execute(InputInterface $input, OutputInterface $output) { global $pdo_dsn, $db_username, $db_password; $dsn = $this->parseDSN($pdo_dsn); $dry_run = $input->getOption('dry-run'); $cmd = 'mysqldump --host=' . escapeshellarg($dsn['host']) . ' --user='******' --password='******' ' . escapeshellarg($dsn['dbname']) . ' '; if ($input->getArgument('outputfile')) { $file = $input->getArgument('outputfile'); } else { if (!is_dir(REAL_PATH . '/../backups/')) { mkdir(REAL_PATH . '/../backups/'); } $file = REAL_PATH . '/../backups/' . strftime('%F-%T.sql'); } $output->writeln("<info>Running: {$cmd}</info>"); $output->writeln("<info>Output to: {$file}</info>"); if (!$dry_run) { $proc = proc_open($cmd, array(0 => array('pipe', 'r'), 1 => array('file', $file, 'w'), 2 => array('pipe', 'w')), $pipes, null, array()); $status = proc_get_status($proc); while ($status['running']) { sleep(1); $output->write('.'); $status = proc_get_status($proc); } if ($status['exitcode']) { $output->writeln('<error>' . stream_get_contents($pipes[2]) . '</error>'); return $status['exitcode']; } $output->writeln("\n<info>Done</info>"); } }
public function startServer($name) { $filename = __DIR__ . '/server/' . $name . '.php'; $pipes = []; $this->servers[$name] = proc_open('php ' . $filename, [], $pipes); usleep(30000); }
public function changePwd($newPwd) { $ldapObj = new Lucid_LDAP($this->configFile); $ldapObj->bind($this->username, $this->password); list($entry, $dn) = $ldapObj->searchUser($this->username, array("sAMAccountName")); $ldapObj->destroy(); $this->loggerObj->log("Changing password for {$this->username}"); $oldPwdEnc = base64_encode(adifyPw($this->password)); $newPwdEnc = base64_encode(adifyPw($newPwd)); $tmpPath = getConfig("tmpPath"); $tmpName = tempnam($tmpPath, "ldap-"); try { $tmpFile = fopen($tmpName, "w+"); fwrite($tmpFile, $this->password); fclose($tmpFile); $cmd = "ldapmodify -H {$ldapObj->url} -D '{$dn}' -x -y {$tmpName}"; $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")); $child = proc_open(escapeshellcmd($cmd), $descriptorspec, $pipes); $ldif_file = array("dn: {$dn}", "changetype: modify", "delete: unicodePwd", "unicodePwd:: {$oldPwdEnc}", "-", "add: unicodePwd", "unicodePwd:: {$newPwdEnc}", "-"); fwrite($pipes[0], implode("\n", $ldif_file) . "\n"); fclose($pipes[0]); $output1 = stream_get_contents($pipes[1]); $output2 = stream_get_contents($pipes[2]); fclose($pipes[1]); fclose($pipes[2]); $status = proc_close($child); $this->loggerObj->log("LDAPModify exited with status: {$status}"); $this->loggerObj->log("LDAPModify Output: {$output1}\n {$output2}"); return array($status, $output2); } finally { if ($tmpFile) { unlink($tmpName); } } }
/** * Executes shell commands. * @param array $args * @return bool Indicates success */ public function executeCommand($args = array()) { $this->lastOutput = array(); $command = call_user_func_array('sprintf', $args); if ($this->quiet) { $this->logger->log('Executing: ' . $command); } $status = 0; $descriptorSpec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")); $pipes = array(); $process = proc_open($command, $descriptorSpec, $pipes, dirname($this->buildPath), null); if (is_resource($process)) { fclose($pipes[0]); $this->lastOutput = stream_get_contents($pipes[1]); $this->lastError = stream_get_contents($pipes[2]); fclose($pipes[1]); fclose($pipes[2]); $status = proc_close($process); } $this->lastOutput = array_filter(explode(PHP_EOL, $this->lastOutput)); $shouldOutput = $this->logExecOutput && ($this->verbose || $status != 0); if ($shouldOutput && !empty($this->lastOutput)) { $this->logger->log($this->lastOutput); } if (!empty($this->lastError)) { $this->logger->log("[0;31m" . $this->lastError . "[0m", LogLevel::ERROR); } $rtn = false; if ($status == 0) { $rtn = true; } return $rtn; }
public function compress($source, $type) { $cmd = sprintf('java -jar %s --type %s --charset UTF-8 --line-break 1000', escapeshellarg($this->yuiPath), $type); $process = proc_open($cmd, array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")), $pipes); fwrite($pipes[0], $source); fclose($pipes[0]); $output = array("stdout" => "", "stderr" => ""); $readSockets = array("stdout" => $pipes[1], "stderr" => $pipes[2]); $empty = array(); while (false !== stream_select($readSockets, $empty, $empty, 1)) { foreach ($readSockets as $stream) { $output[$stream == $pipes[1] ? "stdout" : "stderr"] .= stream_get_contents($stream); } $readSockets = array("stdout" => $pipes[1], "stderr" => $pipes[2]); $eof = true; foreach ($readSockets as $stream) { $eof &= feof($stream); } if ($eof) { break; } } $compressed = $output['stdout']; $errors = $output['stderr']; $this->errors = "" !== $errors; if ($this->errors) { $compressed = ""; $this->errors = sprintf("alert('compression errors, check your source and console for details'); console.error(%s); ", json_encode($errors)); } proc_close($process); return $compressed; }
function execute($cmd, &$output, &$error, &$returnCode) { $descriptorspec = array(1 => array('pipe', 'w'), 2 => array('pipe', 'w')); $process = proc_open($cmd, $descriptorspec, $pipes); if (!is_resource($process)) { throw new RuntimeException("Unable to execute the command. [{$cmd}]"); } stream_set_blocking($pipes[1], false); stream_set_blocking($pipes[2], false); $output = $error = ''; foreach ($pipes as $key => $pipe) { while (!feof($pipe)) { if (!($line = fread($pipe, 128))) { continue; } if (1 == $key) { $output .= $line; // stdout } else { $error .= $line; // stderr } } fclose($pipe); } $returnCode = proc_close($process); }
public function testExternalTest() { $dataDir = dirname(__FILE__) . "/data"; $phpPath = isset($_SERVER["_"]) ? $_SERVER["_"] : "/bin/env php"; $scriptFile = "{$dataDir}/syslog_tests.php"; $desc = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")); $proc = proc_open("'{$phpPath}' '{$scriptFile}'", $desc, $pipes); fclose($pipes[0]); fclose($pipes[1]); $ret = ''; while (!feof($pipes[2])) { $ret .= fgets($pipes[2]); } $strings = explode("\n", $ret); // check each of the strings for correctness $regExp = "/ezctest\\S*: \\[Debug\\] \\[Donny\\] \\[quotes\\] I was bowling. \\(movie: The Big Lebowski\\)/"; $this->assertRegExp($regExp, $strings[0]); $regExp = "/ezctest\\S*: \\[Debug\\] \\[Lebowski\\] \\[quotes\\] The dude abides./"; $this->assertRegExp($regExp, $strings[1]); $regExp = "/ezctest\\S*: \\[Success audit\\] \\[Maude\\] \\[quotes\\] Don't be fatuous, Jeffrey./"; $this->assertRegExp($regExp, $strings[2]); $regExp = "/ezctest\\S*: \\[Failed audit\\] \\[Lebowski\\] \\[quotes\\] Also, my rug was stolen./"; $this->assertRegExp($regExp, $strings[3]); $regExp = "/ezctest\\S*: \\[Info\\] \\[Lebowski\\] \\[quotes\\] Obviously you're not a golfer./"; $this->assertRegExp($regExp, $strings[4]); $regExp = "/ezctest\\S*: \\[Notice\\] \\[Walter\\] \\[quotes\\] Forget it, Donny, you're out of your element!/"; $this->assertRegExp($regExp, $strings[5]); $regExp = "/ezctest\\S*: \\[Failed audit\\] \\[Walter\\] \\[quotes\\] Donny you're out of your element! Dude, the Chinaman is not the issue here!/"; $this->assertRegExp($regExp, $strings[6]); $regExp = "/ezctest\\S*: \\[Fatal\\] \\[The stranger\\] \\[quotes\\] Ok, Dude. Have it your way./"; $this->assertRegExp($regExp, $strings[7]); }
/** * Gets the mime type for a blob * * @param GitPHP_Blob $blob blob * @return string mime type */ public function GetMime($blob) { if (!$blob) { return false; } $data = $blob->GetData(); if (empty($data)) { return false; } $descspec = array(0 => array('pipe', 'r'), 1 => array('pipe', 'w')); $proc = proc_open('file -b --mime -', $descspec, $pipes); if (is_resource($proc)) { fwrite($pipes[0], $data); fclose($pipes[0]); $mime = stream_get_contents($pipes[1]); fclose($pipes[1]); proc_close($proc); if ($mime && strpos($mime, '/')) { if (strpos($mime, ';')) { $mime = strtok($mime, ';'); } return $mime; } } return false; }
private function callFormatter($cmd) { $cmd = $this->getExecPath() . " " . escapeshellarg($cmd); $proc = proc_open($cmd, [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes); if (!$proc) { throw new \RuntimeException("proc_open failed"); } $code = null; while (true) { $status = proc_get_status($proc); if (!$status) { proc_terminate($proc); throw new \RuntimeException("Failed to get process status"); } if (!$status['running']) { $out = stream_get_contents($pipes[1]); $err = stream_get_contents($pipes[2]); $code = $status['exitcode']; break; } } if (null === $code) { throw new \RuntimeException("Failed to execute '{$cmd}' - unknown result"); } return ['out' => $out, 'err' => $err, 'code' => $code]; }
private function executeCommandWithDelayedStdin($command, $stdinLines, $delayMicroseconds = 1000000) { $descriptors = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")); $pipes = array(); $process = proc_open($command, $descriptors, $pipes); if (!is_resource($process)) { throw new \RuntimeException("Failed to run command '{$command}'"); } // $pipes now looks like this: // 0 => writable handle connected to child stdin // 1 => readable handle connected to child stdout // 2 => readable handle connected to child stderr foreach ($stdinLines as $stdinLine) { usleep($delayMicroseconds); fwrite($pipes[0], $stdinLine); } fclose($pipes[0]); $stdOut = stream_get_contents($pipes[1]); fclose($pipes[1]); $stdErr = stream_get_contents($pipes[2]); fclose($pipes[2]); if ($stdErr) { throw new \RuntimeException("Error executing {$command}: {$stdErr}"); } // It is important that to close any pipes before calling // proc_close in order to avoid a deadlock proc_close($process); return $stdOut; }
function PMA_transformation_text_plain__external($buffer, $options = array(), $meta = '') { // possibly use a global transform and feed it with special options: // include './libraries/transformations/global.inc.php'; // further operations on $buffer using the $options[] array. $allowed_programs = array(); // // WARNING: // // It's up to administrator to allow anything here. Note that users may // specify any parameters, so when programs allow output redirection or // any other possibly dangerous operations, you should write wrapper // script that will publish only functions you really want. // // Add here program definitions like (note that these are NOT safe // programs): // //$allowed_programs[0] = '/usr/local/bin/tidy'; //$allowed_programs[1] = '/usr/local/bin/validate'; // no-op when no allowed programs if (count($allowed_programs) == 0) { return $buffer; } if (!isset($options[0]) || $options[0] == '' || !isset($allowed_programs[$options[0]])) { $program = $allowed_programs[0]; } else { $program = $allowed_programs[$options[0]]; } if (!isset($options[1]) || $options[1] == '') { $poptions = '-f /dev/null -i -wrap -q'; } else { $poptions = $options[1]; } if (!isset($options[2]) || $options[2] == '') { $options[2] = 1; } if (!isset($options[3]) || $options[3] == '') { $options[3] = 1; } // needs PHP >= 4.3.0 $newstring = ''; $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w")); $process = proc_open($program . ' ' . $poptions, $descriptorspec, $pipes); if (is_resource($process)) { fwrite($pipes[0], $buffer); fclose($pipes[0]); while (!feof($pipes[1])) { $newstring .= fgets($pipes[1], 1024); } fclose($pipes[1]); // we don't currently use the return value $return_value = proc_close($process); } if ($options[2] == 1 || $options[2] == '2') { $retstring = htmlspecialchars($newstring); } else { $retstring = $newstring; } return $retstring; }
/** * Constructor * * @param string command default NULL * @param string[] arguments default [] * @param string cwd default NULL the working directory * @param [:string] default NULL the environment * @throws io.IOException in case the command could not be executed */ public function __construct($command = NULL, $arguments = array(), $cwd = NULL, $env = NULL) { static $spec = array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w')); // For `new self()` used in getProcessById() if (NULL === $command) { return; } // Check whether the given command is executable. $binary = self::resolve($command); if (!is_file($binary) || !is_executable($binary)) { throw new IOException('Command "' . $binary . '" is not an executable file'); } // Open process $cmd = CommandLine::forName(PHP_OS)->compose($binary, $arguments); if (!is_resource($this->_proc = proc_open($cmd, $spec, $pipes, $cwd, $env, array('bypass_shell' => TRUE)))) { throw new IOException('Could not execute "' . $cmd . '"'); } $this->status = proc_get_status($this->_proc); $this->status['exe'] = $binary; $this->status['arguments'] = $arguments; $this->status['owner'] = TRUE; // Assign in, out and err members $this->in = new File($pipes[0]); $this->out = new File($pipes[1]); $this->err = new File($pipes[2]); }