/**
  * @inheritDoc
  */
 public function format(RequestInterface $request, ResponseInterface $response = null, \Exception $error = null, array $customData = [])
 {
     if (in_array($request->getPath(), $this->paths)) {
         $customData = array_merge(['url' => $this->mask((string) $request->getUrl()), 'resource' => $this->mask($request->getResource()), 'request' => $this->mask((string) $request), 'response' => $this->mask((string) $response), 'res_body' => $response ? $this->mask((string) $response) : 'NULL', 'req_body' => $this->mask((string) $request->getBody())], $customData);
     }
     return parent::format($request, $response, $error, $customData);
 }
 protected function getDefaultOptions(RequestInterface $request, RequestMediator $mediator)
 {
     $url = $request->getUrl();
     // Strip fragment from URL. See:
     // https://github.com/guzzle/guzzle/issues/453
     if (($pos = strpos($url, '#')) !== false) {
         $url = substr($url, 0, $pos);
     }
     $config = $request->getConfig();
     $options = array(CURLOPT_URL => $url, CURLOPT_CONNECTTIMEOUT => $config['connect_timeout'] ?: 150, CURLOPT_RETURNTRANSFER => false, CURLOPT_HEADER => false, CURLOPT_WRITEFUNCTION => array($mediator, 'writeResponseBody'), CURLOPT_HEADERFUNCTION => array($mediator, 'receiveResponseHeader'), CURLOPT_READFUNCTION => array($mediator, 'readRequestBody'), CURLOPT_HTTP_VERSION => $request->getProtocolVersion() === '1.0' ? CURL_HTTP_VERSION_1_0 : CURL_HTTP_VERSION_1_1, CURLOPT_SSL_VERIFYPEER => 1, CURLOPT_SSL_VERIFYHOST => 2, '_headers' => $request->getHeaders());
     if (defined('CURLOPT_PROTOCOLS')) {
         // Allow only HTTP and HTTPS protocols
         $options[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS;
     }
     // Add CURLOPT_ENCODING if Accept-Encoding header is provided
     if ($request->hasHeader('Accept-Encoding')) {
         $options[CURLOPT_ENCODING] = $request->getHeader('Accept-Encoding');
         // Let cURL set the Accept-Encoding header. Without this change
         // curl could add a duplicate value.
         $this->removeHeader('Accept-Encoding', $options);
     }
     // cURL sometimes adds a content-type by default. Prevent this.
     if (!$request->hasHeader('Content-Type')) {
         $options[CURLOPT_HTTPHEADER][] = 'Content-Type:';
     }
     return $options;
 }
Example #3
0
 /**
  * Creates a Ring request from a request object.
  *
  * This function does not hook up the "then" and "progress" events that
  * would be required for actually sending a Guzzle request through a
  * RingPHP handler.
  *
  * @param RequestInterface $request Request to convert.
  *
  * @return array Converted Guzzle Ring request.
  */
 public static function createRingRequest(RequestInterface $request)
 {
     $options = $request->getConfig()->toArray();
     $url = $request->getUrl();
     // No need to calculate the query string twice (in URL and query).
     $qs = ($pos = strpos($url, '?')) ? substr($url, $pos + 1) : null;
     return ['scheme' => $request->getScheme(), 'http_method' => $request->getMethod(), 'url' => $url, 'uri' => $request->getPath(), 'headers' => $request->getHeaders(), 'body' => $request->getBody(), 'version' => $request->getProtocolVersion(), 'client' => $options, 'query_string' => $qs, 'future' => isset($options['future']) ? $options['future'] : false];
 }
Example #4
0
 /**
  * Executes a GuzzleHttp\Message\Request and (if applicable) automatically retries
  * when errors occur.
  *
  * @param Google_Client $client
  * @param GuzzleHttp\Message\Request $req
  * @return array decoded result
  * @throws Google_Service_Exception on server side error (ie: not authenticated,
  *  invalid or malformed post body, invalid url)
  */
 public static function execute(ClientInterface $client, RequestInterface $request, $config = array(), $retryMap = null)
 {
     $runner = new Google_Task_Runner($config, sprintf('%s %s', $request->getMethod(), $request->getUrl()), array(get_class(), 'doExecute'), array($client, $request));
     if (!is_null($retryMap)) {
         $runner->setRetryMap($retryMap);
     }
     return $runner->run();
 }
 /**
  * @param string           $message
  * @param RequestInterface $request
  */
 public function __construct($message = null, RequestInterface $request = null)
 {
     $message = $message ?: $this->message;
     if ($request !== null) {
         $message .= "\nRequest URL: " . $request->getUrl();
     }
     parent::__construct($message, $this->code);
 }
 /**
  * Gets the relevant data from the Guzzle clients.
  *
  * @param RequestInterface $request
  * @param ResponseInterface $response
  */
 public function __construct(RequestInterface $request, ResponseInterface $response)
 {
     if ($response instanceof FutureResponse) {
         $this->httpStatusCode = null;
     } else {
         $this->httpStatusCode = $response->getStatusCode();
     }
     $this->requestUrl = $request->getUrl();
 }
 /**
  * @param RequestInterface $request
  * @return array ['query' => ..., 'request' => ...]
  */
 protected function getRequestAndQuery(RequestInterface $request)
 {
     $query = [];
     foreach ($request->getQuery() as $param => $val) {
         $query[$param] = $val;
     }
     $requestInfo = ['url' => $request->getUrl(), 'path' => $request->getPath(), 'queryString' => (string) $request->getQuery(), 'method' => $request->getMethod(), 'hostname' => $request->getHost(), 'port' => $request->getPort(), 'resource' => $request->getResource()];
     return ['query' => $query, 'request' => $requestInfo];
 }
 /**
  * @param RequestInterface $request
  * @param ResponseInterface $response
  * @return string
  */
 protected function buildMessage($request, $response)
 {
     $resource = $this->getResponseBody();
     if (is_null($resource)) {
         $resource = '';
     }
     $message = sprintf('[url] %s [http method] %s [status code] %s [reason phrase] %s: %s', $request->getUrl(), $request->getMethod(), $response->getStatusCode(), $response->getReasonPhrase(), $resource);
     return $message;
 }
 /**
  * @param string            $message
  * @param RequestInterface  $request
  * @param ResponseInterface $response
  */
 public function __construct($message = null, RequestInterface $request = null, ResponseInterface $response = null)
 {
     $message = $message ?: $this->message;
     if ($request !== null && $response !== null) {
         $details = "[url] " . $request->getUrl();
         $details .= " [status code] " . $response->getStatusCode();
         $details .= " [reason phrase] " . $response->getReasonPhrase();
         $details .= ApiResponseException::getErrorDetails($response);
         $message .= "\nDetails:\n  " . wordwrap($details);
     }
     parent::__construct($message, $this->code);
 }
Example #10
0
 /**
  * Factory method to create a new exception with a normalized error message
  *
  * @param RequestInterface  $request  Request
  * @param ResponseInterface $response Response received
  * @param \Exception        $previous Previous exception
  *
  * @return self
  */
 public static function create(RequestInterface $request, ResponseInterface $response = null, \Exception $previous = null)
 {
     if (!$response) {
         return new self('Error completing request', $request, null, $previous);
     }
     $level = floor($response->getStatusCode() / 100);
     if ($level == '4') {
         $label = 'Client error response';
         $className = __NAMESPACE__ . '\\ClientException';
     } elseif ($level == '5') {
         $label = 'Server error response';
         $className = __NAMESPACE__ . '\\ServerException';
     } else {
         $label = 'Unsuccessful response';
         $className = __CLASS__;
     }
     $message = $label . ' [url] ' . $request->getUrl() . ' [status code] ' . $response->getStatusCode() . ' [reason phrase] ' . $response->getReasonPhrase();
     return new $className($message, $request, $response, $previous);
 }
 protected function getDefaultOptions(RequestInterface $request, RequestMediator $mediator)
 {
     $url = $request->getUrl();
     // Strip fragment from URL. See:
     // https://github.com/guzzle/guzzle/issues/453
     if (($pos = strpos($url, '#')) !== false) {
         $url = substr($url, 0, $pos);
     }
     $config = $request->getConfig();
     $options = [CURLOPT_URL => $url, CURLOPT_CONNECTTIMEOUT => $config['connect_timeout'] ?: 150, CURLOPT_RETURNTRANSFER => false, CURLOPT_HEADER => false, CURLOPT_WRITEFUNCTION => [$mediator, 'writeResponseBody'], CURLOPT_HEADERFUNCTION => [$mediator, 'receiveResponseHeader'], CURLOPT_READFUNCTION => [$mediator, 'readRequestBody'], CURLOPT_HTTP_VERSION => $request->getProtocolVersion() === '1.0' ? CURL_HTTP_VERSION_1_0 : CURL_HTTP_VERSION_1_1, CURLOPT_SSL_VERIFYPEER => 1, CURLOPT_SSL_VERIFYHOST => 2, '_headers' => $request->getHeaders()];
     if (defined('CURLOPT_PROTOCOLS')) {
         // Allow only HTTP and HTTPS protocols
         $options[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS;
     }
     // cURL sometimes adds a content-type by default. Prevent this.
     if (!$request->hasHeader('Content-Type')) {
         $options[CURLOPT_HTTPHEADER][] = 'Content-Type:';
     }
     return $options;
 }
Example #12
0
 public function send(RequestInterface $request)
 {
     $this->logger->info(sprintf('%s "%s"', $request->getMethod(), $request->getUrl()));
     $this->logger->debug(sprintf("Request:\n%s", (string) $request));
     try {
         $response = $this->client->send($request);
     } catch (TransferException $e) {
         $message = sprintf('Something went wrong when calling vault (%s).', $e->getMessage());
         $this->logger->error($message);
         throw new ServerException($message);
     }
     $this->logger->debug(sprintf("Response:\n%s", $response));
     if (400 <= $response->getStatusCode()) {
         $message = sprintf('Something went wrong when calling vault (%s - %s).', $response->getStatusCode(), $response->getReasonPhrase());
         $this->logger->error($message);
         $message .= "\n{$response}";
         if (500 <= $response->getStatusCode()) {
             throw new ServerException($message, $response->getStatusCode(), $response);
         }
         throw new ClientException($message, $response->getStatusCode(), $response);
     }
     return $response;
 }
 /**
  * Hash a request URL into a string that returns cache metadata
  *
  * @param RequestInterface $request
  *
  * @return string
  */
 private function getCacheKey(RequestInterface $request)
 {
     return $this->keyPrefix . md5($request->getMethod() . ' ' . $request->getUrl());
 }
 /**
  * Build a string for displaying in the time-line containing useful info on the request.
  *
  * @param RequestInterface  $request
  * @param ResponseInterface $response
  *
  * @return string
  */
 private function createTimelineMessage(RequestInterface $request, ResponseInterface $response = null)
 {
     $code = $response ? $response->getStatusCode() : 'NULL';
     return sprintf('%s %s (%s)', $request->getMethod(), $request->getUrl(), $code);
 }
Example #15
0
 /**
  * Set the appropriate URL on the request based on the location header
  *
  * @param RequestInterface  $request
  * @param ResponseInterface $response
  * @param array             $protocols
  */
 private function setRedirectUrl(RequestInterface $request, ResponseInterface $response, array $protocols)
 {
     $location = $response->getHeader('Location');
     $location = Url::fromString($location);
     // Combine location with the original URL if it is not absolute.
     if (!$location->isAbsolute()) {
         $originalUrl = Url::fromString($request->getUrl());
         // Remove query string parameters and just take what is present on
         // the redirect Location header
         $originalUrl->getQuery()->clear();
         $location = $originalUrl->combine($location);
     }
     // Ensure that the redirect URL is allowed based on the protocols.
     if (!in_array($location->getScheme(), $protocols)) {
         throw new BadResponseException(sprintf('Redirect URL, %s, does not use one of the allowed redirect protocols: %s', $location, implode(', ', $protocols)), $request, $response);
     }
     $request->setUrl($location);
 }
 /**
  * Looks for a Certificate Authority file in the CA folder
  * that matches the host and update the 'verify' option
  * to its full path.
  * If no specific file regarding a host is found, uses
  * curl-ca-bundle.crt by default.
  * @param RequestInterface $httpRequest
  */
 private function verify(RequestInterface $httpRequest)
 {
     $extensions = array('crt', 'pem', 'cer', 'der');
     $caDir = __DIR__ . '/../CA/';
     // Must be https
     $url = $httpRequest->getUrl();
     if (substr($url, 0, 5) != 'https') {
         $httpRequest->getConfig()->set('verify', false);
         return;
     }
     // Default
     $httpRequest->getConfig()->set('verify', $caDir . 'curl-ca-bundle.crt');
     // Look for a host specific CA file
     $host = strtolower(parse_url($url, PHP_URL_HOST));
     if (!$host) {
         return;
     }
     $filename = $host;
     do {
         // Look for the possible extensions
         foreach ($extensions as $ext) {
             if (file_exists($verify = $caDir . $filename . '.' . $ext)) {
                 $httpRequest->getConfig()->set('verify', $verify);
                 return;
             }
         }
         // Remove a subdomain each time
         $filename = substr($filename, strpos($filename, '.') + 1);
     } while (substr_count($filename, '.') > 0);
     // No specific match
     return;
 }
Example #17
0
 private function createCanonicalizedResource(RequestInterface $request)
 {
     $data = $this->parser->parse($request->getUrl());
     $buffer = '/';
     if ($data['bucket']) {
         $buffer .= $data['bucket'];
         if (!empty($data['key']) || !$data['path_style']) {
             $buffer .= '/' . $data['key'];
         }
     }
     // Add sub resource parameters
     $query = $request->getQuery();
     $first = true;
     foreach ($this->signableQueryString as $key) {
         if ($query->hasKey($key)) {
             $value = $query[$key];
             $buffer .= $first ? '?' : '&';
             $first = false;
             $buffer .= $key;
             // Don't add values for empty sub-resources
             if (strlen($value)) {
                 $buffer .= "={$value}";
             }
         }
     }
     return $buffer;
 }
Example #18
0
 /**
  * Generate a nonce
  *
  * @param RequestInterface $request
  *
  * @return string
  */
 public static function nonce(RequestInterface $request = null)
 {
     $url = $request ? $request->getUrl() : null;
     return sha1(uniqid('', true) . $url);
 }
 private function createStreamResource(RequestInterface $request, array $options, $context, &$http_response_header)
 {
     $url = $request->getUrl();
     return $this->createResource(function () use($url, &$http_response_header, $context) {
         if (false === strpos($url, 'http')) {
             trigger_error("URL is invalid: {$url}", E_USER_WARNING);
             return null;
         }
         return fopen($url, 'r', null, $context);
     }, $request, $options);
 }
Example #20
0
 private function getRequestHeaderAsString(RequestInterface $request)
 {
     $message = vsprintf('%s %s HTTP/%s', [strtoupper($request->getMethod()), $request->getUrl(), $request->getProtocolVersion()]) . "\r\n";
     foreach ($request->getHeaders() as $name => $values) {
         $message .= $name . ': ' . implode(', ', $values) . "\r\n";
     }
     $message .= "\r\n";
     return $message;
 }
 private function assertThatRequestIsEqual(RequestInterface $expectedRequest, RequestInterface $request)
 {
     $this->assertEquals($expectedRequest->getMethod(), $request->getMethod());
     $this->assertEquals($expectedRequest->getUrl(), $request->getUrl());
 }
 /**
  * @param \GuzzleHttp\Message\RequestInterface $request
  * @return \SlevomatZboziApi\Request\ZboziApiRequest
  */
 private function getZboziApiRequest(\GuzzleHttp\Message\RequestInterface $request)
 {
     return new ZboziApiRequest($request->getMethod(), $request->getUrl(), $request->getHeaders(), $request->getBody() === null ? null : json_decode((string) $request->getBody()));
 }
 /**
  * Creates the Signature Base String.
  *
  * The Signature Base String is a consistent reproducible concatenation of
  * the request elements into a single string. The string is used as an
  * input in hashing or signing algorithms.
  *
  * @param RequestInterface $request Request being signed
  * @param array            $params  HTTP Request parameters
  *
  * @return string Returns the base string
  */
 protected function createBaseString(RequestInterface $request, $params = [])
 {
     // Remove query params from URL.
     $url = preg_replace('/https:\\/\\/|\\?.*/', '', $request->getUrl());
     if (is_array($params)) {
         $query = http_build_query($params, '', '&', PHP_QUERY_RFC1738);
     } else {
         $query = $params;
     }
     return strtoupper($request->getMethod()) . ' ' . $url . '?' . $query;
 }
Example #24
0
 /**
  * get cache key for a request
  *
  */
 protected function getCacheKey(RequestInterface $request)
 {
     return $this->keyPrefix . '_' . str_replace([':', '/', '?', '&&'], '_', $request->getUrl()) . '_' . md5($request->getMethod() . ' ' . $request->getUrl());
 }
Example #25
0
 /**
  * Set the appropriate URL on the request based on the location header
  *
  * @param RequestInterface  $request
  * @param ResponseInterface $response
  */
 private function setRedirectUrl(RequestInterface $request, ResponseInterface $response)
 {
     $location = $response->getHeader('Location');
     $location = Url::fromString($location);
     // Combine location with the original URL if it is not absolute.
     if (!$location->isAbsolute()) {
         $originalUrl = Url::fromString($request->getUrl());
         // Remove query string parameters and just take what is present on
         // the redirect Location header
         $originalUrl->getQuery()->clear();
         $location = $originalUrl->combine($location);
     }
     $request->setUrl($location);
 }
Example #26
0
 /**
  * Handle an error. We handle errors by throwing an exception.
  *
  * @param string $error An error code representing the error
  *                      (use_underscore_separators).
  * @param string|null $message The error message.
  * @param \GuzzleHttp\Message\RequestInterface|null $request Optional. The
  *                                                  Guzzle request object.
  * @param \GuzzleHttp\Message\ResponseInterface|null $response Optional. The
  *                                                   Guzzle response object.
  *
  * @return void
  * @throws \Box\View\BoxViewException
  */
 protected static function error($error, $message = null, $request = null, $response = null)
 {
     if (!empty($request)) {
         $message .= "\n";
         $message .= 'Method: ' . $request->getMethod() . "\n";
         $message .= 'URL: ' . $request->getUrl() . "\n";
         $message .= 'Query: ' . json_encode($request->getQuery()->toArray()) . "\n";
         $message .= 'Headers: ' . json_encode($request->getHeaders()) . "\n";
         $message .= 'Request Body: ' . $request->getBody() . "\n";
     }
     if (!empty($response)) {
         $message .= "\n";
         $message .= 'Response Body: ' . $response->getBody() . "\n";
     }
     $exception = new BoxViewException($message);
     $exception->errorCode = $error;
     throw $exception;
 }
Example #27
0
 private function createStreamResource(RequestInterface $request, array $options, $context, &$http_response_header)
 {
     $url = $request->getUrl();
     // Add automatic gzip decompression
     if (strpos($request->getHeader('Accept-Encoding'), 'gzip') !== false) {
         $url = 'compress.zlib://' . $url;
     }
     return $this->createResource(function () use($url, &$http_response_header, $context) {
         if (false === strpos($url, 'http')) {
             trigger_error("URL is invalid: {$url}", E_USER_WARNING);
             return null;
         }
         return fopen($url, 'r', null, $context);
     }, $request, $options);
 }
Example #28
0
 /**
  * @param RequestInterface $request
  * @return Url
  */
 protected function extractUrlArgument(RequestInterface $request)
 {
     $url = Url::fromString($request->getUrl());
     $url->setFragment(null);
     if (!$url->getScheme()) {
         $url = Url::fromString('http://' . (string) $url);
     }
     $this->addCommandPart(escapeshellarg((string) $url));
 }
Example #29
0
 /**
  * Creates the Signature Base String.
  *
  * The Signature Base String is a consistent reproducible concatenation of
  * the request elements into a single string. The string is used as an
  * input in hashing or signing algorithms.
  *
  * @param RequestInterface $request Request being signed
  * @param array            $params  Associative array of OAuth parameters
  *
  * @return string Returns the base string
  * @link http://oauth.net/core/1.0/#sig_base_example
  */
 protected function createBaseString(RequestInterface $request, array $params)
 {
     // Remove query params from URL. Ref: Spec: 9.1.2.
     $url = Url::fromString($request->getUrl());
     $url->setQuery('');
     $query = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
     return strtoupper($request->getMethod()) . '&' . rawurlencode($url) . '&' . rawurlencode($query);
 }
Example #30
0
 /**
  * Internal method which prevents infinite recursion. For certain requests, like the initial
  * auth call itself, we do NOT want to send a token.
  *
  * @param RequestInterface $request
  *
  * @return bool
  */
 private function shouldIgnore(RequestInterface $request)
 {
     return strpos((string) $request->getUrl(), 'tokens') !== false && $request->getMethod() == 'POST';
 }