Example #1
1
 /**
  * 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;
}
Example #3
0
 private function collectProcessGarbage()
 {
     foreach ($this->processes as $key => $procHandle) {
         $info = proc_get_status($procHandle);
         if ($info["running"]) {
             continue;
         }
         $this->defunctProcessCount--;
         proc_close($procHandle);
         unset($this->processes[$key]);
         if ($this->expectedFailures > 0) {
             $this->expectedFailures--;
             continue;
         }
         if (!$this->stopPromisor) {
             $this->spawn();
         }
     }
     // If we've reaped all known dead processes we can stop checking
     if (empty($this->defunctProcessCount)) {
         \Amp\disable($this->procGarbageWatcher);
     }
     if ($this->stopPromisor && empty($this->processes)) {
         \Amp\cancel($this->procGarbageWatcher);
         if ($this->stopPromisor !== true) {
             \Amp\immediately([$this->stopPromisor, "succeed"]);
         }
         $this->stopPromisor = true;
     }
 }
Example #4
0
 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);
         }
     }
 }
 /**
  * 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;
 }
Example #6
0
 /**
  * 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;
 }
Example #7
0
 /**
  * Launch PHP's built-in web server for this specific WordPress installation.
  *
  * Uses `php -S` to launch a web server serving the WordPress webroot.
  * <http://php.net/manual/en/features.commandline.webserver.php>
  *
  * ## OPTIONS
  *
  * [--host=<host>]
  * : The hostname to bind the server to.
  * ---
  * default: localhost
  * ---
  *
  * [--port=<port>]
  * : The port number to bind the server to.
  * ---
  * default: 8080
  * ---
  *
  * [--docroot=<path>]
  * : The path to use as the document root.
  *
  * [--config=<file>]
  * : Configure the server with a specific .ini file.
  *
  * ## EXAMPLES
  *
  *     # Make the instance available on any address (with port 8080)
  *     $ wp server --host=0.0.0.0
  *     PHP 5.6.9 Development Server started at Tue May 24 01:27:11 2016
  *     Listening on http://0.0.0.0:8080
  *     Document root is /
  *     Press Ctrl-C to quit.
  *
  *     # Run on port 80 (for multisite)
  *     $ sudo wp server --host=localhost.localdomain --port=80
  *     PHP 5.6.9 Development Server started at Tue May 24 01:30:06 2016
  *     Listening on http://localhost1.localdomain1:8080
  *     Document root is /
  *     Press Ctrl-C to quit.
  *
  *     # Configure the server with a specific .ini file
  *     $ wp server --config=development.ini
  *     PHP 7.0.9 Development Server started at Mon Aug 22 12:09:04 2016
  *     Listening on http://localhost:8080
  *     Document root is /
  *     Press Ctrl-C to quit.
  *
  * @when before_wp_load
  */
 function __invoke($_, $assoc_args)
 {
     $min_version = '5.4';
     if (version_compare(PHP_VERSION, $min_version, '<')) {
         WP_CLI::error("The `wp server` command requires PHP {$min_version} or newer.");
     }
     $defaults = array('host' => 'localhost', 'port' => 8080, 'docroot' => false, 'config' => get_cfg_var('cfg_file_path'));
     $assoc_args = array_merge($defaults, $assoc_args);
     $docroot = $assoc_args['docroot'];
     if (!$docroot) {
         $config_path = WP_CLI::get_runner()->project_config_path;
         if (!$config_path) {
             $docroot = ABSPATH;
         } else {
             $docroot = dirname($config_path);
         }
     }
     $cmd = \WP_CLI\Utils\esc_cmd('%s -S %s -t %s -c %s %s', PHP_BINARY, $assoc_args['host'] . ':' . $assoc_args['port'], $docroot, $assoc_args['config'], \WP_CLI\Utils\extract_from_phar(WP_CLI_ROOT . '/php/router.php'));
     $descriptors = array(STDIN, STDOUT, STDERR);
     // https://bugs.php.net/bug.php?id=60181
     $options = array();
     if (\WP_CLI\Utils\is_windows()) {
         $options["bypass_shell"] = TRUE;
     }
     exit(proc_close(proc_open($cmd, $descriptors, $pipes, NULL, NULL, $options)));
 }
Example #8
0
/**
 * @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 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";
}
Example #10
0
/**
 * 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;
}
Example #11
0
 public function stream(Git_HTTP_Command $command)
 {
     $cwd = '/tmp';
     $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"));
     if (ForgeConfig::get('sys_logger_level') == Logger::DEBUG) {
         $descriptorspec[2] = array('file', ForgeConfig::get('codendi_log') . '/git_http_error_log', 'a');
     }
     $pipes = array();
     $this->logger->debug('Command: ' . $command->getCommand());
     $this->logger->debug('Environment: ' . print_r($command->getEnvironment(), true));
     $process = proc_open($command->getCommand(), $descriptorspec, $pipes, $cwd, $command->getEnvironment());
     if (is_resource($process)) {
         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
             fwrite($pipes[0], file_get_contents('php://input'));
         }
         fclose($pipes[0]);
         $first = true;
         while ($result = stream_get_contents($pipes[1], self::CHUNK_LENGTH)) {
             if ($first) {
                 list($headers, $body) = http_split_header_body($result);
                 foreach (explode("\r\n", $headers) as $header) {
                     header($header);
                 }
                 file_put_contents('php://output', $body);
             } else {
                 file_put_contents('php://output', $result);
             }
             $first = false;
         }
         fclose($pipes[1]);
         $return_value = proc_close($process);
     }
 }
Example #12
0
 /**
  * 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("" . $this->lastError . "", LogLevel::ERROR);
     }
     $rtn = false;
     if ($status == 0) {
         $rtn = true;
     }
     return $rtn;
 }
Example #13
0
 public function render()
 {
     // Generate the DOT source code, and write to a file.
     $dot = new \Tabulate\Template('erd/erd.twig');
     $dot->tables = $this->tables;
     $dot->selectedTables = $this->selectedTables;
     $dotCode = $dot->render();
     $tmpFilePath = Config::storageDirTmp('erd/' . uniqid());
     $dotFile = $tmpFilePath . '/erd.dot';
     $pngFile = $tmpFilePath . '/erd.png';
     file_put_contents($dotFile, $dotCode);
     // Generate the image.
     $cmd = Config::dotCommand() . ' -Tpng -o' . escapeshellarg($pngFile) . ' ' . escapeshellarg($dotFile);
     $ds = array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
     $pipes = false;
     $proc = proc_open($cmd, $ds, $pipes, Config::storageDirTmp('erd'), array());
     fclose($pipes[0]);
     $out = stream_get_contents($pipes[1]);
     fclose($pipes[1]);
     $err = stream_get_contents($pipes[2]);
     fclose($pipes[2]);
     proc_close($proc);
     if (!empty($err)) {
         throw new \Exception("Error generating graph image. {$err}");
     }
     // Send the image.
     header('Content-Type:image/png');
     echo file_get_contents($pngFile);
     // Clean up.
     \Tabulate\File::rmdir($tmpFilePath);
 }
Example #14
0
 private function execute($args, $pipe_stdout, $cwd_override = null)
 {
     $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
     $cwd = $cwd_override != NULL ? $cwd_override : $this->cwd;
     $cmd = join(' ', array_map('escapeshellarg', $args));
     $proc = proc_open($cmd, $descriptorspec, $pipes, $cwd, array('LANG' => 'en_US.UTF-8'));
     if (!is_resource($proc)) {
         $errors = error_get_last();
         $this->log->error("{$cmd} failed: {$errors['type']} {$errors['message']}");
         throw new Exception($errors['message']);
     }
     fclose($pipes[0]);
     if ($pipe_stdout) {
         $output = stream_get_contents($pipes[1]);
     } else {
         fpassthru($pipes[1]);
         $output = null;
     }
     $err = stream_get_contents($pipes[2]);
     $retval = proc_close($proc);
     if ($retval != 0) {
         $this->log->error("{$cmd} failed: {$retval} {$output} {$err}");
         throw new Exception($err);
     }
     return $output;
 }
Example #15
0
function cs2cs_core2($lat, $lon, $to)
{
    $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
    if (mb_eregi('^[a-z0-9_ ,.\\+\\-=]*$', $to) == 0) {
        die("invalid arguments in command: " . $to . "\n");
    }
    $command = CS2CS . " +proj=latlong +ellps=WGS84 +to " . $to;
    $process = proc_open($command, $descriptorspec, $pipes);
    if (is_resource($process)) {
        fwrite($pipes[0], $lon . " " . $lat);
        fclose($pipes[0]);
        $stdout = stream_get_contents($pipes[1]);
        fclose($pipes[1]);
        $stderr = stream_get_contents($pipes[2]);
        fclose($pipes[2]);
        //
        // $procstat = proc_get_status($process);
        //
        // neither proc_close nor proc_get_status return reasonable results with PHP5 and linux 2.6.11,
        // see http://bugs.php.net/bug.php?id=32533
        //
        // as temporary (?) workaround, check stderr output.
        // (Vinnie, 2006-02-09)
        if ($stderr) {
            die("proc_open() failed:<br />command='{$command}'<br />stderr='" . $stderr . "'");
        }
        proc_close($process);
        return mb_split("\t|\n| ", mb_trim($stdout));
    } else {
        die("proc_open() failed, command={$command}\n");
    }
}
Example #16
0
 /**
  *
  */
 public function stream_close()
 {
     if (is_resource($this->process)) {
         $this->subprocess_write(self::COMMAND_EXIT);
         proc_close($this->process);
     }
 }
Example #17
0
 /**
  */
 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);
     }
 }
Example #18
0
 /**
  * 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;
 }
Example #19
0
 function runTest($data, array $commands, array $ini_options = null)
 {
     file_put_contents($this->tmpDir . '/xdebug-dbgp-test.php', $data);
     $i = 1;
     $socket = $this->open();
     if ($socket === false) {
         echo "Could not create socket server - already in use?\n";
         return;
     }
     $php = $this->launchPhp($ppipes, $ini_options);
     $conn = @stream_socket_accept($socket, 3);
     if ($conn === false) {
         echo @file_get_contents($this->tmpDir . '/error-output.txt'), "\n";
         echo @file_get_contents($this->tmpDir . '/remote_log.txt'), "\n";
         proc_close($php);
         return;
     }
     // read header
     $this->doRead($conn);
     foreach ($commands as $command) {
         // inject identifier
         $parts = explode(' ', $command, 2);
         if (count($parts) == 1) {
             $command = $parts[0] . " -i {$i}";
         } else {
             $command = $parts[0] . " -i {$i} " . $parts[1];
         }
         echo "-> ", $command, "\n";
         fwrite($conn, $command . "");
         $this->doRead($conn);
         $i++;
     }
     fclose($conn);
     proc_close($php);
 }
Example #20
0
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;
}
Example #21
0
 protected function scan($fileView, $filepath)
 {
     $this->status = new Status();
     $fhandler = $this->getFileHandle($fileView, $filepath);
     \OCP\Util::writeLog('files_antivirus', 'Exec scan: ' . $filepath, \OCP\Util::DEBUG);
     // using 2>&1 to grab the full command-line output.
     $cmd = escapeshellcmd($this->avPath) . " - 2>&1";
     $descriptorSpec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"));
     $pipes = array();
     $process = proc_open($cmd, $descriptorSpec, $pipes);
     if (!is_resource($process)) {
         fclose($fhandler);
         throw new \RuntimeException('Error starting process');
     }
     // write to stdin
     $shandler = $pipes[0];
     while (!feof($fhandler)) {
         $chunk = fread($fhandler, $this->chunkSize);
         fwrite($shandler, $chunk);
     }
     fclose($shandler);
     fclose($fhandler);
     $output = stream_get_contents($pipes[1]);
     fclose($pipes[1]);
     $result = proc_close($process);
     $this->status->parseResponse($output, $result);
     return $this->status->getNumericStatus();
 }
Example #22
0
 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;
 }
Example #23
0
 public function close()
 {
     @\fclose($this->stdin);
     @\fclose($this->stdout);
     @\proc_terminate($this->process, 15);
     @\proc_close($this->process);
 }
Example #24
0
 /**
  * Stop Pulsar (ReplyStack)
  */
 public static function tearDownAfterClass()
 {
     foreach (self::$pipes as $pipe) {
         fclose($pipe);
     }
     proc_close(self::$pulsarProcess);
 }
Example #25
0
 public function update()
 {
     $dbConfig = Zend_Registry::get('db')->getConfig();
     $mysqlOptions = "--host=" . escapeshellarg($dbConfig['host']) . " --user="******" --password="******" " . escapeshellarg($dbConfig['dbname']) . " ";
     $mysqlBinary = 'mysql';
     exec("which {$mysqlBinary} 2>&1", $out, $ret);
     if (!$ret) {
         $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
         $process = proc_open($mysqlBinary . ' ' . $mysqlOptions, $descriptorspec, $pipes);
         if (!is_resource($process)) {
             throw new Kwf_Exception("Can't execute mysql");
         }
         fwrite($pipes[0], $this->sql);
         fclose($pipes[0]);
         $output = stream_get_contents($pipes[1]);
         fclose($pipes[1]);
         $output .= stream_get_contents($pipes[2]);
         fclose($pipes[2]);
         if (proc_close($process) != 0) {
             throw new Kwf_Exception("Executing '{$this->_uniqueName}' sql statement failed: " . $output);
         }
     } else {
         //fallback falls kein mysql-binary vorhanden
         //regexp von http://www.dev-explorer.com/articles/multiple-mysql-queries
         $queries = preg_split("/;+(?=([^'|^\\\\']*['|\\\\'][^'|^\\\\']*['|\\\\'])*[^'|^\\\\']*[^'|^\\\\']\$)/", $this->sql);
         foreach ($queries as $query) {
             if (trim($query)) {
                 Kwf_Registry::get('db')->getConnection()->query($query);
             }
         }
     }
 }
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 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;
 }
 /**
  * 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 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;
}