Download available data on socket.

@throws Exception
@return bool    TRUE when there are any requests on queue, FALSE when finished
175919
public function socketPerform()
    {
        if ($this->count() == 0) {
            throw new Exception('Cannot perform if there are no requests in queue.');
        }

        $notRunning = $this->getRequestsNotRunning();
        do {
            /**
             * Apply cURL options to new requests
             */
            foreach ($notRunning as $request) {
                $this->getDefaultOptions()->applyTo($request);
                $request->getOptions()->applyTo($request);
                curl_multi_add_handle($this->mh, $request->getHandle());
                $this->running[$request->getUID()] = $request;
            }

            $runningHandles = null;
            do {
                // http://curl.haxx.se/libcurl/c/curl_multi_perform.html
                // If an added handle fails very quickly, it may never be counted as a running_handle.
                $mrc = curl_multi_exec($this->mh, $runningHandles);
            } while ($mrc === CURLM_CALL_MULTI_PERFORM);

            if ($runningHandles < count($this->running)) {
                $this->read();
            }

            $notRunning = $this->getRequestsNotRunning();
        } while (count($notRunning) > 0);
        // Why the loop? New requests might be added at runtime on 'complete' event.
        // So we need to attach them to curl_multi handle immediately.

        return $this->count() > 0;
    }
9020
public function &readBuffer($length) {

            if ($length+$this->cursor > strlen($this->rawData)) {
                throw new Exception('Buffer underrun at position: '. $this->cursor . '. Trying to fetch '. $length . ' bytes');
                return false;
            }
            $data = substr($this->rawData,$this->cursor,$length);
            $this->cursor+=$length;
            return $data;

        }
926092
public function read()
    {
        // First, read headers only
        $response = '';
        $gotStatus = false;

        while (($line = @fgets($this->socket)) !== false) {
            $gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false);
            if ($gotStatus) {
                $response .= $line;
                if (rtrim($line) === '') break;
            }
        }

        $this->_checkSocketReadTimeout();

        $statusCode = Zend_Http_Response::extractCode($response);

        // Handle 100 and 101 responses internally by restarting the read again
        if ($statusCode == 100 || $statusCode == 101) return $this->read();

        // Check headers to see what kind of connection / transfer encoding we have
        $headers = Zend_Http_Response::extractHeaders($response);

        /**
         * Responses to HEAD requests and 204 or 304 responses are not expected
         * to have a body - stop reading here
         */
        if ($statusCode == 304 || $statusCode == 204 ||
            $this->method == Zend_Http_Client::HEAD) {

            // Close the connection if requested to do so by the server
            if (isset($headers['connection']) && $headers['connection'] == 'close') {
                $this->close();
            }
            return $response;
        }

        // If we got a 'transfer-encoding: chunked' header
        if (isset($headers['transfer-encoding'])) {

            if (strtolower($headers['transfer-encoding']) == 'chunked') {

                do {
                    $line  = @fgets($this->socket);
                    $this->_checkSocketReadTimeout();

                    $chunk = $line;

                    // Figure out the next chunk size
                    $chunksize = trim($line);
                    if (! ctype_xdigit($chunksize)) {
                        $this->close();

                        throw new Zend_Http_Client_Adapter_Exception('Invalid chunk size "' .
                            $chunksize . '" unable to read chunked body');
                    }

                    // Convert the hexadecimal value to plain integer
                    $chunksize = hexdec($chunksize);

                    // Read next chunk
                    $read_to = ftell($this->socket) + $chunksize;

                    do {
                        $current_pos = ftell($this->socket);
                        if ($current_pos >= $read_to) break;

                        if($this->out_stream) {
                            if(stream_copy_to_stream($this->socket, $this->out_stream, $read_to - $current_pos) == 0) {
                              $this->_checkSocketReadTimeout();
                              break;
                             }
                        } else {
                            $line = @fread($this->socket, $read_to - $current_pos);
                            if ($line === false || strlen($line) === 0) {
                                $this->_checkSocketReadTimeout();
                                break;
                            }
                                    $chunk .= $line;
                        }
                    } while (! feof($this->socket));

                    $chunk .= @fgets($this->socket);
                    $this->_checkSocketReadTimeout();

                    if(!$this->out_stream) {
                        $response .= $chunk;
                    }
                } while ($chunksize > 0);
            } else {
                $this->close();

                throw new Zend_Http_Client_Adapter_Exception('Cannot handle "' .
                    $headers['transfer-encoding'] . '" transfer encoding');
            }

            // We automatically decode chunked-messages when writing to a stream
            // this means we have to disallow the Zend_Http_Response to do it again
            if ($this->out_stream) {
                $response = str_ireplace("Transfer-Encoding: chunked\r\n", '', $response);
            }
        // Else, if we got the content-length header, read this number of bytes
        } elseif (isset($headers['content-length'])) {

            // If we got more than one Content-Length header (see ZF-9404) use
            // the last value sent
            if (is_array($headers['content-length'])) {
                $contentLength = $headers['content-length'][count($headers['content-length']) - 1];
            } else {
                $contentLength = $headers['content-length'];
            }

            $current_pos = ftell($this->socket);
            $chunk = '';

            for ($read_to = $current_pos + $contentLength;
                 $read_to > $current_pos;
                 $current_pos = ftell($this->socket)) {

                 if($this->out_stream) {
                     if(@stream_copy_to_stream($this->socket, $this->out_stream, $read_to - $current_pos) == 0) {
                          $this->_checkSocketReadTimeout();
                          break;
                     }
                 } else {
                    $chunk = @fread($this->socket, $read_to - $current_pos);
                    if ($chunk === false || strlen($chunk) === 0) {
                        $this->_checkSocketReadTimeout();
                        break;
                    }

                    $response .= $chunk;
                }

                // Break if the connection ended prematurely
                if (feof($this->socket)) break;
            }

        // Fallback: just read the response until EOF
        } else {

            do {
                if($this->out_stream) {
                    if(@stream_copy_to_stream($this->socket, $this->out_stream) == 0) {
                          $this->_checkSocketReadTimeout();
                          break;
                     }
                }  else {
                    $buff = @fread($this->socket, 8192);
                    if ($buff === false || strlen($buff) === 0) {
                        $this->_checkSocketReadTimeout();
                        break;
                    } else {
                        $response .= $buff;
                    }
                }

            } while (feof($this->socket) === false);

            $this->close();
        }

        // Close the connection if requested to do so by the server
        if (isset($headers['connection']) && $headers['connection'] == 'close') {
            $this->close();
        }

        return $response;
    }
1104894
public function load()
	{
		$filename = $this->getFile();
		if (!file_exists($filename))
			return;

		$json = file_get_contents($filename);
		if (strlen($json) == 0)
			return;

		$data = $this->decode($json);
		if ($data === null)
			throw new Exception('Error while trying to decode ' . $filename . '.');

		$this->data = $data;

		if (!$this->verify())
			throw new Exception($filename . ' failed checksum validation.');
	}
721050
public function write()
    {
        if (!count($this->sndQueue)) {
            return false;
        }

        $line   = array_shift($this->sndQueue);
        $logger = \Plop\Plop::getInstance();

        // Make sure we send the whole line,
        // with a trailing CR LF sequence.
        $eol    = $this->eol[count($this->eol) - 1];
        $line  .= $eol;
        $len    = strlen($line);
        for ($written = 0; $written < $len; $written += $fwrite) {
            $fwrite = @fwrite($this->socket, substr($line, $written));
            if ($fwrite === false) {
                return false;
            }
        }
        $line = substr($line, 0, -strlen($eol));
        $logger->debug(
            '%(line)s',
            array('line' => addcslashes($line, "\000..\037"))
        );
        return $written;
    }
772715
public function download()
    {
        try {
            $result = $this->getSoapClient()->DownloadImage(array(
                'filename' => basename($this->filename) ,
            ));

            return base64_decode($result->DownloadImageResult);
        } catch ( SoapException $e ) {
            throw new DownloadException('Error while downloading the image' , $e);
        }
    }
209726
public function fetch()
        {
            try {
                if ($this->values = $this->statement->fetch(\PDO::FETCH_ASSOC)) {
                    return $this->values;
                } else {
                    return false;
                }
            } catch (\PDOException $e) {
                throw new Exception('An error occured while trying to fetch the result: "' . $e->getMessage() . '"');
            }
        }
37019
public function open()
    {

        $this->log('open socket connection');
        $this->socket = @stream_socket_client($this->remote_socket,  $errno, $errstr, $this->timeout);

        if ($this->socket) {

            return true;
        } else {
            throw(new \Exception("{$errstr} (#{$errno})"));
        }
    }
547015
public function download()
    {
        try{
            $this->checkIfTaskIdExists();

            $taskLogEntity = $this->getTaskLogService()->getByIdAndUser(
                $this->getRequestParameter(self::PARAMETER_TASK_ID),
                $this->getSessionUserUri()
            );

            if (!$taskLogEntity->getStatus()->isCompleted()) {
                throw new \common_Exception('Task "'. $taskLogEntity->getId() .'" is not downloadable.');
            }

            $fileNameOrSerial = $taskLogEntity->getFileNameFromReport();

            if (empty($fileNameOrSerial)) {
                throw new \common_Exception('Filename not found in report.');
            }

            // first try to get a referenced file is it is a serial
            $file = $this->getReferencedFile($fileNameOrSerial);

            // if no file let's try the task queue storage
            if (is_null($file)) {
                $file = $this->getQueueStorageFile($fileNameOrSerial);
            }

            if (!$file) {
                throw new \common_exception_NotFound('File not found.');
            }

            header('Set-Cookie: fileDownload=true');
            setcookie('fileDownload', 'true', 0, '/');
            header('Content-Disposition: attachment; filename="' . $file->getBasename() . '"');
            header('Content-Type: ' . $file->getMimeType());

            \tao_helpers_Http::returnStream($file->readPsrStream());
            exit();
        } catch (\Exception $e) {
            return $this->returnJson([
                'success' => false,
                'errorMsg' => $e instanceof \common_exception_UserReadableException ? $e->getUserMessage() : $e->getMessage(),
                'errorCode' => $e->getCode(),
            ]);
        }
    }
1046072
public function eof() : bool
    {
        if ($this->closed) {
            throw new IoException('The stream is closed.');
        }

        try {
            return ErrorCatcher::run(function() {
                return feof($this->handle);
            });
        } catch (\ErrorException $e) {
            throw new IoException($e->getMessage(), 0, $e);
        }
    }
1104733
private function downloadContent()
    {
        $params = [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_URL => $this->url,
        ];
        if (false === $this->allow_unsecured_connection) {
            $params[CURLOPT_SSL_VERIFYPEER] = true;
            $params[CURLOPT_SSL_VERIFYHOST] = 2;
        }

        $ch = curl_init();
        curl_setopt_array($ch, $params);
        if (!empty($this->custom_headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $this->custom_headers);
        }
        $content = curl_exec($ch);

        try {
            Assertion::false(false === $content, 'Failed to load JWK contents: ');
        } catch (\Assert\AssertionFailedException $e) {
            $curlError = curl_error($ch);
            $curlErrorNumber = curl_errno($ch);

            throw new \InvalidArgumentException(
                $e->getMessage().$curlError,
                $curlErrorNumber
            );
        } catch (\Exception $e) {
            throw new \InvalidArgumentException(
                'Failed to load JWK contents: '.$e->getMessage(),
                0
            );
        } finally {
            curl_close($ch);
        }

        return $content;
    }
941129
public function execute() {
        if(is_null($this->client)) {
            $this->client = $this->getConnection();
        }
        if(is_null($this->query)) {
            throw new Exception('No query');
        }

        list($query_data, $meta) = $this->constructQuery($this->source, $this->query, $this->aggs, $this->post_query, $this->settings);

        $results_set = $this->query($query_data, $meta);
        $results = $this->processResults($results_set, $meta);
        $results = $this->postProcessResults($this->post_query, $results, $meta);

        return $results;
    }
1199191
public function download() {
        \core\session\manager::write_close();
        $this->out($this->get_total_responses_count(), false);
        exit;
    }
1233857
public function recv()
    {
        if(!$this->connected || !$this->connect())
        {
            return false;
        }
        $meta = fread($this->socket, 4);
        if('' === $meta || false === $meta)
        {
            $this->close();
            return false;
        }
        $length = unpack('N', $meta)[1];
        $data = fread($this->socket, $length);
        if(false === $data || !isset($data[$length - 1]))
        {
            $this->close();
            return false;
        }
        $result = ($this->unserialize)($data);
        if($result instanceof Result)
        {
            return $result;
        }
        else
        {
            return false;
        }
    }
1220502
protected function fill()
    {
        if (count($this) <= 0) {
            return;
        }

        $read = $this->sockets;
        $write = null;
        $except = null;
        $time = count($this->results) > 0 ? 0 : $this->timeout;

        if (stream_select($read, $write, $except, $time) > 0) {
            foreach ($read as $socket) {
                try {
                    $result = $this->read($socket);
                } catch (\RuntimeException $e) {
                    continue;
                }
                $this->results->enqueue($result);
                $this->remain--;
            }
        }
    }
450774
private function RunRequest()
    {
        $result = curl_exec($this->_curlHandle);
        if ($result === false && curl_errno($this->_curlHandle) != 0) {
            $this->logger->error("cURL error: " . curl_error($this->_curlHandle));
            throw new Exception('cURL error: ' . curl_error($this->_curlHandle));
        }

        $response = new HttpResponse();
        $response->ResponseCode = (int) curl_getinfo($this->_curlHandle, CURLINFO_HTTP_CODE);

        curl_close($this->_curlHandle);

        $explode = explode("\r\n\r\n", $result);

        // multiple query (follow redirect) take only the last request
        $explode = array_slice($explode, sizeof($explode) - 2, 2);

        $response->Headers = explode("\n", implode($explode));
        $response->Body = array_pop($explode);

        return $response;
    }
825662
public function receive()
    {
        // Read data from the socket
        socket_recv($this->socket, $msg, $this->buffer, MSG_DONTWAIT);

        if ($msg === false) {
            return null;
        }

        // Trim the padding from the message content
        $msg = trim($msg);

        // If message is not valid JSON, return it verbatim
        if (json_decode($msg) === null) {
            return $msg;
        }

        // Decode and return the message content
        return json_decode($msg);
    }