fetch file from remote destination

@param RequestInterface $request request

@return string
346284
private function fetchFile(RequestInterface $request)
    {
        $content = "{}";
        try {
            $response = $this->client->send($request);
            $content = (string) $response->getBody();
            if (isset($this->cache)) {
                $this->cache->save($this->options['storeKey'], $content, $this->cacheLifetime);
            }
        } catch (RequestException $e) {
            $this->logger->info(
                "Unable to fetch File!",
                [
                    "message" => $e->getMessage(),
                    "url" => $request->getRequestTarget(),
                    "code" => (!empty($e->getResponse())? $e->getResponse()->getStatusCode() : 500)
                ]
            );
        }

        return $content;
    }
73291
private function getCookiePathFromRequest(RequestInterface $request)
    {
        $uriPath = $request->getUri()->getPath();
        if (''  === $uriPath) {
            return '/';
        }
        if (0 !== strpos($uriPath, '/')) {
            return '/';
        }
        if ('/' === $uriPath) {
            return '/';
        }
        if (0 === $lastSlashPos = strrpos($uriPath, '/')) {
            return '/';
        }

        return substr($uriPath, 0, $lastSlashPos);
    }
1175094
private function determineRemoteFromRequest(RequestInterface $request)
    {
        if (!$request->hasHeader('Host') && '' === $request->getUri()->getHost()) {
            throw new InvalidRequestException('Remote is not defined and we cannot determine a connection endpoint for this request (no Host header)', $request);
        }

        $host = $request->getUri()->getHost();
        $port = $request->getUri()->getPort() ?: ('https' === $request->getUri()->getScheme() ? 443 : 80);
        $endpoint = sprintf('%s:%s', $host, $port);

        // If use the host header if present for the endpoint
        if (empty($host) && $request->hasHeader('Host')) {
            $endpoint = $request->getHeaderLine('Host');
        }

        if ($this->hasAsync) {
            return sprintf('async-tcp://%s', $endpoint);
        }

        return sprintf('tcp://%s', $endpoint);
    }
22662
protected function provideFromRequest(RequestInterface $request, string $field) : string
    {
        Assert::isInstanceOf($request, ServerRequest::class);

        $data = $request->getData();

        $result = is_array($data) && array_key_exists($field, $data) ? (string)$data[$field] : '';

        return $result;
    }
276459
protected function getCacheKey(RequestInterface $request)
    {
        // Allow cache.key_filter to trim down the URL cache key by removing generate query string values (e.g. auth)
        if ($filter = $request->getParams()->get('cache.key_filter')) {
            $url = $request->getUrl(true);
            foreach (explode(',', $filter) as $remove) {
                $url->getQuery()->remove(trim($remove));
            }
        } else {
            $url = $request->getUrl();
        }

        return $this->keyPrefix . md5($request->getMethod() . ' ' . $url);
    }
1015901
public function sendRequest(RequestInterface $request)
    {
        if ($request instanceof InternalRequestInterface) {
            return $this->sendInternalRequest($request);
        }

        $protocolVersion = $this->getConfiguration()->getProtocolVersion();
        $this->getConfiguration()->setProtocolVersion($request->getProtocolVersion());

        $response = $this->send(
            $request->getUri(),
            $request->getMethod(),
            $request->getHeaders(),
            $request->getBody()
        );

        $this->getConfiguration()->setProtocolVersion($protocolVersion);

        return $response;
    }
916963
public function toString(RequestInterface $request)
    {
        $string = sprintf(
            "%s %s HTTP/%s\n",
            $request->getMethod(),
            $request->getRequestTarget(),
            $request->getProtocolVersion()
        );

        $string .= $this->headersAndBody($request);

        return $string;
    }
236943
private function getLocalIp(ServerRequestInterface $request)
    {
        $server = $request->getServerParams();
        $ip = trim($server['REMOTE_ADDR'] ?? '', '[]');

        if (self::isValid($ip)) {
            return $ip;
        }
    }
791927
protected function createBaseUrl(RequestInterface $request)
    {
        $url = $this->getUrl();

        if ($request instanceof ContextualizedRequestInterface) {
            $url .= '/'.$request->buildContext();
        }

        return $url;
    }
201883
public function httpGet(RequestInterface $request, ResponseInterface $response)
    {
        $queryParams = $request->getQueryParameters();
        if (!array_key_exists('export', $queryParams)) {
            return;
        }

        $path = $request->getPath();

        $node = $this->server->tree->getNodeForPath($path);

        if (!($node instanceof IAddressBook)) {
            return;
        }

        $this->server->transactionType = 'get-addressbook-export';

        // Checking ACL, if available.
        if ($aclPlugin = $this->server->getPlugin('acl')) {
            $aclPlugin->checkPrivileges($path, '{DAV:}read');
        }

        $nodes = $this->server->getPropertiesForPath($path, [
            '{'.Plugin::NS_CARDDAV.'}address-data',
        ], 1);

        $format = 'text/directory';

        $output = null;
        $filenameExtension = null;

        switch ($format) {
            case 'text/directory':
                $output = $this->generateVCF($nodes);
                $filenameExtension = '.vcf';
                break;
        }

        $filename = preg_replace(
            '/[^a-zA-Z0-9-_ ]/um',
            '',
            $node->getName()
        );
        $filename .= '-'.date('Y-m-d').$filenameExtension;

        $response->setHeader('Content-Disposition', 'attachment; filename="'.$filename.'"');
        $response->setHeader('Content-Type', $format);

        $response->setStatus(200);
        $response->setBody($output);

        // Returning false to break the event chain
        return false;
    }
646197
protected function _pathFrom(RequestInterface $request)
    {
        $uriPath = $request->path();
        if ($uriPath === '') {
            return '/';
        }
        if (strpos($uriPath, '/') !== 0) {
            return '/';
        }
        if ($uriPath === '/') {
            return '/';
        }
        if (($lastSlashPos = strrpos($uriPath, '/')) === 0) {
            return '/';
        }

        return substr($uriPath, 0, $lastSlashPos);
    }
180799
protected function getLogLevel(RequestInterface $request)
    {
        if (!$this->logLevel) {
            return $this->getDefaultLogLevel();
        }

        if (is_callable($this->logLevel)) {
            return call_user_func($this->logLevel, $request);
        }

        return (string) $this->logLevel;
    }
1121914
protected function doRequest(RequestInterface $request)
    {
        // Create the stream context options array with the required method offset.
        $options = ['method' => $request->getMethod()];

        // Set HTTP Version
        $options['protocol_version'] = $request->getProtocolVersion();

        // If data exists let's encode it and make sure our Content-Type header is set.
        $data = (string) $request->getBody();

        if (isset($data)) {
            // If the data is a scalar value simply add it to the stream context options.
            if (is_scalar($data)) {
                $options['content'] = $data;
            } else // Otherwise we need to encode the value first.
            {
                $options['content'] = http_build_query($data);
            }

            if (!$request->getHeader('Content-Type')) {
                $request = $request->withHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
            }

            // Add the relevant headers.
            $request = $request->withHeader('Content-Length', (string) strlen($options['content']));
        }

        // Speed up stream get URL
        // @see http://stackoverflow.com/questions/3629504/php-file-get-contents-very-slow-when-using-full-url
        // @see http://stackoverflow.com/questions/13679976/how-to-speed-up-file-get-contents
        $request = $request->withHeader('Connection', 'Close');

        // Build the headers string for the request.
        if ($headers = $request->getHeaders()) {
            // Add the headers string into the stream context options array.
            $options['header'] = HeaderHelper::toHeaderLine($headers, true);
        }

        // If an explicit timeout is given user it.
        if ($this->getOption('timeout')) {
            $options['timeout'] = (int) $this->getOption('timeout');
        }

        // If an explicit user agent is given use it.
        if ($this->getOption('userAgent')) {
            $options['user_agent'] = $this->getOption('userAgent');
        }

        // Ignore HTTP errors so that we can capture them.
        $options['ignore_errors'] = 1;

        // Follow redirects.
        $options['follow_location'] = (int) $this->getOption('follow_location', 1);

        foreach ((array) $this->getOption('options') as $key => $value) {
            $options[$key] = $value;
        }

        // Create the stream context for the request.
        $context = stream_context_create(['http' => $options]);

        // Capture PHP errors
        $php_errormsg = '';
        $track_errors = ini_get('track_errors');
        ini_set('track_errors', '1');

        $connection = @fopen($request->getRequestTarget(), Stream::MODE_READ_ONLY_FROM_BEGIN, false, $context);

        if (!$connection) {
            if (!$php_errormsg) {
                // Error but nothing from php? Create our own
                $php_errormsg = sprintf('Could not connect to resource: %s', $request->getRequestTarget());
            }

            // Restore error tracking to give control to the exception handler
            ini_set('track_errors', $track_errors);

            throw new \RuntimeException($php_errormsg);
        }

        $stream = new Stream($connection);

        if ($dest = $this->getOption('target_file')) {
            $content = '';
            StreamHelper::copyTo($stream, $dest);
        } else {
            $content = $stream->getContents();
        }

        $metadata = $stream->getMetadata();

        $stream->close();

        if (isset($metadata['wrapper_data']['headers'])) {
            $headers = $metadata['wrapper_data']['headers'];
        } elseif (isset($metadata['wrapper_data'])) {
            $headers = $metadata['wrapper_data'];
        } else {
            $headers = [];
        }

        return $this->getResponse($headers, $content);
    }
974264
public function httpGet(RequestInterface $request, ResponseInterface $response)
    {
        // We're not using straight-up $_GET, because we want everything to be
        // unit testable.
        $getVars = $request->getQueryParameters();

        // CSP headers
        $response->setHeader('Content-Security-Policy', "default-src 'none'; img-src 'self'; style-src 'self'; font-src 'self';");

        $sabreAction = isset($getVars['sabreAction']) ? $getVars['sabreAction'] : null;

        switch ($sabreAction) {
            case 'asset':
                // Asset handling, such as images
                $this->serveAsset(isset($getVars['assetName']) ? $getVars['assetName'] : null);

                return false;
            default:
            case 'info':
                try {
                    $this->server->tree->getNodeForPath($request->getPath());
                } catch (DAV\Exception\NotFound $e) {
                    // We're simply stopping when the file isn't found to not interfere
                    // with other plugins.
                    return;
                }

                $response->setStatus(200);
                $response->setHeader('Content-Type', 'text/html; charset=utf-8');

                $response->setBody(
                    $this->generateDirectoryIndex($request->getPath())
                );

                return false;

            case 'plugins':
                $response->setStatus(200);
                $response->setHeader('Content-Type', 'text/html; charset=utf-8');

                $response->setBody(
                    $this->generatePluginListing()
                );

                return false;
        }
    }
96452
public function getFileAction(Request $request)
    {
        $customerClient = $this->getFactory()->createCustomerClient();
        $customerTransfer = $customerClient->getCustomer();

        if (!$customerTransfer) {
            return $this->redirectResponseInternal(PayoneControllerProvider::ROUTE_LOGIN);
        }

        $getFileTransfer = new PayoneGetFileTransfer();
        $getFileTransfer->setReference($request->query->get('id'));
        $getFileTransfer->setCustomerId($customerTransfer->getIdCustomer());

        $response = $this->getClient()->getFile($getFileTransfer);

        if ($response->getStatus() === 'ERROR') {
            return $this->viewResponse(['errormessage' => $response->getCustomerErrorMessage()]);
        }

        $callback = function () use ($response) {
            echo base64_decode($response->getRawResponse());
        };

        return $this->streamedResponse($callback, 200, ["Content-type" => "application/pdf"]);
    }
1307508
private function getCacheKey(RequestInterface $request)
    {
        return implode('|', [$request->getIndex(), $request->getType(), $request->getQueryText()]);
    }
416928
public function httpGet(RequestInterface $request, ResponseInterface $response)
    {
        $node = $this->server->tree->getNodeForPath($request->getPath());
        if ($node instanceof DAV\IFile) {
            return;
        }

        $subRequest = clone $request;
        $subRequest->setMethod('PROPFIND');

        $this->server->invokeMethod($subRequest, $response);

        return false;
    }