/** * @param RequestInterface|ResponseInterface $message * @return string */ protected function formatBody($message) { $header = $message->getHeader('Content-Type'); if (JsonStringFormatter::isJsonHeader($header)) { $formatter = new JsonStringFormatter(); return $formatter->format($message->getBody()); } elseif (XmlStringFormatter::isXmlHeader($header)) { $formatter = new XmlStringFormatter(); return $formatter->format($message->getBody()); } $factory = new StringFactoryFormatter(); return $factory->format($message->getBody()); }
public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, array $context) { $name = urlencode($param->formName); $value = urlencode($command[$param->getName()]); $content = Stream::factory($param->filter($value)); if ($request->getBody() === null) { $request->setBody(Stream::factory("")); } $queryChar = '&'; if ($request->getBody()->__toString() == '') { $queryChar = ''; } $request->getBody()->write($queryChar . $name . "=" . $content); }
/** * Calculate signature for request * * @param RequestInterface $request Request to generate a signature for * * @return string */ public function getSignature(RequestInterface $request) { // For POST|PUT set the JSON body string as the params if ($request->getMethod() == 'POST' || $request->getMethod() == 'PUT') { $params = $request->getBody()->__toString(); /** * If you don't seek() back to the beginning then attempting to * send a JSON body > 1MB will probably fail. * * @link http://stackoverflow.com/q/32359664/99071 * @link https://groups.google.com/forum/#!topic/guzzle/vkF5druf6AY */ $request->getBody()->seek(0); // Make sure to remove any other query params $request->setQuery([]); } else { $params = Query::fromString($request->getQuery(), Query::RFC1738)->toArray(); $params = $this->prepareParameters($params); // Re-Set the query to the properly ordered query string $request->setQuery($params); $request->getQuery()->setEncodingType(Query::RFC1738); } $baseString = $this->createBaseString($request, $params); return base64_encode($this->sign_HMAC_SHA256($baseString)); }
/** * @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); }
/** * 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]; }
protected function assertRequestHasPostParameter($parameterName, $expectedValue, RequestInterface $request) { /** @var PostBody $requestBody */ $requestBody = $request->getBody(); $this->assertNotEmpty($requestBody); $this->assertInstanceOf(PostBody::class, $requestBody); $actualValue = $requestBody->getField($parameterName); $this->assertNotNull($actualValue, "The request should have the post body parameter '{$parameterName}'"); $this->assertEquals($expectedValue, $actualValue); }
/** * {@inheritdoc} * Replaces the ewayCardNumber field in the body with "X"s. */ public function format(RequestInterface $request, ResponseInterface $response = null, \Exception $error = null, array $customData = array()) { $body = $request->getBody()->__toString(); $newBody = preg_replace_callback('/<ewayCardNumber>(.*?)<\\/ewayCardNumber>/', function ($matches) { $privateNumber = str_repeat('X', strlen($matches[1]) - 4) . substr($matches[1], -4); return '<ewayCardNumber modified>' . $privateNumber . '</ewayCardNumber>'; }, $body); $newRequest = clone $request; $newRequest->setBody(Stream::factory($newBody)); $request->setBody(Stream::factory($body)); return parent::format($newRequest, $response, $error, $customData); }
public function visit(GuzzleCommandInterface $command, RequestInterface $request, Parameter $param, array $context) { $body = $request->getBody(); if (!$body instanceof PostBodyInterface) { throw new \RuntimeException('Must be a POST body interface'); } $value = $param->filter($command[$param->getName()]); if (!$value instanceof PostFileInterface) { $value = new PostFile($param->getWireName(), $value); } $body->addFile($value); }
/** * Sends HTTP request to specific URL with form data from PyString. * * @param string $method request method * @param string $url relative url * @param PyStringNode $body request body * * @When /^(?:I )?send a ([A-Z]+) request to "([^"]+)" with form data:$/ */ public function iSendARequestWithFormData($method, $url, PyStringNode $body) { $url = $this->prepareUrl($url); $body = $this->replacePlaceHolder(trim($body)); $fields = array(); parse_str(implode('&', explode("\n", $body)), $fields); $this->request = $this->getClient()->createRequest($method, $url); /** @var \GuzzleHttp\Post\PostBodyInterface $requestBody */ $requestBody = $this->request->getBody(); foreach ($fields as $key => $value) { $requestBody->setField($key, $value); } $this->sendRequest(); }
public function after(CommandInterface $command, RequestInterface $request, Operation $operation, array $context) { $additional = $operation->getAdditionalParameters(); if ($additional && $additional->getLocation() == $this->locationName) { $body = $request->getBody(); if (!$body instanceof PostBodyInterface) { throw new \RuntimeException('Must be a POST body interface'); } foreach ($command->toArray() as $key => $value) { if (!$operation->hasParam($key)) { $body->setField($key, $this->prepareValue($value, $additional)); } } } }
public function signRequest(RequestInterface $request, CredentialsInterface $credentials) { /** @var PostBodyInterface $body */ $body = $request->getBody(); $body->setField('Timestamp', gmdate('c')); $body->setField('SignatureVersion', '2'); $body->setField('SignatureMethod', 'HmacSHA256'); $body->setField('AWSAccessKeyId', $credentials->getAccessKeyId()); if ($token = $credentials->getSecurityToken()) { $body->setField('SecurityToken', $token); } // build string to sign $sign = $request->getMethod() . "\n" . $request->getHost() . "\n" . '/' . "\n" . $this->getCanonicalizedParameterString($body); $request->getConfig()->set('aws.signature', $sign); $body->setField('Signature', base64_encode(hash_hmac('sha256', $sign, $credentials->getSecretKey(), true))); }
/** * Calculate signature for request * * @param RequestInterface $request Request to generate a signature for * * @return string * * @throws \RuntimeException */ public function getSignature(RequestInterface $request) { // For POST|PUT set the JSON body string as the params if ($request->getMethod() == 'POST' || $request->getMethod() == 'PUT') { $params = $request->getBody()->__toString(); // Make sure to remove any other query params $request->setQuery([]); } else { $params = Query::fromString($request->getQuery(), Query::RFC1738)->toArray(); $params = $this->prepareParameters($params); // Re-Set the query to the properly ordered query string $request->setQuery($params); $request->getQuery()->setEncodingType(Query::RFC1738); } $baseString = $this->createBaseString($request, $params); return base64_encode($this->sign_HMAC_SHA256($baseString)); }
/** * Calculate signature for request * * This method mostly copy pasted from original class, except its bottom part where we actually hashing our request * * @param RequestInterface $request Request to generate a signature for * @param array $params Oauth parameters. * * @return string */ public function getSignature(RequestInterface $request, array $params) { // Remove oauth_signature if present // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.") unset($params['oauth_signature']); // Add POST fields if the request uses POST fields and no files $body = $request->getBody(); if ($body instanceof PostBodyInterface && !$body->getFiles()) { $query = Query::fromString($body->getFields(true)); $params += $query->toArray(); } // Parse & add query string parameters as base string parameters $query = Query::fromString((string) $request->getQuery()); $query->setEncodingType(Query::RFC1738); $params += $query->toArray(); $baseString = $this->createBaseString($request, $this->prepareParameters($params)); // changed code return base64_encode(hash_hmac('sha1', $baseString, $this->consumer_secret, true)); }
/** * @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())); }
private function modifyRedirectRequest(RequestInterface $request, ResponseInterface $response) { $config = $request->getConfig(); // Use a GET request if this is an entity enclosing request and we are // not forcing RFC compliance, but rather emulating what all browsers // would do. $statusCode = $response->getStatusCode(); if ($statusCode == 303 || $statusCode <= 302 && $request->getBody() && !$config->getPath('redirect/strict')) { $request->setMethod('GET'); $request->setBody(null); } $previousUrl = $request->getUrl(); $this->setRedirectUrl($request, $response); $this->rewindEntityBody($request); // Add the Referer header if it is told to do so and only // add the header if we are not redirecting from https to http. if ($config->getPath('redirect/referer') && ($request->getScheme() == 'https' || $request->getScheme() == $config['redirect_scheme'])) { $url = Url::fromString($previousUrl); $url->setUsername(null); $url->setPassword(null); $request->setHeader('Referer', (string) $url); } else { $request->removeHeader('Referer'); } }
/** * @param RequestInterface $request */ protected function extractBodyArgument(RequestInterface $request) { if ($request->getBody() && ($contents = (string) $request->getBody())) { $this->addOption('d', escapeshellarg($contents)); } //if get request has data Add G otherwise curl will make a post request if (!empty($this->options['d']) && 'GET' === $request->getMethod()) { $this->addOption('G'); } }
private function getDefaultOptions(RequestInterface $request) { $headers = ''; foreach ($request->getHeaders() as $name => $values) { $headers .= $name . ': ' . implode(', ', $values) . "\r\n"; } return ['http' => ['method' => $request->getMethod(), 'header' => trim($headers), 'protocol_version' => $request->getProtocolVersion(), 'ignore_errors' => true, 'follow_location' => 0, 'content' => (string) $request->getBody()]]; }
/** * Calculate signature for request * * @param RequestInterface $request Request to generate a signature for * @param array $params Oauth parameters. * * @return string * * @throws \RuntimeException */ public function getSignature(RequestInterface $request, array $params) { // Remove oauth_signature if present // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.") unset($params['oauth_signature']); // Add POST fields if the request uses POST fields and no files $body = $request->getBody(); if ($body instanceof PostBodyInterface && !$body->getFiles()) { $query = Query::fromString($body->getFields(true)); $params += $query->toArray(); } // Parse & add query string parameters as base string parameters $query = Query::fromString((string) $request->getQuery()); $query->setEncodingType(Query::RFC1738); $params += $query->toArray(); $baseString = $this->createBaseString($request, $this->prepareParameters($params)); // Implements double-dispatch to sign requests switch ($this->config['signature_method']) { case Oauth1::SIGNATURE_METHOD_HMAC: $signature = $this->signUsingHmacSha1($baseString); break; case Oauth1::SIGNATURE_METHOD_RSA: $signature = $this->signUsingRsaSha1($baseString); break; case Oauth1::SIGNATURE_METHOD_PLAINTEXT: $signature = $this->signUsingPlaintext($baseString); break; default: throw new \RuntimeException('Unknown signature method: ' . $this->config['signature_method']); break; } return base64_encode($signature); }
/** * 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; }
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 (string) $request->getHeader('x-amz-content-sha256'); } if ($body = $request->getBody()) { if (!$body->isSeekable()) { throw new CouldNotCreateChecksumException('sha256'); } return Utils::hash($body, 'sha256'); } return self::EMPTY_PAYLOAD; }
/** * Calculate signature for request * * @param RequestInterface $request Request to generate a signature for * @param array $params Oauth parameters. * * @return string * * @throws \RuntimeException */ public function getSignature(RequestInterface $request, array $params) { // Remove oauth_signature if present // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.") unset($params['oauth_signature']); // Add POST fields if the request uses POST fields and no files $body = $request->getBody(); if ($body instanceof PostBodyInterface && !$body->getFiles()) { $query = Query::fromString($body->getFields(true)); $params += $query->toArray(); } // Parse & add query string parameters as base string parameters $query = Query::fromString((string) $request->getQuery()); $query->setEncodingType(Query::RFC1738); $params += $query->toArray(); $baseString = $this->createBaseString($request, $this->prepareParameters($params)); // Implements double-dispatch to sign requests $meth = [$this, 'sign_' . str_replace('-', '_', $this->config['signature_method'])]; if (!is_callable($meth)) { throw new \RuntimeException('Unknown signature method: ' . $this->config['signature_method']); } return base64_encode(call_user_func($meth, $baseString, $this->config)); }
public function sign(RequestInterface $request, $client_id, $client_secret) { $body = $request->getBody(); $body->setField($this->client_id_field, $client_id); $body->setField($this->client_secret_field, $client_secret); }
private function applyBody(RequestInterface $request, array &$options) { if ($request->hasHeader('Content-Length')) { $size = (int) $request->getHeader('Content-Length'); } else { $size = null; } $request->getBody()->seek(0); // You can send the body as a string using curl's CURLOPT_POSTFIELDS if ($size !== null && $size < 32768 || isset($request->getConfig()['curl']['body_as_string'])) { $options[CURLOPT_POSTFIELDS] = $request->getBody()->getContents(); // Don't duplicate the Content-Length header $this->removeHeader('Content-Length', $options); $this->removeHeader('Transfer-Encoding', $options); } else { $options[CURLOPT_UPLOAD] = true; // Let cURL handle setting the Content-Length header if ($size !== null) { $options[CURLOPT_INFILESIZE] = $size; $this->removeHeader('Content-Length', $options); } } // If the Expect header is not present, prevent curl from adding it if (!$request->hasHeader('Expect')) { $options[CURLOPT_HTTPHEADER][] = 'Expect:'; } }
/** * Create a redirect request for a specific request object * * Takes into account strict RFC compliant redirection (e.g. redirect POST * with POST) vs doing what most clients do (e.g. redirect POST with GET). * * @param RequestInterface $request * @param ResponseInterface $response * * @return RequestInterface Returns a new redirect request * @throws CouldNotRewindStreamException If the body cannot be rewound. */ private function createRedirectRequest(RequestInterface $request, ResponseInterface $response) { $config = $request->getConfig(); // Use a GET request if this is an entity enclosing request and we are // not forcing RFC compliance, but rather emulating what all browsers // would do. Be sure to disable redirects on the clone. $redirectRequest = clone $request; $redirectRequest->getEmitter()->detach($this); $statusCode = $response->getStatusCode(); if ($statusCode == 303 || $statusCode <= 302 && $request->getBody() && !$config->getPath('redirect/strict')) { $redirectRequest->setMethod('GET'); $redirectRequest->setBody(null); } $this->setRedirectUrl($redirectRequest, $response); $this->rewindEntityBody($redirectRequest); // Add the Referer header if it is told to do so and only // add the header if we are not redirecting from https to http. if ($config->getPath('redirect/referer') && ($redirectRequest->getScheme() == 'https' || $redirectRequest->getScheme() == $request->getScheme())) { $url = Url::fromString($request->getUrl()); $url->setUsername(null)->setPassword(null); $redirectRequest->setHeader('Referer', (string) $url); } return $redirectRequest; }
protected function addPostFiles(RequestInterface $request, array $files, $arrayName = '') { foreach ($files as $name => $info) { if (!empty($arrayName)) { $name = $arrayName . '[' . $name . ']'; } if (is_array($info)) { if (isset($info['tmp_name'])) { if ('' !== $info['tmp_name']) { $request->getBody()->addFile(new PostFile($name, fopen($info['tmp_name'], 'r'), isset($info['name']) ? $info['name'] : null)); } else { continue; } } else { $this->addPostFiles($request, $info, $name); } } else { $request->getBody()->addFile(new PostFile($name, fopen($info, 'r'))); } } }
/** * Collect & sanitize data about a Guzzle request. * * @param RequestInterface $request Guzzle request. * @return array */ private function collectRequest(RequestInterface $request) { $query = $request->getQuery(); return ['headers' => $request->getHeaders(), 'method' => $request->getMethod(), 'scheme' => $request->getScheme(), 'host' => $request->getHost(), 'path' => $request->getPath(), 'query' => (string) $query, 'queryParams' => $query->toArray(), 'body' => (string) $request->getBody()]; }