示例#1
1
 protected function _recv()
 {
     stream_set_timeout($this->_fp, 0, $this->_timeout_recv);
     $data = fread($this->_fp, 24);
     $info = stream_get_meta_data($this->_fp);
     if ($info['timed_out']) {
         return FALSE;
     }
     $array = $this->_show_request($data);
     if ($array['bodylength']) {
         $bodylength = $array['bodylength'];
         $data = '';
         while ($bodylength > 0) {
             $recv_data = fread($this->_fp, $bodylength);
             $bodylength -= strlen($recv_data);
             $data .= $recv_data;
         }
         if ($array['extralength']) {
             $extra_unpacked = unpack('Nint', substr($data, 0, $array['extralength']));
             $array['extra'] = $extra_unpacked['int'];
         }
         $array['key'] = substr($data, $array['extralength'], $array['keylength']);
         $array['body'] = substr($data, $array['extralength'] + $array['keylength']);
     }
     return $array;
 }
 /**
  * @inheritdoc
  */
 public function send($request)
 {
     $request->prepare();
     $url = $request->getUrl();
     $method = strtoupper($request->getMethod());
     $contextOptions = ['http' => ['method' => $method, 'ignore_errors' => true], 'ssl' => ['verify_peer' => false]];
     $content = $request->getContent();
     if ($content !== null) {
         $contextOptions['http']['content'] = $content;
     }
     $headers = $request->composeHeaderLines();
     $contextOptions['http']['header'] = $headers;
     $contextOptions = ArrayHelper::merge($contextOptions, $this->composeContextOptions($request->getOptions()));
     $token = $request->client->createRequestLogToken($method, $url, $headers, $content);
     Yii::info($token, __METHOD__);
     Yii::beginProfile($token, __METHOD__);
     try {
         $context = stream_context_create($contextOptions);
         $stream = fopen($url, 'rb', false, $context);
         $responseContent = stream_get_contents($stream);
         $metaData = stream_get_meta_data($stream);
         fclose($stream);
     } catch (\Exception $exception) {
         Yii::endProfile($token, __METHOD__);
         throw $exception;
     }
     Yii::endProfile($token, __METHOD__);
     $responseHeaders = isset($metaData['wrapper_data']) ? $metaData['wrapper_data'] : [];
     return $request->client->createResponse($responseContent, $responseHeaders);
 }
 function createFile($imgURL)
 {
     $remImgURL = urldecode($imgURL);
     $urlParced = pathinfo($remImgURL);
     $remImgURLFilename = $urlParced['basename'];
     $imgData = wp_remote_get($remImgURL);
     if (is_wp_error($imgData)) {
         $badOut['Error'] = print_r($imgData, true) . " - ERROR";
         return $badOut;
     }
     $imgData = $imgData['body'];
     $tmp = array_search('uri', @array_flip(stream_get_meta_data($GLOBALS[mt_rand()] = tmpfile())));
     if (!is_writable($tmp)) {
         return "Your temporary folder or file (file - " . $tmp . ") is not witable. Can't upload images to Flickr";
     }
     rename($tmp, $tmp .= '.png');
     register_shutdown_function(create_function('', "unlink('{$tmp}');"));
     file_put_contents($tmp, $imgData);
     if (!$tmp) {
         return 'You must specify a path to a file';
     }
     if (!file_exists($tmp)) {
         return 'File path specified does not exist';
     }
     if (!is_readable($tmp)) {
         return 'File path specified is not readable';
     }
     //  $data['name'] = basename($tmp);
     return "@{$tmp}";
 }
示例#4
0
 public function analyze($handle)
 {
     $meta = stream_get_meta_data($handle);
     if (file_exists($meta['uri'])) {
         $type = 'file';
         $source = $meta['uri'];
     } else {
         $type = 'buffer';
         rewind($handle);
         $source = fread($handle, 1000000);
     }
     $result = call_user_func("finfo_{$type}", $this->_resource, $source, FILEINFO_MIME);
     if (strpos($result, 'application/ogg') === 0) {
         $full = call_user_func("finfo_{$type}", $this->_resource, $source);
         list($type, $attributes) = explode(';', $result, 2);
         if (strpos($full, 'video') !== false) {
             $type = 'video/ogg';
         } elseif (strpos($full, 'audio') !== false) {
             $type = 'audio/ogg';
         }
         return "{$type};{$attributes}";
     }
     if ($result != 'application/x-empty') {
         return $result;
     }
 }
示例#5
0
 public function testManualErrorOutputStream()
 {
     $adapter = new Stub(array('outputStream' => 'php://stderr'));
     $this->assertTrue(is_resource($adapter->getOutputStream()));
     $metaData = stream_get_meta_data($adapter->getOutputStream());
     $this->assertEquals('php://stderr', $metaData['uri']);
 }
示例#6
0
 /**
  * Set the Stream resource we use to get the email text
  * @return Object MimeMailParser Instance
  * @param $stream Resource
  */
 public function setStream($stream)
 {
     // streams have to be cached to file first
     $meta = @stream_get_meta_data($stream);
     if (!$meta || $meta['eof']) {
         throw new \Exception('setStream() expects parameter stream to be readable stream resource.');
     }
     $tmp_fp = tmpfile();
     if ($tmp_fp) {
         while (!feof($stream)) {
             fwrite($tmp_fp, fread($stream, 2028));
         }
         fseek($tmp_fp, 0);
         $this->stream =& $tmp_fp;
     } else {
         throw new \Exception('Could not create temporary files for attachments. Your tmp directory may be unwritable by PHP.');
     }
     fclose($stream);
     $this->resource = mailparse_msg_create();
     // parses the message incrementally (low memory usage but slower)
     while (!feof($this->stream)) {
         mailparse_msg_parse($this->resource, fread($this->stream, 2082));
     }
     $this->parse();
     return $this;
 }
示例#7
0
function _test_environment_getHello($url)
{
    $fp = fopen($url, 'r', false, stream_context_create(array('http' => array('method' => "GET", 'timeout' => '10', 'header' => "Accept-Encoding: deflate, gzip\r\n"))));
    $meta = stream_get_meta_data($fp);
    $encoding = '';
    $length = 0;
    foreach ($meta['wrapper_data'] as $i => $header) {
        if (preg_match('@^Content-Length:\\s*(\\d+)$@i', $header, $m)) {
            $length = $m[1];
        } elseif (preg_match('@^Content-Encoding:\\s*(\\S+)$@i', $header, $m)) {
            if ($m[1] !== 'identity') {
                $encoding = $m[1];
            }
        }
    }
    $streamContents = stream_get_contents($fp);
    fclose($fp);
    if (__FILE__ === realpath($_SERVER['SCRIPT_FILENAME'])) {
        if ($length != 6) {
            echo "\nReturned content should be 6 bytes and not HTTP encoded.\n" . "Headers returned by: {$url}\n\n";
            var_export($meta['wrapper_data']);
            echo "\n\n";
        }
    }
    return array('length' => $length, 'encoding' => $encoding, 'bytes' => $streamContents);
}
 /**
  * Format resource metadata.
  *
  * @param resource $value
  *
  * @return string
  */
 protected function formatMetadata($value)
 {
     $props = array();
     switch (get_resource_type($value)) {
         case 'stream':
             $props = stream_get_meta_data($value);
             break;
         case 'curl':
             $props = curl_getinfo($value);
             break;
         case 'xml':
             $props = array('current_byte_index' => xml_get_current_byte_index($value), 'current_column_number' => xml_get_current_column_number($value), 'current_line_number' => xml_get_current_line_number($value), 'error_code' => xml_get_error_code($value));
             break;
     }
     if (empty($props)) {
         return '{}';
     }
     $formatted = array();
     foreach ($props as $name => $value) {
         $formatted[] = sprintf('%s: %s', $name, $this->indentValue($this->presentSubValue($value)));
     }
     $template = sprintf('{%s%s%%s%s}', PHP_EOL, self::INDENT, PHP_EOL);
     $glue = sprintf(',%s%s', PHP_EOL, self::INDENT);
     return sprintf($template, implode($glue, $formatted));
 }
示例#9
0
 public function stream_open($path, $mode, $options, &$opened_path)
 {
     if (!self::$rootView) {
         self::$rootView = new OC_FilesystemView('');
     }
     $path = str_replace('crypt://', '', $path);
     if (dirname($path) == 'streams' and isset(self::$sourceStreams[basename($path)])) {
         $this->source = self::$sourceStreams[basename($path)]['stream'];
         $this->path = self::$sourceStreams[basename($path)]['path'];
         $this->size = self::$sourceStreams[basename($path)]['size'];
     } else {
         $this->path = $path;
         if ($mode == 'w' or $mode == 'w+' or $mode == 'wb' or $mode == 'wb+') {
             $this->size = 0;
         } else {
             $this->size = self::$rootView->filesize($path, $mode);
         }
         OC_FileProxy::$enabled = false;
         //disable fileproxies so we can open the source file
         $this->source = self::$rootView->fopen($path, $mode);
         OC_FileProxy::$enabled = true;
         if (!is_resource($this->source)) {
             OCP\Util::writeLog('files_encryption', 'failed to open ' . $path, OCP\Util::ERROR);
         }
     }
     if (is_resource($this->source)) {
         $this->meta = stream_get_meta_data($this->source);
     }
     return is_resource($this->source);
 }
示例#10
0
 /**
  * 
  * Support method to make the request, then return headers and content.
  * 
  * @param string $uri The URI get a response from.
  * 
  * @param array $headers A sequential array of header lines for the request.
  * 
  * @param string $content A string of content for the request.
  * 
  * @return array A sequential array where element 0 is a sequential array of
  * header lines, and element 1 is the body content.
  * 
  */
 protected function _fetch($uri, $headers, $content)
 {
     // prepare the stream context
     $context = $this->_prepareContext($headers, $content);
     // connect to the uri (suppress errors and deal with them later)
     $stream = @fopen($uri, 'r', false, $context);
     // did we hit any errors?
     if ($stream === false) {
         // the $http_response_header variable is automatically created
         // by the streams extension
         if (!empty($http_response_header)) {
             // server responded, but there's no content
             return array($http_response_header, null);
         } else {
             // no server response, must be some other error
             throw $this->_exception('ERR_CONNECTION_FAILED', error_get_last());
         }
     }
     // get the response message
     $content = stream_get_contents($stream);
     $meta = stream_get_meta_data($stream);
     fclose($stream);
     // did it time out?
     if ($meta['timed_out']) {
         throw $this->_exception('ERR_CONNECTION_TIMEOUT', array('uri' => $uri, 'meta' => $meta, 'content' => $content));
     }
     // return headers and content
     return array($meta['wrapper_data'], $content);
 }
示例#11
0
function SendMsg2Daemon($ip, $port, $msg, $timeout = 15)
{
    if (!$ip || !$port || !$msg) {
        return array(false);
    }
    $errno;
    $errstr;
    $fp = @fsockopen($ip, $port, $errno, $errstr, $timeout);
    if (!$fp) {
        return array(false);
    }
    stream_set_blocking($fp, true);
    stream_set_timeout($fp, $timeout);
    @fwrite($fp, $msg . "\n");
    $status = stream_get_meta_data($fp);
    $ret;
    if (!$status['timed_out']) {
        $datas = 'data:';
        while (!feof($fp)) {
            $data = fread($fp, 4096);
            if ($data) {
                $datas = $datas . $data;
            }
        }
        return array(true, $datas);
    } else {
        $ret = array(false);
    }
    @fclose($fp);
    return ret;
}
示例#12
0
 /**
  * Gets the metadata from a file url
  *
  * @param string %url to grab from
  * @param int $redirect whether to redirect or not
  * @return mixed stream data
  * @throws Exception if file doesn't exist.
  **/
 public static function getMetaData($url, $redirect = 1)
 {
     $context = stream_context_create(array("http" => array("follow_location" => $redirect, "ignore_errors" => true, "method" => "HEAD")));
     //"@" suppresses warnings and errors
     $fd = @fopen($url, "rb", false, $context);
     //grab the stream data
     $streamData = stream_get_meta_data($fd);
     fclose($fd);
     $wrapperData = $streamData["wrapper_data"];
     //loop through and find the "HTTP" attribute
     $http = "";
     foreach ($wrapperData as $data) {
         if (strpos($data, "HTTP") !== false) {
             $http = $data;
             break;
         }
     }
     if (strpos($http, "400")) {
         throw new Exception("Bad request");
     }
     if (strpos($http, "401")) {
         throw new Exception("Unauthorized");
     }
     if (strpos($http, "403")) {
         throw new Exception("Forbidden");
     }
     if (strpos($http, "404")) {
         throw new Exception("Not Found");
     }
     if (strpos($http, "418")) {
         throw new Exception("Get your tea set");
     }
     return $streamData;
 }
 function _sendHttpOpenSsl($msg, $server, $port, $timeout = 0, $username = '', $password = '')
 {
     if (!empty($timeout)) {
         // Set timeout
         $old_timeout = ini_get('default_socket_timeout');
         ini_set('default_socket_timeout', $timeout);
     }
     $this->_sendHttpGenerate($msg, $username, $password);
     $context = stream_context_create(array('http' => array('method' => 'POST', 'header' => preg_replace('/^.*?\\r\\n/', '', $this->headers), 'content' => $msg->payload), 'ssl' => array('verify_peer' => $this->verifyPeer, 'cafile' => $this->caFile)));
     $protocol = $this->protocol == 'ssl://' ? 'https://' : 'http://';
     $fp = @fopen("{$protocol}{$this->server}:{$port}{$this->path}", 'rb', false, $context);
     if (!empty($timeout)) {
         // Restore timeout
         ini_set('default_socket_timeout', $old_timeout);
     }
     if (!$fp) {
         $this->raiseError('Connection to RPC server ' . $server . ':' . $port . ' failed. ' . $this->errstr, XML_RPC_ERROR_CONNECTION_FAILED);
         return 0;
     }
     $resp = $msg->parseResponseFile($fp);
     $meta = stream_get_meta_data($fp);
     if ($meta['timed_out']) {
         fclose($fp);
         $this->errstr = 'RPC server did not send response before timeout.';
         $this->raiseError($this->errstr, XML_RPC_ERROR_CONNECTION_FAILED);
         return 0;
     }
     fclose($fp);
     return $resp;
 }
示例#14
0
 /**
  * Makes an HTTP request to put.io's API and returns the response.
  * Relies on native PHP functions.
  *
  * NOTE!! Due to restrictions, files must be loaded into the memory when
  * uploading. I don't recommend uploading large files using native
  * functions. Only use this if you absolutely must! Otherwise, the cURL
  * engine is much better!
  *
  * Downloading is no issue as long as you're saving the file somewhere on
  * the file system rather than the memory. Set $outFile and you're all set!
  *
  * Returns false if a file was not found.
  *
  * @param string $method      HTTP request method. Only POST and GET are
  *                                  supported.
  * @param string $url         Remote path to API module.
  * @param array  $params      Variables to be sent.
  * @param string $outFile     If $outFile is set, the response will be
  *                                  written to this file instead of StdOut.
  * @param bool   $returnBool
  * @param string $arrayKey    Will return all data on a specific array key
  *                                  of the response.
  * @param bool   $verifyPeer  If true, will use proper SSL peer/host
  *                                  verification.
  * @return mixed
  * @throws \PutIO\Exceptions\LocalStorageException
  * @throws \PutIO\Exceptions\RemoteConnectionException
  */
 public function request($method, $url, array $params = [], $outFile = '', $returnBool = \false, $arrayKey = '', $verifyPeer = \true)
 {
     list($url, $contextOptions) = $this->configureRequestOptions($url, $method, $params, $verifyPeer);
     $fp = @fopen($url, 'rb', \false, stream_context_create($contextOptions));
     $headers = stream_get_meta_data($fp)['wrapper_data'];
     return $this->handleRequest($fp, $headers, $outFile, $returnBool, $arrayKey);
 }
示例#15
0
function kill_client($port, $remipp)
{
    global $g;
    //$tcpsrv = "tcp://127.0.0.1:{$port}";
    $tcpsrv = "unix://{$g['varetc_path']}/openvpn/{$port}.sock";
    $errval;
    $errstr;
    /* open a tcp connection to the management port of each server */
    $fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
    $killed = -1;
    if ($fp) {
        stream_set_timeout($fp, 1);
        fputs($fp, "kill {$remipp}\n");
        while (!feof($fp)) {
            $line = fgets($fp, 1024);
            $info = stream_get_meta_data($fp);
            if ($info['timed_out']) {
                break;
            }
            /* parse header list line */
            if (strpos($line, "INFO:") !== false) {
                continue;
            }
            if (strpos($line, "SUCCESS") !== false) {
                $killed = 0;
            }
            break;
        }
        fclose($fp);
    }
    return $killed;
}
示例#16
0
 /**
  * Initialize a new stream listener
  */
 public function __construct($stream)
 {
     $this->stream = $stream;
     stream_set_blocking($this->stream, 0);
     $meta = stream_get_meta_data($this->stream);
     if (substr($meta['mode'], -1) === '+') {
         $this->writable = true;
         $this->readable = true;
     } else {
         if (strpos($meta['mode'], 'r') !== false) {
             $this->readable = true;
         }
         if (strpos($meta['mode'], 'w') !== false) {
             $this->writable = true;
         }
     }
     if ($this->readable) {
         $this->ev_read = event_new();
         event_set($this->ev_read, $this->stream, EV_READ | EV_PERSIST, array($this, '_read'));
         Loop::attachEvent($this->ev_read);
     }
     if ($this->writable) {
         $this->ev_write = event_new();
         event_set($this->ev_write, $this->stream, EV_WRITE | EV_PERSIST, array($this, '_write'));
         Loop::attachEvent($this->ev_write);
     }
 }
 public function load($var, $level = 1)
 {
     if (!$this->isResource($var)) {
         throw new InvalidVariableTypeException();
     }
     $this->level = $level;
     $this->resourceType = get_resource_type($var);
     $this->resourceId = (int) $var;
     if ($this->resourceType == 'stream') {
         $stream_vars = stream_get_meta_data($var);
         // prevent unix sistems getting stream in files
         if (isset($stream_vars['stream_type']) && $stream_vars['stream_type'] == 'STDIO') {
             $this->resourceType = 'file';
         }
     }
     $this->variableWrapper = new VariableWrapper($this->getResourceType(), $var, VariableWrapper::TYPE_RESOURCE);
     // metadata
     if ($this->metadataResolver->has($this->variableWrapper)) {
         $metadata = $this->metadataResolver->get($this->variableWrapper);
         if (array_key_exists('help_link', $metadata)) {
             $this->helpLink = $metadata['help_link'];
         }
         if (array_key_exists('icon', $metadata)) {
             $this->icon = $metadata['icon'];
         }
         if (array_key_exists('version', $metadata)) {
             $this->version = $metadata['version'];
         }
     }
     // Resource data
     $this->loadData($var);
 }
示例#18
0
 /**
  * Execute a HTTP request.
  * 
  * @param string $url
  * @param array  $options
  * 
  * @return mixed         
  */
 public function request($url, $options = array())
 {
     // parse request
     $request = $this->parseRequest($url, $options);
     // create stream options
     $options = array('http' => array('method' => $request['method'], 'protocol_version' => $request['version'], 'max_redirects' => $request['redirects'], 'timeout' => $request['timeout'], 'ignore_errors' => true, 'content' => $request['body']));
     // create header string
     $options['http']['header'] = $this->buildHeader($request['header']);
     if (!empty($request['cookies'])) {
         $options['http']['header'] .= $this->buildCookies($request['cookies']);
     }
     // connect with fopen and streams
     $res = false;
     $fp = @fopen($url, 'r', false, stream_context_create($options));
     $res = stream_get_contents($fp);
     $meta = stream_get_meta_data($fp);
     fclose($fp);
     // parse response
     $res = $this->parseResponse((isset($meta['wrapper_data']) ? implode($this->line_break, $meta['wrapper_data']) . $this->line_break . $this->line_break : null) . $res);
     // save to file
     if ($res && $request['file'] && file_put_contents($request['file'], $res['body']) === false) {
         return false;
     }
     return $res;
 }
示例#19
0
 /**
  * @test
  */
 public function fromFile_exceed_buffer()
 {
     //Create a 10k temp file
     $temp = tmpfile();
     fwrite($temp, str_repeat("1", 10000));
     $meta_data = stream_get_meta_data($temp);
     $filename = $meta_data["uri"];
     /** @var LoopInterface $loop */
     $loop = \EventLoop\getLoop();
     $source = new FromFileObservable($filename);
     $result = false;
     $complete = false;
     $error = false;
     $source->subscribe(new CallbackObserver(function ($value) use(&$result) {
         $result = $value;
     }, function ($e) use(&$error) {
         $error = true;
     }, function () use(&$complete) {
         $complete = true;
     }));
     $loop->tick();
     $this->assertEquals("4096", strlen($result));
     $this->assertFalse($complete);
     $this->assertFalse($error);
     $loop->tick();
     $this->assertEquals("4096", strlen($result));
     $this->assertFalse($complete);
     $this->assertFalse($error);
     $loop->tick();
     $this->assertEquals("1808", strlen($result));
     $this->assertTrue($complete);
     $this->assertFalse($error);
 }
示例#20
0
文件: Output.php 项目: fpoirotte/xrl
 /**
  * Create a new outputter.
  *
  * \param resource $stream
  *      The PHP stream this outputter
  *      will write to.
  */
 public function __construct($stream)
 {
     if (@stream_get_meta_data($stream) === null) {
         throw new \InvalidArgumentException('Not a valid stream');
     }
     $this->stream = $stream;
 }
示例#21
0
 /**
  * Execute a HTTP request to the remote server
  *
  * Returns the result from the remote server.
  *
  * @param string $method
  * @param string $path
  * @param \eZ\Publish\Core\REST\Common\Message $message
  *
  * @return \eZ\Publish\Core\REST\Common\Message
  */
 public function request($method, $path, Message $message = null)
 {
     $message = $message ?: new Message();
     $requestHeaders = $this->getRequestHeaders($message->headers);
     $url = $this->server . $path;
     $contextOptions = array('http' => array('method' => $method, 'content' => $message->body, 'ignore_errors' => true, 'header' => $requestHeaders, 'follow_location' => 0));
     $httpFilePointer = @fopen($url, 'r', false, stream_context_create($contextOptions));
     // Check if connection has been established successfully
     if ($httpFilePointer === false) {
         throw new ConnectionException($this->server, $path, $method);
     }
     // Read request body
     $body = '';
     while (!feof($httpFilePointer)) {
         $body .= fgets($httpFilePointer);
     }
     $metaData = stream_get_meta_data($httpFilePointer);
     // This depends on PHP compiled with or without --curl-enable-streamwrappers
     $rawHeaders = isset($metaData['wrapper_data']['headers']) ? $metaData['wrapper_data']['headers'] : $metaData['wrapper_data'];
     $headers = array();
     foreach ($rawHeaders as $lineContent) {
         // Extract header values
         if (preg_match('(^HTTP/(?P<version>\\d+\\.\\d+)\\s+(?P<status>\\d+))S', $lineContent, $match)) {
             $headers['version'] = $match['version'];
             $headers['status'] = (int) $match['status'];
         } else {
             list($key, $value) = explode(':', $lineContent, 2);
             $headers[$key] = ltrim($value);
         }
     }
     return new Message($headers, $body, $headers['status']);
 }
示例#22
0
 protected function readBuffer($resource)
 {
     if ($this->ssl === true) {
         $buffer = fread($resource, 8192);
         // extremely strange chrome behavior: first frame with ssl only contains 1 byte?!
         if (strlen($buffer) === 1) {
             $buffer .= fread($resource, 8192);
         }
         return $buffer;
     } else {
         $buffer = '';
         $buffsize = 8192;
         $metadata['unread_bytes'] = 0;
         do {
             if (feof($resource)) {
                 return false;
             }
             $result = fread($resource, $buffsize);
             if ($result === false || feof($resource)) {
                 return false;
             }
             $buffer .= $result;
             $metadata = stream_get_meta_data($resource);
             $buffsize = $metadata['unread_bytes'] > $buffsize ? $buffsize : $metadata['unread_bytes'];
         } while ($metadata['unread_bytes'] > 0);
         return $buffer;
     }
 }
示例#23
0
 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;
 }
示例#24
0
 /**
  * @param resource $stream
  * @param int $limit
  * @return resource
  */
 public static function wrap($stream, $limit)
 {
     $id = uniqid();
     self::register($id, $stream, $limit);
     $meta = stream_get_meta_data($stream);
     return fopen('quota://' . $id, $meta['mode']);
 }
示例#25
0
 protected function performHandshake()
 {
     $request = '';
     do {
         $buffer = stream_get_line($this->socket, 1024, "\r\n");
         $request .= $buffer . "\n";
         $metadata = stream_get_meta_data($this->socket);
     } while (!feof($this->socket) && $metadata['unread_bytes'] > 0);
     if (!preg_match('/GET (.*) HTTP\\//mUi', $request, $matches)) {
         throw new ConnectionException("No GET in request:\n" . $request);
     }
     $get_uri = trim($matches[1]);
     $uri_parts = parse_url($get_uri);
     $this->request = explode("\n", $request);
     $this->request_path = $uri_parts['path'];
     /// @todo Get query and fragment as well.
     if (!preg_match('#Sec-WebSocket-Key:\\s(.*)$#mUi', $request, $matches)) {
         throw new ConnectionException("Client had no Key in upgrade request:\n" . $request);
     }
     $key = trim($matches[1]);
     /// @todo Validate key length and base 64...
     $response_key = base64_encode(pack('H*', sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
     $header = "HTTP/1.1 101 Switching Protocols\r\n" . "Upgrade: websocket\r\n" . "Connection: Upgrade\r\n" . "Sec-WebSocket-Accept: {$response_key}\r\n" . "\r\n";
     $this->write($header);
     $this->is_connected = true;
 }
 /**
  * Publishes the given source stream to this target, with the given relative path.
  *
  * @param resource $sourceStream Stream of the source to publish
  * @param string $relativeTargetPathAndFilename relative path and filename in the target directory
  * @throws Exception
  * @throws \TYPO3\Flow\Utility\Exception
  */
 protected function publishFile($sourceStream, $relativeTargetPathAndFilename)
 {
     $streamMetaData = stream_get_meta_data($sourceStream);
     if ($streamMetaData['wrapper_type'] !== 'plainfile' || $streamMetaData['stream_type'] !== 'STDIO') {
         throw new Exception(sprintf('Could not publish stream "%s" into resource publishing target "%s" because the source is not a local file.', $streamMetaData['uri'], $this->name), 1416242392);
     }
     $sourcePathAndFilename = $streamMetaData['uri'];
     $targetPathAndFilename = $this->path . $relativeTargetPathAndFilename;
     if (@stat($sourcePathAndFilename) === false) {
         throw new Exception(sprintf('Could not publish "%s" into resource publishing target "%s" because the source file is not accessible (file stat failed).', $sourcePathAndFilename, $this->name), 1415716366);
     }
     if (!file_exists(dirname($targetPathAndFilename))) {
         Files::createDirectoryRecursively(dirname($targetPathAndFilename));
     }
     try {
         if (Files::is_link($targetPathAndFilename)) {
             Files::unlink($targetPathAndFilename);
         }
         $temporaryTargetPathAndFilename = uniqid($targetPathAndFilename . '.') . '.tmp';
         symlink($sourcePathAndFilename, $temporaryTargetPathAndFilename);
         $result = rename($temporaryTargetPathAndFilename, $targetPathAndFilename);
     } catch (\Exception $exception) {
         $result = false;
     }
     if ($result === false) {
         throw new Exception(sprintf('Could not publish "%s" into resource publishing target "%s" because the source file could not be symlinked at target location.', $sourcePathAndFilename, $this->name), 1415716368, isset($exception) ? $exception : null);
     }
     $this->systemLogger->log(sprintf('FileSystemSymlinkTarget: Published file. (target: %s, file: %s)', $this->name, $relativeTargetPathAndFilename), LOG_DEBUG);
 }
/**
 * NOTE: This function is incomplete, the fallback is to '/tmp' which targets Unix-like.
 *
 * @return string
 */
function php_sys_get_temp_dir()
{
    // (PHP 5 >= 5.2.1)
    if (function_exists('sys_get_temp_dir')) {
        return sys_get_temp_dir();
    }
    // (PHP 4 >= 4.3.0, PHP 5)
    if (function_exists('stream_get_meta_data')) {
        $handle = tmpfile();
        // (PHP 4, PHP 5)
        $meta = stream_get_meta_data($handle);
        // (PHP 5 >= 5.1.0)
        if (isset($meta['uri'])) {
            return dirname($meta['uri']);
        }
    }
    // emulate  PHP 4 <= 4.0.6 tempnam() behavior, fragile
    foreach (array('TMPDIR', 'TMP') as $key) {
        if (isset($_ENV[$key])) {
            return $_ENV[$key];
        }
    }
    // fallback for Unix-like (php_shell specifically)
    return '/tmp';
}
示例#28
0
 /**
  * Output json
  *
  * @param  array  data to output
  * @return void
  * @author Dmitry (dio) Levashov
  **/
 protected function output(array $data)
 {
     $header = isset($data['header']) ? $data['header'] : $this->header;
     unset($data['header']);
     $headers = array();
     if ($header) {
         foreach ((array) $header as $headerString) {
             if (strpos($headerString, ':') !== false) {
                 list($key, $value) = explode(':', $headerString, 2);
                 $headers[$key] = $value;
             }
         }
     }
     if (isset($data['pointer'])) {
         $this->response = new StreamedResponse(function () use($data) {
             if (stream_get_meta_data($data['pointer'])['seekable']) {
                 rewind($data['pointer']);
             }
             fpassthru($data['pointer']);
             if (!empty($data['volume'])) {
                 $data['volume']->close($data['pointer'], $data['info']['hash']);
             }
         }, 200, $headers);
     } else {
         if (!empty($data['raw']) && !empty($data['error'])) {
             $this->response = new JsonResponse($data['error'], 500);
         } else {
             $this->response = new JsonResponse($data, 200, $headers);
         }
     }
 }
示例#29
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;
}
示例#30
0
 /**
  * Generate real image.
  * @param resource $image
  * @param string $format
  * @return \App\Libraries\Image
  */
 private static function generateRealImage($image, $format)
 {
     $tempFile = tmpfile();
     $metaDatas = stream_get_meta_data($tempFile);
     $tmpFilename = $metaDatas['uri'];
     fclose($tempFile);
     switch ($format) {
         case Objects\Image::PNG:
             imagepng($image, $tmpFilename);
             break;
         case Objects\Image::JPG:
             imagejpeg($image, $tmpFilename);
             break;
         case Objects\Image::GIF:
             imagegif($image, $tmpFilename);
             break;
         default:
             $format = Objects\Image::PNG;
             imagepng($image, $tmpFilename);
             break;
     }
     $formatedFilename = $tmpFilename . "." . $format;
     @rename($tmpFilename, $formatedFilename);
     imagedestroy($image);
     return new Objects\Image($formatedFilename, $format);
 }