Starts the authentication: Send HTTP header

@param Request $request The current request
@param Response $response The current response
@return void
513868
public function startAuthentication(Request $request, Response $response)
    {
        $response->setStatus(401);
        $response->setHeader('WWW-Authenticate', 'Basic realm="' . (isset($this->options['realm']) ? $this->options['realm'] : sha1(FLOW_PATH_ROOT)) . '"');
        $response->setContent('Authorization required');
    }
135294
public function send(\Psr\Http\Message\RequestInterface $request)
    {
        if($this->credentials instanceof Container) {
            if ($this->needsKeypairAuthentication($request)) {
                $request = $request->withHeader('Authorization', 'Bearer ' . $this->credentials->get(Keypair::class)->generateJwt());
            } else {
                $request = self::authRequest($request, $this->credentials->get(Basic::class));
            }
        } elseif($this->credentials instanceof Keypair){
            $request = $request->withHeader('Authorization', 'Bearer ' . $this->credentials->generateJwt());
        } elseif($this->credentials instanceof SignatureSecret){
            $request = self::signRequest($request, $this->credentials);
        } elseif($this->credentials instanceof Basic){
            $request = self::authRequest($request, $this->credentials);
        }

        //todo: add oauth support

        //allow any part of the URI to be replaced with a simple search
        if(isset($this->options['url'])){
            foreach($this->options['url'] as $search => $replace){
                $uri = (string) $request->getUri();

                $new = str_replace($search, $replace, $uri);
                if($uri !== $new){
                    $request = $request->withUri(new Uri($new));
                }
            }
        }

        // The user agent must be in the following format:
        // LIBRARY-NAME/LIBRARY-VERSION LANGUAGE-NAME/LANGUAGE-VERSION [APP-NAME/APP-VERSION]
        // See https://github.com/Nexmo/client-library-specification/blob/master/SPECIFICATION.md#reporting
        $userAgent = [];

        // Library name
        $userAgent[] = 'nexmo-php/'.self::VERSION;

        // Language name
        $userAgent[] = 'php/'.PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION;

        // If we have an app set, add that to the UA
        if (isset($this->options['app'])) {
            $app = $this->options['app'];
            $userAgent[] = $app['name'].'/'.$app['version'];
        }

        // Set the header. Build by joining all the parts we have with a space
        $request = $request->withHeader('User-Agent', implode(" ", $userAgent));

        $response = $this->client->sendRequest($request);
        return $response;
    }
910027
public function handleRequest(Request $request, Response $response) {
		if ($this->static_enable) {
			$request->uri = $request->server['request_uri'];
			$uri = $request->server['request_uri'];
			if (strpos($uri, $this->static_prefix) === 0) {
				$uri = substr($uri, strlen($this->static_prefix));
			}
			$path = realpath($this->static_dir . $uri);
			if ($path !== false && strpos($path, $this->static_dir) === 0) {
				if ($this->executeInterceptor('before', $request, $response) !== null) {
					$request->end();
					$response->end();
					unset($request, $response);
					return;
				}
				$response->mimeType(pathinfo($path, PATHINFO_EXTENSION));
				$response->sendfile($path);
				$this->executeInterceptor('after', $request, $response);
				$request->end();
				$response->end();
				unset($request, $response);
				return;
			}
		}
		$this->router->parse($request);
		if ($this->executeInterceptor('before', $request, $response) !== null) {
			$request->end();
			$response->end();
			unset($request, $response);
			return;
		}
		$this->dispatch($request, $response);
	}
1074326
public function send(RequestInterface $request, MessageInterface $response)
    {
        $cacheKey = $this->generateCacheKeyForRequest($request);

        if ($this->cache->contains($cacheKey)) {
            $this->hits++;

            $cachedResponse = unserialize($this->cache->fetch($cacheKey));
            /* @var $cachedResponse \Buzz\Message\Response */

            $response->setContent($cachedResponse->getContent());
            $response->setHeaders($cachedResponse->getHeaders());

            return;
        }

        $this->misses++;

        $this->client->send($request, $response);

        $this->cache->save($cacheKey, serialize($response), $this->lifetime);
    }
364649
public function api($request = null, $response = null, $sendResponse = true)
    {
        $this->klein->respond('POST', '/authenticate', $this->authenticate);
        $this->klein->onHttpError($this->handleError);

        // see https://github.com/klein/klein.php/wiki/Sub-Directory-Installation
        if ($request === null)
            $request = Request::createFromGlobals();

        // Grab the server-passed "REQUEST_URI"
        $uri = $request->server()->get('REQUEST_URI');

        // Set the request URI to a modified one (without the "subdirectory") in it
        $request->server()->set('REQUEST_URI', '/' . substr($uri, strlen($this->configuration['basePath'])));

        // Pass our request to our dispatch method
        $this->klein->dispatch($request, $response, $sendResponse);
    }
416779
public function sendHeaders(): void
	{
		// Send status header

		$protocol = $this->request->getServer()->get('SERVER_PROTOCOL', 'HTTP/1.1');

		header($protocol . ' ' . $this->statusCode . ' ' . $this->statusCodes[$this->statusCode]);

		// Send content type header

		$contentType = $this->contentType;

		if(stripos($contentType, 'text/') === 0 || in_array($contentType, ['application/json', 'application/xml', 'application/rss+xml', 'application/atom+xml']))
		{
			$contentType .= '; charset=' . $this->charset;
		}

		header('Content-Type: ' . $contentType);

		// Send other headers

		foreach($this->headers->all() as $name => $values)
		{
			foreach($values as $value)
			{
				header($name . ': ' . $value, false);
			}
		}

		// Send cookie headers

		foreach($this->cookies->all() as $cookie)
		{
			['raw' => $raw, 'name' => $name, 'value' => $value, 'options' => $options] = $cookie;

			if($raw)
			{
				setrawcookie($name, $value, $options['expires'], $options['path'], $options['domain'], $options['secure'], $options['httponly']);
			}
			else
			{
				setcookie($name, $value, $options['expires'], $options['path'], $options['domain'], $options['secure'], $options['httponly']);
			}
		}
	}
1279098
public function sendRequest(Request $request)
    {
        $response = $this->httpClient->send($request);

        $this->checkErrorResponse($response);

        return $response;
    }
36232
public function start(Request $request, AuthenticationException $authException = null)
    {
        return new Response(
            null,
            Response::HTTP_UNAUTHORIZED,
            [
                'Pragma' => 'no-cache',
                'Cache-Control' => 'no-store, private',
                'Expires' => 0,
                'WWW-Authenticate' => sprintf(
                    '%s realm="%s", error="%", error_description="%s"',
                    $this->tokenType->getName(),
                    $this->realm,
                    'invalid_token',
                    $authException->getMessage()
                )
            ]
        );
    }
750406
protected function sendHeader()
    {
        /* @var $response Doozr_Response_Web */
        $response = $this->front->getResponse();

        // Custom default header configured?
        try {
            $headers = object_to_array(
                $this->configuration->kernel->transmission->response->header->api->rest
            );

        } catch (Exception $e) {
            $headers = [];
        }

        // add our REST API Header set ... $headers
        $headers = $this->normalizeHeaders(
            merge_array($this->getDefaultApiResponseHeader(), $headers)
        );

        // Send configured header
        foreach ($headers as $header) {
            $response->sendHeader($header);
        }
    }
874298
private function sendResponse(int $requestId, ResponseInterface $response): void
    {
        $statusCode   = $response->getStatusCode();
        $reasonPhrase = $response->getReasonPhrase();

        $headerData = "Status: {$statusCode} {$reasonPhrase}\r\n";

        foreach ($response->getHeaders() as $name => $values) {
            $headerData .= $name.': '.implode(', ', $values)."\r\n";
        }

        $headerData .= "\r\n";

        $this->writeResponse($requestId, $headerData, $response->getBody()->detach());
    }
1369548
public function sendRequest(Request $request)
    {

        $result = $this->responseFactory->create();
        $client = $this->httpClientFactory->create();

        $apiData = $request->getApiData();
        $apiUrl = $request->getApiUrl();
        $apiKey = $request->getApiKey();
        $requestMethod = $request->getRequestMethod();

        $requestData = $requestMethod !== "GET" ? json_encode($apiData, JSON_UNESCAPED_SLASHES) : null;

        $client->setUri($apiUrl);

        $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);

        $headers =  [
            'User-Agent'            => 'BoltPay/Magento-'.$this->configHelper->getStoreVersion() . '/' . $this->configHelper->getModuleVersion(),
            'X-Bolt-Plugin-Version' => $this->configHelper->getModuleVersion(),
            'Content-Type'          => 'application/json',
            'Content-Length'        => $requestData ? strlen($requestData) : null,
            'X-Api-Key'             => $apiKey,
            'X-Nonce'               => rand(100000000000, 999999999999)
        ] + (array)$request->getHeaders();

        $request->setHeaders($headers);

        $this->bugsnag->registerCallback(function ($report) use ($request) {
            $report->setMetaData([
                'BOLT API REQUEST' => $request->getData()
            ]);
        });

        $client->setHeaders($headers);

        $responseBody = null;

        try {
            $response     = $client->setRawData($requestData, 'application/json')->request($requestMethod);
            $responseBody = $response->getBody();

            $this->bugsnag->registerCallback(function ($report) use ($response) {
                $report->setMetaData([
                    'BOLT API RESPONSE' => [
                        'headers' => $response->getHeaders(),
                        'body'    => $response->getBody(),
                    ]
                ]);
            });

            $this->bugsnag->registerCallback(function ($report) use ($response) {
                $headers = $response->getHeaders();
                $report->setMetaData([
                    'META DATA' => [
                        'bolt_trace_id' => @$headers[ConfigHelper::BOLT_TRACE_ID_HEADER],
                    ]
                ]);
            });
        } catch (\Exception $e) {
            throw new LocalizedException($this->wrapGatewayError($e->getMessage()));
        }

        if ($request->getStatusOnly() && $response) {
            return $response->getStatus();
        }

        if ($responseBody) {
            $resultFromJSON = json_decode($responseBody);
            $jsonError  = $this->handleJsonParseError();
            if ($jsonError != null) {
                $message = __("JSON Parse Error: " . $jsonError);
                throw new LocalizedException($message);
            }

            if ($this->isResponseError($resultFromJSON)) {
                $message = isset($resultFromJSON->errors[0]->message) ? __($resultFromJSON->errors[0]->message) :  __("Bolt API Error Response");
                throw new LocalizedException($message);
            }

            $result->setResponse($resultFromJSON);
        } else {
            throw new LocalizedException(
                __('Something went wrong in the payment gateway.')
            );
        }
        return $result;
    }
743424
public function send(Request $request)
    {
        $this->logger()->debug('Sending request. {request}', [
            'request'  => $request,
        ]);

        $response = $this->sendOrRetry($request, $request->getRetries());

        $this->logger()->debug('Response received. {response}', [
            'request'  => $request,
            'response' => $response,
        ]);

        return $response;
    }
708198
public function resolve(Request $request, Response $response)
    {
        $allowedMethods = $this->matchingRoutes->allowedMethods();
        if (!in_array(Http::OPTIONS, $allowedMethods)) {
            $allowedMethods[] = Http::OPTIONS;
        }

        $response->addHeader('Allow', join(', ', $allowedMethods))
                ->addHeader(
                        'Access-Control-Allow-Methods',
                        join(', ', $allowedMethods)
                );
    }
1017653
public function start(Request $request, AuthenticationException $authException = null)
    {
        return new RedirectResponse($this->createLoginPath($request));
    }
744540
protected function sendRequest(Request $request)
    {
        $curl = curl_init($this->getUrl($request));

        curl_setopt_array($curl, $this->curlOptions);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($request->getRequestFields()));

        $response = curl_exec($curl);

        if(curl_errno($curl))
        {
            $error_message  = 'Error occurred: ' . curl_error($curl);
            $error_code     = curl_errno($curl);
        }
        elseif(curl_getinfo($curl, CURLINFO_HTTP_CODE) != 200)
        {
            $error_code     = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            $error_message  = "Error occurred. HTTP code: '{$error_code}'";
        }

        curl_close($curl);

        if (!empty($error_message))
        {
            throw new RequestException($error_message, $error_code);
        }
        else
        {
            return $response;
        }
    }
603829
public function send(\BearFramework\App\Response $response): void
    {
        if ($this->hasEventListeners('beforeSendResponse')) {
            $this->dispatchEvent('beforeSendResponse', new \BearFramework\App\BeforeSendResponseEventDetails($response));
        }
        if (!$response->headers->exists('Content-Length')) {
            $response->headers->set($response->headers->make('Content-Length', ($response instanceof App\Response\FileReader ? (string) filesize($response->filename) : (string) strlen($response->content))));
        }
        if (!$response->headers->exists('Cache-Control')) {
            $response->headers->set($response->headers->make('Cache-Control', 'no-cache, no-store, must-revalidate, private, max-age=0'));
        }
        http_response_code($response->statusCode);
        if (!headers_sent()) {
            $headers = $response->headers->getList();
            foreach ($headers as $header) {
                if ($header->name === 'Content-Type' && $response->charset !== null) {
                    $header->value .= '; charset=' . $response->charset;
                }
                header($header->name . ': ' . $header->value);
            }
            $cookies = $response->cookies->getList();
            if ($cookies->count() > 0) {
                $baseURLParts = parse_url($this->request->base);
                foreach ($cookies as $cookie) {
                    setcookie($cookie->name, $cookie->value, $cookie->expire, $cookie->path === null ? (isset($baseURLParts['path']) ? $baseURLParts['path'] . '/' : '/') : $cookie->path, $cookie->domain === null ? (isset($baseURLParts['host']) ? $baseURLParts['host'] : '') : $cookie->domain, $cookie->secure === null ? $this->request->scheme === 'https' : $cookie->secure, $cookie->httpOnly);
                }
            }
        }
        if ($response instanceof App\Response\FileReader) {
            readfile($response->filename);
        } else {
            echo $response->content;
        }
        if ($this->hasEventListeners('sendResponse')) {
            $this->dispatchEvent('sendResponse', new \BearFramework\App\SendResponseEventDetails($response));
        }
    }
860479
protected function sendResetLinkResponse(Request $request, $response)
    {
        if ($request->expectsJson()) {
            return response()->json([
                'status' => trans($response)
            ]);
        }
        return back()->with('status', trans($response));
    }