Execute read request

@throws Exception\ServiceReaderException
@return OpenCalaisResponse
17081
protected function executeRequest()
    {
        if (!is_callable('curl_init')) {
            throw new Exception\ServiceReaderException('cURL not found.');
        }

        $options  = 'licenseID='  . urlencode($this->apiKey);
        $options .= '&paramsXML=' . urlencode($this->request->generateXMLRequestString());
        $options .= '&content='   . urlencode($this->request->getTextData());

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $this->getApiEndpoint());
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $options);
        curl_setopt($ch, CURLOPT_POST, 1);
        $response = curl_exec($ch);
        curl_close($ch);

        if (strpos($response, "<Exception>") !== false) {
            preg_match("/<Exception\>(.*)<\/Exception>/mu", $response, $matches);
            throw new Exception\ServiceReaderException($matches[1]);
        }

        return new OpenCalaisResponse($response, $this->request);
    }
1118466
public function onRead()
    {
        start:
        if ($this->state === self::STATE_ROOT) {
            $header = $this->readExact(8);

            if ($header === false) {
                return;
            }

            $this->header = unpack('Cver/Ctype/nreqid/nconlen/Cpadlen/Creserved', $header);

            if ($this->header['conlen'] > 0) {
                $this->setWatermark($this->header['conlen'], $this->header['conlen']);
            }
            $type = $this->header['type'];
            $this->header['ttype'] = isset(self::$requestTypes[$type]) ? self::$requestTypes[$type] : $type;
            $rid = $this->header['reqid'];
            $this->state = self::STATE_CONTENT;
        } else {
            $type = $this->header['type'];
            $rid = $this->header['reqid'];
        }
        if ($this->state === self::STATE_CONTENT) {
            $this->content = $this->readExact($this->header['conlen']);

            if ($this->content === false) {
                $this->setWatermark($this->header['conlen'], $this->header['conlen']);
                return;
            }

            if ($this->header['padlen'] > 0) {
                $this->setWatermark($this->header['padlen'], $this->header['padlen']);
            }

            $this->state = self::STATE_PADDING;
        }

        if ($this->state === self::STATE_PADDING) {
            $pad = $this->readExact($this->header['padlen']);

            if ($pad === false) {
                return;
            }
        }
        $this->setWatermark(8, 0xFFFFFF);
        $this->state = self::STATE_ROOT;

//        /*Daemon::log('[DEBUG] FastCGI-record ' . $this->header['ttype'] . '). Request ID: ' . $rid
//                . '. Content length: ' . $this->header['conlen'] . ' (' . mb_orig_strlen($this->content) . ') Padding length: ' . $this->header['padlen']
//                . ' (' . mb_orig_strlen($pad) . ')');*/

        if ($type === self::FCGI_BEGIN_REQUEST) {
            $u = unpack('nrole/Cflags', $this->content);

            $req = new \stdClass();
            $req->attrs = new \stdClass;
            $req->attrs->request = [];
            $req->attrs->get = [];
            $req->attrs->post = [];
            $req->attrs->cookie = [];
            $req->attrs->server = [];
            $req->attrs->files = [];
            $req->attrs->session = null;
            $req->attrs->role = self::$roles[$u['role']];
            $req->attrs->flags = $u['flags'];
            $req->attrs->id = $this->header['reqid'];
            $req->attrs->paramsDone = false;
            $req->attrs->inputDone = false;
            $req->attrs->input = new \PHPDaemon\HTTPRequest\Input();
            $req->attrs->chunked = false;
            $req->attrs->noHttpVer = true;
            $req->queueId = $rid;
            $this->requests[$rid] = $req;
        } elseif (isset($this->requests[$rid])) {
            $req = $this->requests[$rid];
        } else {
            Daemon::log('Unexpected FastCGI-record #' . $this->header['type'] . ' (' . $this->header['ttype'] . '). Request ID: ' . $rid . '.');
            return;
        }

        if ($type === self::FCGI_ABORT_REQUEST) {
            $req->abort();
        } elseif ($type === self::FCGI_PARAMS) {
            if ($this->content === '') {
                if (!isset($req->attrs->server['REQUEST_TIME'])) {
                    $req->attrs->server['REQUEST_TIME'] = time();
                }
                if (!isset($req->attrs->server['REQUEST_TIME_FLOAT'])) {
                    $req->attrs->server['REQUEST_TIME_FLOAT'] = microtime(true);
                }
                $req->attrs->paramsDone = true;

                $req = Daemon::$appResolver->getRequest($req, $this);

                if ($req instanceof \stdClass) {
                    $this->endRequest($req, 0, 0);
                    unset($this->requests[$rid]);
                } else {
                    if ($this->pool->config->sendfile->value
                        && (
                            !$this->pool->config->sendfileonlybycommand->value
                            || isset($req->attrs->server['USE_SENDFILE'])
                        )
                        && !isset($req->attrs->server['DONT_USE_SENDFILE'])
                    ) {
                        $fn = tempnam(
                            $this->pool->config->sendfiledir->value,
                            $this->pool->config->sendfileprefix->value
                        );

                        $req->sendfp = fopen($fn, 'wb');
                        $req->header('X-Sendfile: ' . $fn);
                    }

                    $this->requests[$rid] = $req;

                    $req->callInit();
                }
            } else {
                $p = 0;

                while ($p < $this->header['conlen']) {
                    if (($namelen = ord($this->content{$p})) < 128) {
                        ++$p;
                    } else {
                        $u = unpack(
                            'Nlen',
                            chr(ord($this->content{$p}) & 0x7f) . mb_orig_substr($this->content, $p + 1, 3)
                        );
                        $namelen = $u['len'];
                        $p += 4;
                    }

                    if (($vlen = ord($this->content{$p})) < 128) {
                        ++$p;
                    } else {
                        $u = unpack(
                            'Nlen',
                            chr(ord($this->content{$p}) & 0x7f) . mb_orig_substr($this->content, $p + 1, 3)
                        );
                        $vlen = $u['len'];
                        $p += 4;
                    }

                    $req->attrs->server[mb_orig_substr($this->content, $p, $namelen)] = mb_orig_substr(
                        $this->content,
                        $p + $namelen,
                        $vlen
                    );
                    $p += $namelen + $vlen;
                }
            }
        } elseif ($type === self::FCGI_STDIN) {
            if (!$req->attrs->input) {
                goto start;
            }
            if ($this->content === '') {
                $req->attrs->input->sendEOF();
            } else {
                $req->attrs->input->readFromString($this->content);
            }
        }

        if ($req->attrs->inputDone && $req->attrs->paramsDone) {
            $order = $this->pool->variablesOrder ?: 'GPC';
            for ($i = 0, $s = mb_orig_strlen($order); $i < $s; ++$i) {
                $char = $order[$i];

                if ($char === 'G' && is_array($req->attrs->get)) {
                    $req->attrs->request += $req->attrs->get;
                } elseif ($char === 'P' && is_array($req->attrs->post)) {
                    $req->attrs->request += $req->attrs->post;
                } elseif ($char === 'C' && is_array($req->attrs->cookie)) {
                    $req->attrs->request += $req->attrs->cookie;
                }
            }

            Daemon::$process->timeLastActivity = time();
        }
        goto start;
    }
1155323
final public function read(): Promise
    {
        if ($this->promise) {
            throw new \Error("Cannot stream message data once a buffered message has been requested");
        }

        return $this->lastRead = $this->stream->read();
    }
1355801
public function execute()
    {
        parent::execute();

        $client = ServicesContainer::instance()->getClient();
        return $client->processReport($this);
    }
513267
public function read(RequestInterface $request)
    {
        if (!$request instanceof UclassifyRequest) {
            throw new \InvalidArgumentException("Expected instance of UclassifyRequest, got ".get_class($request));
        }
        $this->request = $request;

        return $this->executeRequest();
    }
567887
public function request(): Request
    {
        try {
            $request = $this->container->get(Request::class);
        } catch (ContainerExceptionInterface $e) {
            throw new ScopeException(
                "Unable to get `ServerRequestInterface` in active container scope",
                $e->getCode(),
                $e
            );
        }

        //Flushing input state
        if ($this->request !== $request) {
            $this->bags = [];
            $this->request = $request;
        }

        return $this->request;
    }
1060420
public function onRead()
    {
        start:
        if ($this->freed) {
            return;
        }
        if ($this->state === self::STATE_ROOT) {
            if (false === ($hdr = $this->readExact(16))) {
                return; // we do not have a header
            }
            $this->hdr = unpack('Vlen/VreqId/VresponseTo/VopCode', $hdr);
            $this->hdr['plen'] = $this->hdr['len'] - 16;
            $this->setWatermark($this->hdr['plen'], $this->hdr['plen']);
            $this->state = self::STATE_PACKET;
        }
        if ($this->state === self::STATE_PACKET) {
            if (false === ($pct = $this->readExact($this->hdr['plen']))) {
                return; //we do not have a whole packet
            }
            $this->state = self::STATE_ROOT;
            $this->setWatermark(16, 0xFFFFFF);
            if ($this->hdr['opCode'] === Pool::OP_REPLY) {
                $r = unpack('Vflag/VcursorID1/VcursorID2/Voffset/Vlength', mb_orig_substr($pct, 0, 20));
                $r['cursorId'] = mb_orig_substr($pct, 4, 8);
                $id = (int)$this->hdr['responseTo'];
                if (isset($this->requests[$id])) {
                    $req = $this->requests[$id];
                    if (sizeof($req) === 1) { // get more
                        $r['cursorId'] = $req[0];
                    }
                } else {
                    $req = false;
                }
                $flagBits = str_pad(strrev(decbin($r['flag'])), 8, '0', STR_PAD_LEFT);
                $curId = ($r['cursorId'] !== "\x00\x00\x00\x00\x00\x00\x00\x00" ? 'c' . $r['cursorId'] : 'r' . $this->hdr['responseTo']);

                if ($req && isset($req[2]) && ($req[2] === false) && !isset($this->cursors[$curId])) {
                    $cur = new Cursor($curId, $req[0], $this);
                    $this->cursors[$curId] = $cur;
                    $cur->failure = $flagBits[1] === '1';
                    $cur->await = $flagBits[3] === '1';
                    $cur->callback = $req[1];
                    $cur->parseOplog = isset($req[3]) && $req[3];
                    $cur->tailable = isset($req[4]) && $req[4];
                } else {
                    $cur = isset($this->cursors[$curId]) ? $this->cursors[$curId] : false;
                }
                if ($cur && (($r['length'] === 0) || (mb_orig_substr($curId, 0, 1) === 'r'))) {
                    if ($cur->tailable) {
                        if ($cur->finished = ($flagBits[0] === '1')) {
                            $cur->destroy();
                        }
                    } else {
                        $cur->finished = true;
                    }
                }

                $p = 20;
                $items = [];
                while ($p < $this->hdr['plen']) {
                    $dl = unpack('Vlen', mb_orig_substr($pct, $p, 4));
                    $doc = bson_decode(mb_orig_substr($pct, $p, $dl['len']));

                    if ($cur) {
                        if ($cur->parseOplog && isset($doc['ts'])) {
                            $tsdata = unpack('Vsec/Vinc', mb_orig_substr($pct, $p + 8, 8));
                            $doc['ts'] = $tsdata['sec'] . ' ' . $tsdata['inc'];
                        }
                        $cur->items[] = $doc;
                        ++$cur->counter;
                    } else {
                        $items[] = $doc;
                    }
                    $p += $dl['len'];
                }
                $this->setFree(true);
                if (isset($req[2]) && $req[2] && $req[1]) {
                    $req[1](sizeof($items) ? $items[0] : false);

                    if ($cur) {
                        if ($cur instanceof Cursor) {
                            $cur->destroy();
                        } else {
                            unset($this->cursors[$curId]);
                        }
                    }
                } elseif ($cur) {
                    $func = $cur->callback;
                    $func($cur);
                }
                unset($this->requests[$id]);
                $req = null;
            }
        }
        goto start;
    }
1358227
public function index()
    {
        $this->authorize('readList', Block::class);
        $input   = $this->validator->validate('list');
        $params  = $this->processor->process($input)->getProcessedFields();
        $results = $this->repository->getBlocks(
            $params['filter'],
            $params['orderBy'],
            $params['page'],
            $params['perPage']
        );
        return $this->respondWithSuccess($results, new BlockTransformer);
    }
1015535
protected function read()
    {
        $method = '__'.str_replace(__CLASS__.'::', '', __METHOD__);

        if ($this->hasMethod($method) && is_callable([$this, $method])) {
            $arguments = func_get_args();
            if (empty($arguments)) {
                $result = $this->{$method}();
            } else {
                $result = call_user_func_array([$this, $method], $arguments);
            }

            return $result;
        }
    }
333321
public function execute()
	{
		// open a Redis connection and execute the queued commands
		foreach ($this->queue as $command)
		{
			for ($written = 0; $written < strlen($command); $written += $fwrite)
			{
				$fwrite = fwrite($this->connection, substr($command, $written));
				if ($fwrite === false)
				{
					throw new \RedisException('Failed to write entire command to stream');
				}
			}
		}

		// Read in the results from the pipelined commands
		$responses = array();
		for ($i = 0; $i < count($this->queue); $i++)
		{
			$responses[] = $this->readResponse();
		}

		// Clear the queue and return the response
		$this->queue = array();

		if ($this->pipelined)
		{
			$this->pipelined = false;
			return $responses;
		}
		else
		{
			return $responses[0];
		}
	}
1340582
public function load(): ResponseInterface
    {
        if (false === mb_strpos($this->file, '://')) {
            if (!is_file($this->file)) {
                throw new Exception('The given local file [' . $this->file . '] is not a file', Exception::LOCAL_FILE_NOT_READABLE);
            }

            if (!is_readable($this->file)) {
                throw new Exception('The given local file [' . $this->file . '] is not readable', Exception::LOCAL_FILE_NOT_READABLE);
            }
        }

        $stream = fopen($this->file, 'rb', false);

        if (false === $stream) {
            throw new Exception('could not read content from the given local file  [' . $this->file . ']', Exception::LOCAL_FILE_NOT_READABLE);
        }

        return new Response(200, [], new Stream($stream));
    }
1094707
public function read(Request $request)
    {
        if (!$request->cookies->has($this->cookieSettings->getName())) {
            return null;
        }

        return $this->createCookieWithValue(
            $request->cookies->get($this->cookieSettings->getName())
        );
    }
952633
private static function read()
	{
		self::lock();
		if ( is_null( self::$authFileP ) ) throw new Exception( 'No lock has been requested' );
		return stream_get_contents( self::$authFileP , -1 , 0 );
	}
1338424
protected function getOpenedServiceClient()
    {
        if (!isset($this->openedClient)) {
            $this->openedClient = $this->getOpenedClient(new ServiceClient());
        }

        return $this->openedClient;
    }
286150
public function getReadConcern()
    {
        if ($this->_readConcern !== null) {
            if (is_scalar($this->_readConcern)) {
                $this->_readConcern = new ReadConcern($this->_readConcern);
            }
        }
        return $this->_readConcern;
    }
527390
public function index()
    {
        $this->authorize('readList', File::class);
        $input  = $this->validator->validate('list');
        $params = $this->processor->process($input)->getProcessedFields();
        $query  = QueryBuilder::with($params['filter'], $params['orderBy'], $params['query']);
        $query->setPageSize($params['perPage']);
        $results = $this->fileRepo->getFiles($query, $params['page']);
        return $this->respondWithSuccess($results, new FileTransformer);
    }
455196
public function onRead()
    {
        if ($this->state === self::STATE_BODY) {
            goto body;
        }
        if ($this->reqType === null) {
            if ($this->requests->isEmpty()) {
                $this->finish();
                return;
            }
            $this->reqType = $this->requests->shift();
        }
        while (($line = $this->readLine()) !== null) {
            if ($line !== '') {
                if ($this->rawHeaders !== null) {
                    $this->rawHeaders[] = $line;
                }
            } else {
                if (isset($this->headers['HTTP_CONTENT_LENGTH'])) {
                    $this->contentLength = (int)$this->headers['HTTP_CONTENT_LENGTH'];
                } else {
                    $this->contentLength = -1;
                }
                if (isset($this->headers['HTTP_TRANSFER_ENCODING'])) {
                    $e = explode(', ', strtolower($this->headers['HTTP_TRANSFER_ENCODING']));
                    $this->chunked = in_array('chunked', $e, true);
                } else {
                    $this->chunked = false;
                }
                if (isset($this->headers['HTTP_CONNECTION'])) {
                    $e = explode(', ', strtolower($this->headers['HTTP_CONNECTION']));
                    $this->keepalive = in_array('keep-alive', $e, true);
                }
                if (isset($this->headers['HTTP_CONTENT_TYPE'])) {
                    parse_str('type=' . strtr($this->headers['HTTP_CONTENT_TYPE'], [';' => '&', ' ' => '']), $p);
                    $this->contentType = $p['type'];
                    if (isset($p['charset'])) {
                        $this->charset = strtolower($p['charset']);
                    }
                }
                if ($this->contentLength === -1 && !$this->chunked && !$this->keepalive) {
                    $this->eofTerminated = true;
                }
                if ($this->reqType === 'HEAD') {
                    $this->requestFinished();
                } else {
                    $this->state = self::STATE_BODY;
                }
                break;
            }
            if ($this->state === self::STATE_ROOT) {
                $this->headers['STATUS'] = $line;
                $e = explode(' ', $this->headers['STATUS']);
                $this->responseCode = isset($e[1]) ? (int)$e[1] : 0;
                $this->state = self::STATE_HEADERS;
            } elseif ($this->state === self::STATE_HEADERS) {
                $e = explode(': ', $line);

                if (isset($e[1])) {
                    $k = 'HTTP_' . strtoupper(strtr($e[0], Generic::$htr));
                    if ($k === 'HTTP_SET_COOKIE') {
                        parse_str(strtr($e[1], [';' => '&', ' ' => '']), $p);
                        if (sizeof($p)) {
                            $this->cookie[$k = key($p)] =& $p;
                            $p['value'] = $p[$k];
                            unset($p[$k], $p);
                        }
                    }
                    if (isset($this->headers[$k])) {
                        if (is_array($this->headers[$k])) {
                            $this->headers[$k][] = $e[1];
                        } else {
                            $this->headers[$k] = [$this->headers[$k], $e[1]];
                        }
                    } else {
                        $this->headers[$k] = $e[1];
                    }
                }
            }
        }
        if ($this->state !== self::STATE_BODY) {
            return; // not enough data yet
        }
        body:
        if ($this->eofTerminated) {
            $body = $this->readUnlimited();
            if ($this->chunkcb) {
                $func = $this->chunkcb;
                $func($body);
            }
            $this->body .= $body;
            return;
        }
        if ($this->chunked) {
            chunk:
            if ($this->curChunkSize === null) { // outside of chunk
                $l = $this->readLine();
                if ($l === '') { // skip empty line
                    goto chunk;
                }
                if ($l === null) {
                    return; // not enough data yet
                }
                if (!ctype_xdigit($l)) {
                    $this->protocolError = __LINE__;
                    $this->finish(); // protocol error
                    return;
                }
                $this->curChunkSize = hexdec($l);
            }
            if ($this->curChunkSize !== null) {
                if ($this->curChunkSize === 0) {
                    if ($this->readLine() === '') {
                        $this->requestFinished();
                        return;
                    } else { // protocol error
                        $this->protocolError = __LINE__;
                        $this->finish();
                        return;
                    }
                }
                $n = $this->curChunkSize - mb_orig_strlen($this->curChunk);
                $this->curChunk .= $this->read($n);
                if ($this->curChunkSize <= mb_orig_strlen($this->curChunk)) {
                    if ($this->chunkcb) {
                        $func = $this->chunkcb;
                        $func($this->curChunk);
                    }
                    $this->body .= $this->curChunk;
                    $this->curChunkSize = null;
                    $this->curChunk = '';
                    goto chunk;
                }
            }
        } else {
            $body = $this->read($this->contentLength - mb_orig_strlen($this->body));
            if ($this->chunkcb) {
                $func = $this->chunkcb;
                $func($body);
            }
            $this->body .= $body;
            if (($this->contentLength !== -1) && (mb_orig_strlen($this->body) >= $this->contentLength)) {
                $this->requestFinished();
            }
        }
    }