public function signRequest(RequestInterface $request, CredentialsInterface $credentials) { $params = Psr7\parse_query($request->getBody()); $params['Timestamp'] = gmdate('c'); $params['SignatureVersion'] = '2'; $params['SignatureMethod'] = 'HmacSHA256'; $params['AWSAccessKeyId'] = $credentials->getAccessKeyId(); if ($token = $credentials->getSecurityToken()) { $params['SecurityToken'] = $token; } // build string to sign $sign = $request->getMethod() . "\n" . $request->getHeaderLine('Host') . "\n" . '/' . "\n" . $this->getCanonicalizedParameterString($params); $params['Signature'] = base64_encode(hash_hmac('sha256', $sign, $credentials->getSecretKey(), true)); return $request->withBody(Psr7\stream_for(http_build_query($params))); }
/** * {@inheritDoc} */ public function signResponse(ResponseInterface $response) { $authHeader = AuthorizationHeader::createFromRequest($this->request); $parts = [$authHeader->getNonce(), $this->request->getHeaderLine('X-Authorization-Timestamp'), (string) $response->getBody()]; $message = implode("\n", $parts); $signature = $this->digest->sign($message, $this->key->getSecret()); /** @var \Psr\Http\Message\ResponseInterface $response */ $response = $response->withHeader('X-Server-Authorization-HMAC-SHA256', $signature); return $response; }
/** * Returns the override method. * * @param RequestInterface $request * * @return string|null */ private function getOverrideMethod(RequestInterface $request) { $method = $request->getHeaderLine(self::HEADER); if (!empty($method) && $method !== $request->getMethod()) { return strtoupper($method); } }
/** * Render a PSR-7 request. * * @param RequestInterface $request * @return string */ public function renderRequest(RequestInterface $request) { $return = ''; $return .= sprintf("URL: %s\n", $request->getUri()); $return .= sprintf("METHOD: %s\n", $request->getMethod()); if ($request->getHeaders()) { $return .= 'HEADERS:'; } $indent = false; foreach ($request->getHeaders() as $name => $values) { if ($indent) { $return .= str_repeat(' ', 8); } $return .= sprintf(" %s: %s\n", $name, implode(', ', $values)); $indent = true; } if ($body = (string) $request->getBody()) { $return .= 'BODY: '; switch ($request->getHeaderLine('Content-Type')) { case 'application/json': $return .= json_encode(json_decode($body, true), JSON_PRETTY_PRINT); break; default: $return .= $body; break; } $return .= "\n"; } return $return; }
/** * @param RequestInterface $request * @return string[] */ protected function getRequestHeaders(RequestInterface $request) { $headers = array(); foreach (array_keys($request->getHeaders()) as $name) { $headers[] = $name . ': ' . $request->getHeaderLine($name); } return $headers; }
/** * Is the strategy acceptable for this request? * * @param \Psr\Http\Message\RequestInterface $request The request * * @return bool Returns true on success, false otherwise */ public function isAcceptable(RequestInterface $request) { $accept = $request->getHeaderLine('Accept'); if ($accept && preg_match('#^application/([^+\\s]+\\+)?json#', $accept)) { return true; } return false; }
/** * Execute the middleware. * * @param RequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next) { $authorization = self::parseAuthorizationHeader($request->getHeaderLine('Authorization')); if ($authorization && $this->checkUserPassword($authorization['username'], $authorization['password'])) { return $next($request, $response); } return $response->withStatus(401)->withHeader('WWW-Authenticate', 'Basic realm="' . $this->realm . '"'); }
public function render(RequestInterface $request, ResponseInterface $response, $data) { $mediaType = $this->determineMediaType($request->getHeaderLine('Accept')); $output = $this->renderOutput($mediaType, $data); $response = $this->writeBody($response, $output); $response = $response->withHeader('Content-type', $mediaType); return $response; }
public function detect() { if ($this->detected === null) { $headers = $this->request->getHeaders(); $userAgent = $this->request->getHeaderLine('user-agent'); if ($this->detector->isMobile($headers, $userAgent)) { $this->detected = 'mobile'; } else { if ($this->detector->isTablet($headers, $userAgent)) { $this->detected = 'tablet'; } else { $this->detected = 'desktop'; } } } return $this->detected; }
/** * Normalizes the custom headers for signing. * * @return string[] * An array of normalized headers. */ protected function normalizeCustomHeaders() { $headers = []; // The spec requires that headers are sorted by header name. sort($this->headers); foreach ($this->headers as $header) { if ($this->request->hasHeader($header)) { $headers[] = strtolower($header) . ':' . $this->request->getHeaderLine($header); } } return $headers; }
/** * Take a request and update the $_SERVER global to match * * @param RequestInterface $request */ private function forgeServerGlobal(RequestInterface $request) { $_SERVER['REQUEST_URI'] = $request->getUri()->getPath(); $_SERVER['REQUEST_METHOD'] = $request->getMethod(); $_SERVER['QUERY_STRING'] = $request->getUri()->getQuery(); if ($request->hasHeader('Content-Type')) { $_SERVER['CONTENT_TYPE'] = $request->getHeaderLine('Content-Type'); } if ($request->hasHeader('Referer')) { $_SERVER['HTTP_REFERER'] = $request->getHeaderLine('Referer'); } if ($request->hasHeader('X-Requested-with')) { $_SERVER['HTTP_X_REQUESTED_WITH'] = $request->getHeaderLine('X-Requested-With'); } if ($request->hasHeader('User-Agent')) { $_SERVER['HTTP_USER_AGENT'] = $request->getHeaderLine('User-Agent'); } if ($request->hasHeader('X-Forwarded-For')) { $_SERVER['HTTP_X_FORWARDED_FOR'] = $request->getHeaderLine('X-Forwarded-For'); } return $this; }
public function render(RequestInterface $request, ResponseInterface $response, $data) { $mediaType = $this->determineMediaType($request->getHeaderLine('Accept')); $mediaSubType = explode('/', $mediaType)[1]; $dataIsValidForMediatype = $this->isDataValidForMediaType($mediaSubType, $data); if (!$dataIsValidForMediatype) { throw new RuntimeException('Data for mediaType ' . $mediaType . ' must be ' . implode($this->mediaSubtypesToAllowedDataTypesMap[$mediaSubType], ' or ')); } $output = $this->renderOutput($mediaType, $data); $response = $this->writeBody($response, $output); $response = $response->withHeader('Content-type', $mediaType); return $response; }
/** * Login or check the user credentials. * * @param RequestInterface $request * * @return bool */ private function login(RequestInterface $request) { //Check header $authorization = self::parseAuthorizationHeader($request->getHeaderLine('Authorization')); if (!$authorization) { return false; } //Check whether user exists if (!isset($this->users[$authorization['username']])) { return false; } //Check authentication return $this->checkAuthentication($authorization, $request->getMethod(), $this->users[$authorization['username']]); }
public function render(RequestInterface $request, ResponseInterface $response, $data) { $contentType = $this->determineMediaType($request->getHeaderLine('Accept')); $output = $this->renderOutput($contentType, $data); $response = $this->writeBody($response, $output); // set the HAL content type for JSON or XML if (stripos($contentType, 'json')) { $contentType = 'application/hal+json'; } elseif (stripos($contentType, 'xml')) { $contentType = 'application/hal+xml'; } $response = $response->withHeader('Content-type', $contentType); return $response; }
/** * @param RequestInterface $request */ private function assertValidBody(RequestInterface $request) { $body = $request->getBody()->getContents(); $method = $request->getMethod(); $path = $request->getUri()->getPath(); $contentType = $request->getHeaderLine('Content-Type'); $schemaBody = $this->schemaHelper->getRequestBody($method, $path, $contentType); try { $schemaBody->getSchema()->validate($body); } catch (InvalidSchemaException $exception) { $message = sprintf('Request body for %s %s with content type %s does not match schema: %s', strtoupper($method), $path, $contentType, $this->getSchemaErrorsAsString($exception->getErrors())); throw new ValidatorRequestException($message, 0, $exception); } }
/** * @param RequestInterface $request * * @return string */ private function getHeadersAsCommandOptions(RequestInterface $request) { $command = ''; foreach ($request->getHeaders() as $name => $values) { if ('host' === strtolower($name) && $values[0] === $request->getUri()->getHost()) { continue; } if ('user-agent' === strtolower($name)) { $command .= sprintf('-A %s', escapeshellarg($values[0])); continue; } $command .= sprintf(' -H %s', escapeshellarg($name . ': ' . $request->getHeaderLine($name))); } return $command; }
protected function getPayload(RequestInterface $request) { // Calculate the request signature payload if ($request->hasHeader('X-Amz-Content-Sha256')) { // Handle streaming operations (e.g. Glacier.UploadArchive) return $request->getHeaderLine('X-Amz-Content-Sha256'); } if (!$request->getBody()->isSeekable()) { throw new CouldNotCreateChecksumException('sha256'); } try { return Psr7\hash($request->getBody(), 'sha256'); } catch (\Exception $e) { throw new CouldNotCreateChecksumException('sha256', $e); } }
/** * {@inheritDoc} */ public static function createFromRequest(RequestInterface $request) { if (!$request->hasHeader('Authorization')) { throw new MalformedRequestException('Authorization header is required.', null, 0, $request); } $header = $request->getHeaderLine('Authorization'); $id_match = preg_match('/.*id="(.*?)"/', $header, $id_matches); $realm_match = preg_match('/.*realm="(.*?)"/', $header, $realm_matches); $nonce_match = preg_match('/.*nonce="(.*?)"/', $header, $nonce_matches); $version_match = preg_match('/.*version="(.*?)"/', $header, $version_matches); $signature_match = preg_match('/.*signature="(.*?)"/', $header, $signature_matches); $headers_match = preg_match('/.*headers="(.*?)"/', $header, $headers_matches); if (!$id_match || !$realm_match || !$nonce_match || !$version_match || !$signature_match) { throw new MalformedRequestException('Authorization header requires a realm, id, version, nonce and a signature.', null, 0, $request); } $customHeaders = !empty($headers_matches[1]) ? explode('%3B', $headers_matches[1]) : []; return new static(rawurldecode($realm_matches[1]), $id_matches[1], $nonce_matches[1], $version_matches[1], $customHeaders, $signature_matches[1]); }
/** * {@inheritdoc} */ public function sendRequest(RequestInterface $request) { $cakeRequest = new Request(); $cakeRequest->method($request->getMethod()); $cakeRequest->url((string) $request->getUri()); $cakeRequest->version($request->getProtocolVersion()); $cakeRequest->body($request->getBody()->getContents()); foreach ($request->getHeaders() as $header => $values) { $cakeRequest->header($header, $request->getHeaderLine($header)); } if (null === $cakeRequest->header('Content-Type')) { $cakeRequest->header('Content-Type', 'application/x-www-form-urlencoded'); } try { $cakeResponse = $this->client->send($cakeRequest, $this->client->config()); } catch (Exception $exception) { throw new NetworkException('Failed to send request', $request, $exception); } return $this->responseFactory->createResponse($cakeResponse->statusCode(), null, $cakeResponse->headers(), $cakeResponse->body(), $cakeResponse->version()); }
/** * Return remote socket from the request. * * @param RequestInterface $request * * @throws InvalidRequestException When no remote can be determined from the request * * @return string */ 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() ?: ($request->getUri()->getScheme() === 'https' ? 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'); } return sprintf('tcp://%s', $endpoint); }
private function extractVariables($extractions, ValueBag $values = null, Crawler $crawler = null, RequestInterface $request, ResponseInterface $response) { if (null === $values) { throw new LogicException('Unable to extract variables if no ValueBag is registered.'); } $variables = $this->createVariables($response, $crawler); foreach ($extractions as $name => $extract) { list($expression, $attributes) = $extract; if (!is_array($attributes)) { $attributes = [$attributes]; } try { $data = $this->language->evaluate($expression, $variables + $values->all(true)); if ($data instanceof Crawler) { $value = $data->extract($attributes); if (count($attributes) == 1) { $data = count($data) > 1 ? $value : $value[0]; } else { $data = $value; } } $values->set($name, $data); } catch (ExpressionSyntaxError $e) { $msg = sprintf('Syntax Error in "%s": %s', $expression, $e->getMessage()); $this->logger and $this->logger->critical($msg, ['request' => $request->getHeaderLine('X-Request-Id')]); throw new ExpectationErrorException($msg); } } }
/** * Send a request to the server and return a Response object with the response. * * @param RequestInterface $request The request object to store request params. * * @return ResponseInterface * * @since 2.1 */ protected function doRequest(RequestInterface $request) { // Setup the cURL handle. $ch = curl_init(); // Set the request method. $options[CURLOPT_CUSTOMREQUEST] = $request->getMethod(); // Don't wait for body when $method is HEAD $options[CURLOPT_NOBODY] = $request->getMethod() === 'HEAD'; // Initialize the certificate store $options[CURLOPT_CAINFO] = $this->getOption('certpath', __DIR__ . '/cacert.pem'); // Set HTTP Version switch ($request->getProtocolVersion()) { case '1.0': $options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0; break; case '1.1': $options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1; break; case '2.0': if (defined('CURL_HTTP_VERSION_2_0')) { $options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_2_0; } } // 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 cURL post fields. if (is_scalar($data) || strpos($request->getHeaderLine('Content-Type'), 'multipart/form-data') === 0) { $options[CURLOPT_POSTFIELDS] = $data; } else { $options[CURLOPT_POSTFIELDS] = http_build_query($data); } if (!$request->getHeaderLine('Content-Type')) { $request = $request->withHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8'); } // Add the relevant headers. if (is_scalar($options[CURLOPT_POSTFIELDS])) { $request = $request->withHeader('Content-Length', strlen($options[CURLOPT_POSTFIELDS])); } } // Build the headers string for the request. if ($headers = $request->getHeaders()) { // Add the headers string into the stream context options array. $options[CURLOPT_HTTPHEADER] = HeaderHelper::toHeaderLine($headers); } // If an explicit timeout is given user it. if ($timeout = $this->getOption('timeout')) { $options[CURLOPT_TIMEOUT] = (int) $timeout; $options[CURLOPT_CONNECTTIMEOUT] = (int) $timeout; } // If an explicit user agent is given use it. if ($userAgent = $this->getOption('userAgent')) { $options[CURLOPT_USERAGENT] = $userAgent; } // Set the request URL. $options[CURLOPT_URL] = (string) $request->getRequestTarget(); // We want our headers. :-) $options[CURLOPT_HEADER] = true; // Return it... echoing it would be tacky. $options[CURLOPT_RETURNTRANSFER] = true; // Override the Expect header to prevent cURL from confusing itself in its own stupidity. // Link: http://the-stickman.com/web-development/php-and-curl-disabling-100-continue-header/ $options[CURLOPT_HTTPHEADER][] = 'Expect:'; /* * Follow redirects if server config allows * @deprecated safe_mode is removed in PHP 5.4, check will be dropped when PHP 5.3 support is dropped */ if (!ini_get('safe_mode') && !ini_get('open_basedir')) { $options[CURLOPT_FOLLOWLOCATION] = (bool) isset($this->options['follow_location']) ? $this->options['follow_location'] : true; } // Set any custom transport options if ($this->getOption('options')) { foreach ((array) $this->getOption('options') as $key => $value) { $options[$key] = $value; } } // Set the cURL options. curl_setopt_array($ch, $options); // Execute the request and close the connection. $content = curl_exec($ch); if (!$this->getOption('allow_empty_result', false) && !trim($content)) { $message = curl_error($ch); // Error but nothing from cURL? Create our own $message = $message ?: 'No HTTP response received'; throw new \RuntimeException($message); } // Get the request information. $info = curl_getinfo($ch); // Close the connection. curl_close($ch); return $this->getResponse($content, $info); }
/** * Return remote socket from the request * * @param RequestInterface $request * * @throws NetworkException When no remote can be determined from the request * * @return string */ private function determineRemoteFromRequest(RequestInterface $request) { if ($request->getUri()->getHost() == "" && !$request->hasHeader('Host')) { throw new NetworkException("Cannot find connection endpoint for this request", $request); } $host = $request->getUri()->getHost(); $port = $request->getUri()->getPort() ?: ($request->getUri()->getScheme() == "https" ? 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'); } return sprintf('tcp://%s', $endpoint); }
private function getNotificationEvent(RequestInterface $request) { $notification = json_decode((string) $request->getBody(), true); $event = (new GithubNotificationEvent())->withParams($notification)->withGithubEventName($request->getHeaderLine('X-GitHub-Event'))->withDeliveryId($request->getHeaderLine('X-Github-Delivery'))->withSignature($request->getHeaderLine('X-Hub-Signature')); return $event; }
/** * @param RequestInterface $request */ public function writeRequest(RequestInterface $request) { echo sprintf("URL: %s\n", $request->getUri()); echo sprintf("METHOD: %s\n", $request->getMethod()); if ($request->getHeaders()) { echo 'HEADERS:'; } $indent = false; foreach ($request->getHeaders() as $name => $values) { if ($indent) { echo str_repeat(' ', 9); } echo sprintf(" %s: %s\n", $name, implode(', ', $values)); $indent = true; } if ($body = (string) $request->getBody()) { echo "\nBODY:"; switch ($request->getHeaderLine('Content-Type')) { case 'application/json': echo json_encode(json_decode($body, true), JSON_PRETTY_PRINT); break; default: echo $body; break; } $this->emptyLine(); } }
/** * Generates cURL options * * @param RequestInterface $request * * @throws UnexpectedValueException if unsupported HTTP version requested * * @return array */ private function createCurlOptions(RequestInterface $request) { $options = array_key_exists('curl_options', $this->options) ? $this->options['curl_options'] : []; $options[CURLOPT_HEADER] = true; $options[CURLOPT_RETURNTRANSFER] = true; $options[CURLOPT_HTTP_VERSION] = $this->getProtocolVersion($request->getProtocolVersion()); $options[CURLOPT_URL] = (string) $request->getUri(); $options[CURLOPT_CONNECTTIMEOUT] = $this->options['connection_timeout']; $options[CURLOPT_FOLLOWLOCATION] = $this->options['follow_redirects']; $options[CURLOPT_MAXREDIRS] = $this->options['max_redirects']; $options[CURLOPT_SSL_VERIFYPEER] = $this->options['ssl_verify_peer']; $options[CURLOPT_TIMEOUT] = $this->options['timeout']; if ($this->options['decode_content'] && $request->hasHeader('accept-encoding')) { $options[CURLOPT_ENCODING] = $request->getHeaderLine('accept-encoding'); } if ($this->options['use_cookies'] && $request->hasHeader('cookie')) { $options[CURLOPT_COOKIE] = implode('; ', $request->getHeader('cookie')); } switch ($request->getMethod()) { case 'GET': $options[CURLOPT_HTTPGET] = true; break; case 'HEAD': $options[CURLOPT_NOBODY] = true; break; case 'POST': case 'CONNECT': case 'DELETE': case 'PATCH': case 'PUT': case 'TRACE': $options[CURLOPT_CUSTOMREQUEST] = $request->getMethod(); break; } $headers = array_keys($request->getHeaders()); foreach ($headers as $name) { $values = $request->getHeader($name); foreach ($values as $value) { $options[CURLOPT_HTTPHEADER][] = $name . ': ' . $value; } } if ($request->getUri()->getUserInfo()) { $options[CURLOPT_USERPWD] = $request->getUri()->getUserInfo(); } return $options; }
private function prepareRequest(Step $step, ValueBag $values, RequestInterface $request, $options) { $options['allow_redirects'] = false; if (!$step->getDelay()) { $options['delay'] = 0; } else { try { $options['delay'] = $this->language->evaluate($step->getDelay(), $values->all(true)); } catch (ExpressionSyntaxError $e) { $msg = sprintf('Delay syntax error in "%s": %s', $step->getDelay(), $e->getMessage()); $this->logger and $this->logger->critical($msg, ['request' => $request->getHeaderLine('X-Request-Id')]); throw new InvalidArgumentException($msg); } } unset($options['expectations']); if ($step->getExpectations()) { $options['expectations'] = $step->getExpectations(); } unset($options['extractions']); if ($step->getExtractions()) { $options['extractions'] = $step->getExtractions(); } foreach ($this->extensions as $extension) { $options = $extension->prepareRequest($step, $values, $request, $options); } return $options; }
/** * Decode an HTTP Response. * @static * @throws Google_Service_Exception * @param Psr\Http\Message\RequestInterface $response The http response to be decoded. * @param Psr\Http\Message\ResponseInterface $response * @return mixed|null */ public static function decodeHttpResponse(ResponseInterface $response, RequestInterface $request = null, $expectedClass = null) { $body = (string) $response->getBody(); $code = $response->getStatusCode(); $result = null; // return raw response when "alt" is "media" $isJson = !($request && 'media' == $request->getUri()->getQuery('alt')); // set the result to the body if it's not set to anything else if ($isJson) { $result = json_decode($body, true); if (null === $result && 0 !== json_last_error()) { // in the event of a parse error, return the raw string $result = $body; } } else { $result = $body; } // retry strategy if (intVal($code) >= 400) { $errors = null; // Specific check for APIs which don't return error details, such as Blogger. if (isset($result['error']['errors'])) { $errors = $result['error']['errors']; } throw new Google_Service_Exception($body, $code, null, $errors); } // use "is_null" because "false" is used to explicitly // prevent an expected class from being returned if (is_null($expectedClass) && $request) { $expectedClass = $request->getHeaderLine('X-Php-Expected-Class'); } if (!empty($expectedClass)) { return new $expectedClass($result); } return $response; }
/** * Check whether a request is or not ajax. * * @param RequestInterface $request * * @return bool */ public static function isAjax(RequestInterface $request) { return strtolower($request->getHeaderLine('X-Requested-With')) === 'xmlhttprequest'; }
/** * Tells if the given request expects a json response. * @param Request $request The request to verify * @return bool True if json is expected, false if not */ private function isJsonRequest(Request $request) : bool { if ($this->isJsonMimeType($request->getHeaderLine('Content-Type'))) { return true; } elseif ($this->isJsonMimeType($request->getHeaderLine('Accept'))) { return true; } return false; }