/** * {@inheritdoc} */ public function getNextRequest(ClientInterface $client, JobConfig $jobConfig, $response, $data) { $nextUrl = Utils::getDataFromPath($this->urlParam, $response, '.'); if (empty($nextUrl)) { return false; } // start_time validation // https://developer.zendesk.com/rest_api/docs/core/incremental_export#incremental-ticket-export $now = new \DateTime(); $startDateTime = \DateTime::createFromFormat('U', Url::fromString($nextUrl)->getQuery()->get('start_time')); if ($startDateTime && $startDateTime > $now->modify(sprintf("-%d minutes", self::NEXT_PAGE_FILTER_MINUTES))) { return false; } $config = $jobConfig->getConfig(); if (!$this->includeParams) { $config['params'] = []; } if (!$this->paramIsQuery) { $config['endpoint'] = $nextUrl; } else { // Create an array from the query string $responseQuery = Query::fromString(ltrim($nextUrl, '?'))->toArray(); $config['params'] = array_replace($config['params'], $responseQuery); } return $client->createRequest($config); }
/** * {@inheritdoc} */ public function getNextRequest(ClientInterface $client, JobConfig $jobConfig, $response, $data) { $nextUrl = Utils::getDataFromPath($this->urlParam, $response, '.'); if (empty($nextUrl)) { return false; } // since validation - cannot be greater than now $now = new \DateTime(); $sinceDateTime = \DateTime::createFromFormat('U', Url::fromString($nextUrl)->getQuery()->get('since')); if ($sinceDateTime && $sinceDateTime > $now) { return false; } $config = $jobConfig->getConfig(); if (!$this->includeParams) { $config['params'] = []; } if (!$this->paramIsQuery) { $config['endpoint'] = $nextUrl; } else { // Create an array from the query string $responseQuery = Query::fromString(ltrim($nextUrl, '?'))->toArray(); $config['params'] = array_replace($config['params'], $responseQuery); } return $client->createRequest($config); }
/** * 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)); }
/** * {@inheritdoc} */ public function getNextRequest(ClientInterface $client, JobConfig $jobConfig, $response, $data) { $nextUrl = Utils::getDataFromPath($this->urlParam, $response, '.'); if (empty($nextUrl)) { return false; } else { $config = $jobConfig->getConfig(); if (!$this->includeParams) { $config['params'] = []; } if (!$this->paramIsQuery) { $config['endpoint'] = $nextUrl; } else { // Create an array from the query string $responseQuery = Query::fromString(ltrim($nextUrl, '?'))->toArray(); $config['params'] = array_replace($config['params'], $responseQuery); } return $client->createRequest($config); } }
/** * Set the query part of the URL. * * You may provide a query string as a string and pass $rawString as true * to provide a query string that is not parsed until a call to getQuery() * is made. Setting a raw query string will still encode invalid characters * in a query string. * * @param Query|string|array $query Query string value to set. Can * be a string that will be parsed into a Query object, an array * of key value pairs, or a Query object. * @param bool $rawString Set to true when providing a raw query string. * * @throws \InvalidArgumentException */ public function setQuery($query, $rawString = false) { if ($query instanceof Query) { $this->query = $query; } elseif (is_string($query)) { if (!$rawString) { $this->query = Query::fromString($query); } else { // Ensure the query does not have illegal characters. $this->query = preg_replace_callback(self::$queryPattern, array(__CLASS__, 'encodeMatch'), $query); } } elseif (is_array($query)) { $this->query = new Query($query); } else { throw new \InvalidArgumentException('Query must be a Query, ' . 'array, or string. Got ' . Core::describeType($query)); } }
/** * 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); }
public function testCastingToAndCreatingFromStringWithEmptyValuesIsFast() { $this->assertEquals('', (string) Query::fromString('')); }
/** * generic request executor * * @param string $method GET, POST, PUT, DELETE * @param string $endpointUrl * @param array $queryString * @param array|string $body * @param string $auth http-signatures to enable http-signature signing * @param string $contentMD5Mode body or url * @param float $timeout timeout in seconds * @return RequestInterface */ public function buildRequest($method, $endpointUrl, $queryString = null, $body = null, $auth = null, $contentMD5Mode = null, $timeout = null) { if (is_null($contentMD5Mode)) { $contentMD5Mode = !is_null($body) ? 'body' : 'url'; } $request = $this->guzzle->createRequest($method, $endpointUrl); if ($queryString) { $request->getQuery()->replace($queryString); } if (!$request->getQuery()->get('api_key')) { $request->getQuery()->set('api_key', $this->apiKey); } // normalize the query string the same way the server expects it $request->setQuery(Query::fromString(Request::normalizeQueryString((string) $request->getQuery()))); if (!$request->hasHeader('Date')) { $request->setHeader('Date', $this->getRFC1123DateString()); } if (!is_null($body)) { if (!$request->hasHeader('Content-Type')) { $request->setHeader('Content-Type', 'application/json'); } if (!is_string($body)) { $body = json_encode($body); } $request->setBody(Stream::factory($body)); } // for GET/DELETE requests, MD5 the request URI (excludes domain, includes query strings) if ($contentMD5Mode == 'body') { $request->setHeader('Content-MD5', md5((string) $body)); } else { $qs = (string) $request->getQuery(); $request->setHeader('Content-MD5', md5($request->getPath() . ($qs ? "?{$qs}" : ""))); } if ($auth !== null) { $request->getConfig()['auth'] = $auth; } if ($timeout !== null) { $request->getConfig()['timeout'] = $timeout; } return $request; }
/** * Creates a multipart/form-data body stream * * @return MultipartBody */ private function createMultipart() { // Flatten the nested query string values using the correct aggregator $query = (string) (new Query($this->fields))->setEncodingType(false)->setAggregator($this->getAggregator()); // Convert the flattened query string back into an array $fields = Query::fromString($query)->toArray(); return new MultipartBody($fields, $this->files); }
public function testConvertsPlusSymbolsToSpacesByDefault() { $query = Query::fromString('var=foo+bar', true); $this->assertEquals('foo bar', $query->get('var')); }
/** * Initializes an AccessToken by making a request to the token endpoint * * @param array $params An array of params for the token endpoint * @param array $access Token options, to pass to the AccessToken object * @return \OAuth2\AccessToken */ public function getToken($params = array(), $tokenOpts = array()) { // Get parse mode for the response $parseMode = isset($params['parse']) ? $params['parse'] : 'automatic'; unset($params['parse']); if ($this->options['token_method'] === 'POST') { $opts['headers'] = array('Content-Type' => 'x-www-form-urlencoded'); $opts['body'] = $params; } else { $opts['query'] = $params; } // Create request $request = $this->createRequest($this->options['token_method'], $this->tokenUrl(), $opts); // Set auth if (isset($this->options['client_auth'])) { if ($this->options['client_auth'] === 'header') { $request->setHeader('Authorization', 'Basic ' . base64_encode("{$this->id}:{$this->secret}")); } else { if ($this->options['client_auth'] === 'query') { $request->getQuery()->merge(['client_id' => $this->id, 'client_secret' => $this->secret]); } else { if ($this->options['client_auth'] === 'body') { // Retrieve current body as a \Guzzle\Query object since we'll have to add client auth $body = \GuzzleHttp\Query::fromString((string) $request->getBody()); // Add client auth $body->merge(['client_id' => $this->id, 'client_secret' => $this->secret]); // Replace body $request->setBody(\GuzzleHttp\Stream\Stream::factory((string) $body)); } else { throw new \Exception("Unknown client authentication method."); } } } } else { throw new \Exception("Missing client authentication method."); } // Get response $response = $this->getResponse($request, $parseMode); // Handle response $parsedResponse = $response->parse(); if (!is_array($parsedResponse) && !isset($parsedResponse['access_token'])) { throw new \OAuth2\Error($response); } // Return access token return \OAuth2\AccessToken::fromHash($this, array_merge($parsedResponse, $tokenOpts)); }
/** * Set the query part of the URL * * @param Query|string|array $query Query string value to set. Can * be a string that will be parsed into a Query object, an array * of key value pairs, or a Query object. * * @throws \InvalidArgumentException */ public function setQuery($query) { if ($query instanceof Query) { $this->query = $query; } elseif (is_string($query)) { $this->query = Query::fromString($query); } elseif (is_array($query)) { $this->query = new Query($query); } else { throw new \InvalidArgumentException('Query must be a Query, ' . 'array, or string. Got ' . Core::describeType($query)); } }
public function testQueryStringsAllowDecodingEncodingCompletelyDisabled() { $q = Query::fromString('foo=bar%2Fbaz&bam=boo boo!', false); $this->assertEquals('foo=bar%2Fbaz&bam=boo boo!', (string) $q); }
private function createQueryString() { $q_string = ''; $q_string .= isset($this->process_date_start) ? '&process_date_start=' . str_replace(' ', '%20', $this->process_date_start) : ''; $q_string .= isset($this->process_date_end) ? '&process_date_end=' . str_replace(' ', '%20', $this->process_date_end) : ''; $q_string .= isset($this->transaction_date_start) ? '&transaction_date_start=' . str_replace(' ', '%20', $this->transaction_date_start) : ''; $q_string .= isset($this->transaction_date_end) ? '&transaction_date_end=' . str_replace(' ', '%20', $this->transaction_date_end) : ''; $q_string .= isset($this->limit) ? '&limit=' . $this->limit : ''; $q_string .= isset($this->page) ? '&page=' . $this->page : ''; return Query::fromString($q_string, false); }
public function testQueryIsNormalizedAndProperlyEncodedFromString() { $q = Query::fromString('foo=bar%2Fbaz&bam=boo boo!?'); $this->assertEquals('foo=bar/baz&bam=boo%20boo!?', (string) $q); }
public function testCanChangeUrlEncodingDecodingToRfc3986() { $q = Query::fromString('foo=bar%20baz', Query::RFC3986); $this->assertEquals('bar baz', $q['foo']); $this->assertEquals('foo=bar%20baz', (string) $q); }
/** * 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 * * @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)); }
/** * 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)); }