/** * Authenticate with the server and retrieve an auth token. * * Currently implements Citrix's {@link https://developer.citrixonline.com/page/direct-login "Direct Login"} method. * * @param string $userId * @param string $password * @return \kenobi883\GoToMeeting\Models\Auth */ public function authenticate($userId, $password) { $url = "{$this->endpoint}/access_token"; $query = new Query(); $query->add('grant_type', 'password')->add('user_id', $userId)->add('password', $password)->add('client_id', $this->client->getApiKey()); $jsonBody = $this->client->sendRequest('GET', $url, $query, true); return new Auth($jsonBody); }
/** * @param array $userValues The user-defined values that will populate the JSON * @param []Parameter $params The parameter schemas that define how each value is populated. * For example, specifying any deep nesting or aliasing. * @param string $inputString The initial URL string being decorated. * * @return Url */ public function serialize($userValues, array $params, $inputString) { $url = Url::fromString($inputString); $query = new Query(); foreach ($userValues as $paramName => $value) { $schema = $params[$paramName]; if (!$schema->hasLocation('query')) { continue; } $query->set($schema->getName(), $value); } $url->setQuery($query); return $url; }
/** * {@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); }
/** * Constructor. * * @param \Cartalyst\Stripe\ConfigInterface $config * @return void */ public function __construct(ConfigInterface $config) { parent::__construct(['base_url' => $config->base_url]); // Set the Config repository instance $this->config = $config; // Prepare the request headers $this->prepareRequestHeaders(); // Register some before events $this->getEmitter()->on('before', function (BeforeEvent $event) { // Get the event request $request = $event->getRequest(); // Set the Stripe API key $request->setHeader('Authorization', "Basic " . base64_encode($this->config->api_key)); // Set the query aggregator $request->getQuery()->setAggregator(Query::phpAggregator(false)); }); }
/** * 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); } }
public function testCanSpecifyQueryAggregator() { $b = new PostBody(); $b->setField('foo', ['baz', 'bar']); $this->assertEquals('foo%5B0%5D=baz&foo%5B1%5D=bar', (string) $b); $b = new PostBody(); $b->setField('foo', ['baz', 'bar']); $agg = Query::duplicateAggregator(); $b->setAggregator($agg); $this->assertEquals('foo=baz&foo=bar', (string) $b); }
public function testCanUseUrlWithCustomQuery() { $client = new Client(); $url = Url::fromString('http://foo.com/bar'); $query = new Query(['baz' => '123%20']); $query->setEncodingType(false); $url->setQuery($query); $r = $client->createRequest('GET', $url); $this->assertEquals('http://foo.com/bar?baz=123%20', $r->getUrl()); }
/** * @param string $name * @param mixed $value * * @return $this */ public function setQueryField($name, $value) { $this->query->set($name, $value); return $this; }
/** * Get attendees for the specified meeting instance key and date range. * * Instance keys may only be obtained for historical meetings. * * @param string $meetingInstanceKey * @param \DateTime $startDate * @param \DateTime $endDate * @return array includes `meetings` and `attendees` keys mapping to arrays of the Meeting and Attendee * instances returned from the API */ public function getAttendeesByMeeting($meetingInstanceKey, \DateTime $startDate, \DateTime $endDate) { $url = "{$this->endpoint}/{$meetingInstanceKey}/attendees"; $query = new Query(); $query->add('startDate', $startDate->format(MeetingService::DATE_FORMAT_INPUT))->add('endDate', $endDate->format(MeetingService::DATE_FORMAT_INPUT)); $jsonBody = $this->client->sendRequest('GET', $url, $query); $meetings = array(); $attendees = array(); foreach ($jsonBody as $meetingAttendee) { $meetings[] = new Meeting($meetingAttendee); $attendees[] = new Attendee($meetingAttendee); } return array('meetings' => $meetings, 'attendees' => $attendees); }
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); }
/** * 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)); } }
/** * 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); }
/** * 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 testQueryStringsAllowDecodingEncodingCompletelyDisabled() { $q = Query::fromString('foo=bar%2Fbaz&bam=boo boo!', false); $this->assertEquals('foo=bar%2Fbaz&bam=boo boo!', (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 */ 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)); }
/** * 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)); }
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 testQueryIsNormalizedAndProperlyEncodedFromString() { $q = Query::fromString('foo=bar%2Fbaz&bam=boo boo!?'); $this->assertEquals('foo=bar/baz&bam=boo%20boo!?', (string) $q); }
/** * @param Query $query */ private function addParamsToUri(Query $query) { foreach ($this->_properties as $key => $value) { $query->set($key, $value); } }
/** * @ticket https://github.com/guzzle/guzzle/issues/706 */ public function testDoesNotApplyPostBodyRightAway() { $request = (new MessageFactory())->createRequest('POST', 'http://f.cn', ['body' => ['foo' => ['bar', 'baz']]]); $this->assertEquals('', $request->getHeader('Content-Type')); $this->assertEquals('', $request->getHeader('Content-Length')); $request->getBody()->setAggregator(Query::duplicateAggregator()); $request->getBody()->applyRequestHeaders($request); $this->assertEquals('foo=bar&foo=baz', $request->getBody()); }
/** * @param Service $api Service API description * @param string $endpoint Endpoint to connect to */ public function __construct(Service $api, $endpoint) { $this->api = $api; $this->endpoint = Url::fromString($endpoint); $this->aggregator = Query::duplicateAggregator(); }
/** * Get the aggregator used to join multi-valued field parameters * * @return callable */ final protected function getAggregator() { if (!$this->aggregator) { $this->aggregator = Query::phpAggregator(); } return $this->aggregator; }
public function testPhpEncodesNoNumericIndices() { $agg = Query::phpAggregator(false); $result = $agg($this->encodeData); $this->assertEquals(array('t[v1][]' => ['a', '1'], 't[v2]' => ['b'], 't[v3][v4]' => ['c'], 't[v3][v5]' => ['d']), $result); }
/** * @param string $endpointUrl * @param array $putData * * @return \stdClass * * @throws GenericHTTPError * @throws InvalidCredentials * @throws MissingEndpoint * @throws MissingRequiredParameters */ public function put($endpointUrl, $putData) { $request = $this->mgClient->createRequest('PUT', $endpointUrl, ['body' => $putData]); /** @var \GuzzleHttp\Post\PostBodyInterface $postBody */ $postBody = $request->getBody(); $postBody->setAggregator(Query::duplicateAggregator()); $response = $this->mgClient->send($request); return $this->responseHandler($response); }
/** * 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); }