/** * {@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); }
/** * @param AccessTokenInterface $token * @param array $options */ public function __construct(AccessTokenInterface $token, array $options = []) { $options = array_merge($options, ['emitter' => EventsManager::getEmitter()]); parent::__construct($options); if ($token instanceof OAuth2AccessTokenInterface) { $this->getEmitter()->on('before', function (BeforeEvent $event) use($token) { /** @var \Eva\EvaOAuth\OAuth2\Token\AccessToken $token */ $event->getRequest()->setHeader('Authorization', $token->getTokenType() . ' ' . $token->getTokenValue()); }); } else { $signatureMethod = isset($options['signature_method']) ? $options['signature_method'] : SignatureInterface::METHOD_HMAC_SHA1; $signatureClasses = [SignatureInterface::METHOD_PLAINTEXT => 'Eva\\EvaOAuth\\OAuth1\\Signature\\PlainText', SignatureInterface::METHOD_HMAC_SHA1 => 'Eva\\EvaOAuth\\OAuth1\\Signature\\Hmac', SignatureInterface::METHOD_RSA_SHA1 => 'Eva\\EvaOAuth\\OAuth1\\Signature\\Rsa']; if (false === isset($signatureClasses[$signatureMethod])) { throw new InvalidArgumentException(sprintf('Signature method %s not able to process', $signatureMethod)); } $signatureClass = $signatureClasses[$signatureMethod]; $this->getEmitter()->on('before', function (BeforeEvent $event) use($token, $signatureClass) { /** @var Request $request */ $request = $event->getRequest(); /** @var \Eva\EvaOAuth\OAuth1\Token\AccessToken $token */ $httpMethod = strtoupper($request->getMethod()); $url = Url::fromString($request->getUrl()); $parameters = ['oauth_consumer_key' => $token->getConsumerKey(), 'oauth_signature_method' => SignatureInterface::METHOD_HMAC_SHA1, 'oauth_timestamp' => (string) time(), 'oauth_nonce' => strtolower(Text::generateRandomString(32)), 'oauth_token' => $token->getTokenValue(), 'oauth_version' => '1.0']; $signature = (string) new $signatureClass($token->getConsumerSecret(), Text::buildBaseString($httpMethod, $url, $parameters), $token->getTokenSecret()); $parameters['oauth_signature'] = $signature; $event->getRequest()->setHeader('Authorization', Text::buildHeaderString($parameters)); }); } }
/** * Builds the URI template for a REST based request. * * @param array $operation * @param array $args * * @return array */ private function buildEndpoint($operation, array $args) { $endpoint = Url::fromString($this->endpoint); $varspecs = []; if (isset($operation['http']['requestUri'])) { $endpoint->combine($operation['http']['requestUri']); // Create an associative array of varspecs used in expansions if (isset($operation['parameters'])) { foreach ($operation['parameters'] as $name => $member) { if ($member['location'] == 'uri') { $varspecs[isset($member['locationName']) ? $member['locationName'] : $name] = isset($args[$name]) ? $args[$name] : null; } elseif ($member['location'] == 'query' && !empty($args[$name])) { $endpoint->getQuery()->set($name, $args[$name]); } } } } $uri = (string) $endpoint; return preg_replace_callback('/%7B([^\\}]+)%7D/', function (array $matches) use($varspecs) { $isGreedy = substr($matches[1], -1, 1) == '+'; $k = $isGreedy ? substr($matches[1], 0, -1) : $matches[1]; if (!isset($varspecs[$k])) { return ''; } elseif ($isGreedy) { return str_replace('%2F', '/', rawurlencode($varspecs[$k])); } else { return rawurlencode($varspecs[$k]); } }, $uri); }
/** * {@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); }
public function onPrepared(PreparedEvent $event) { $command = $event->getCommand(); if ($command->hasParam('QueueUrl')) { $request = $event->getRequest(); $url = Url::fromString($request->getUrl()); $request->setUrl($url->combine($command['QueueUrl'])); } }
public function testStripsFragmentFromHost() { Server::flush(); Server::enqueue("HTTP/1.1 200 OK\r\n\r\nContent-Length: 0\r\n\r\n"); // This will fail if the removal of the #fragment is not performed $url = Url::fromString(Server::$url)->setPath(null)->setFragment('foo'); $client = new Client(); $client->get($url); }
public static function getArguments() { $args = parent::getArguments(); $args['endpoint']['required'] = true; $args['region']['default'] = function (array $args) { // Determine the region from the provided endpoint. // (e.g. http://search-blah.{region}.cloudsearch.amazonaws.com) return explode('.', Url::fromString($args['endpoint']))[1]; }; return $args; }
/** * @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; }
private function createPresignedUrl(AwsClientInterface $client, CommandInterface $cmd) { $newCmd = $client->getCommand('CopySnapshot', $cmd->toArray()); $newCmd->getEmitter()->detach($this); // Serialize a request for the CopySnapshot operation. $request = $client->initTransaction($newCmd)->request; // Create the new endpoint for the target endpoint. $endpoint = EndpointProvider::resolve($this->endpointProvider, ['region' => $cmd['SourceRegion'], 'service' => 'ec2'])['endpoint']; // Set the request to hit the target endpoint. $request->setHost(Url::fromString($endpoint)->getHost()); // Create a presigned URL for our generated request. $signer = new SignatureV4('ec2', $cmd['SourceRegion']); return $signer->createPresignedUrl(SignatureV4::convertPostToGet($request), $client->getCredentials(), '+1 hour'); }
/** * Parses a URL into an associative array of Amazon S3 data including: * * - bucket: The Amazon S3 bucket (null if none) * - key: The Amazon S3 key (null if none) * - path_style: Set to true if using path style, or false if not * - region: Set to a string if a non-class endpoint is used or null. * * @param $uri * * @return array * @throws \InvalidArgumentException */ public function parse($uri) { $url = Url::fromString($uri); if (!$url->getHost()) { throw new \InvalidArgumentException('No hostname found in URI: ' . $uri); } if (!preg_match($this->pattern, $url->getHost(), $matches)) { return $this->parseCustomEndpoint($url); } // Parse the URI based on the matched format (path / virtual) $result = empty($matches[1]) ? $this->parsePathStyle($url) : $this->parseVirtualHosted($url, $matches); // Add the region if one was found and not the classic endpoint $result['region'] = $matches[2] == 'amazonaws' ? null : $matches[2]; return $result; }
/** * Validates a message from SNS to ensure that it was delivered by AWS * * @param Message $message The message to validate * * @throws MessageValidatorException If the certificate cannot be * retrieved, if the certificate's source cannot be verified, or if the * message's signature is invalid. */ public function validate(Message $message) { // Get and validate the URL for the certificate. $certUrl = Url::fromString($message->get('SigningCertURL')); $this->validateUrl($certUrl); // Get the cert itself and extract the public key $certificate = $this->client->get((string) $certUrl)->getBody(); $key = openssl_get_publickey($certificate); if (!$key) { throw new MessageValidatorException('Cannot get the public key ' . 'from the certificate.'); } // Verify the signature of the message $content = $message->getStringToSign(); $signature = base64_decode($message->get('Signature')); if (!openssl_verify($content, $signature, $key, OPENSSL_ALGO_SHA1)) { throw new MessageValidatorException('The message signature is ' . 'invalid.'); } }
/** * @param array $config Service description data * @param array $options Custom options to apply to the description * - formatter: Can provide a custom SchemaFormatter class * * @throws \InvalidArgumentException */ public function __construct(array $config, array $options = []) { // Keep a list of default keys used in service descriptions that is // later used to determine extra data keys. static $defaultKeys = ['name', 'models', 'apiVersion', 'description']; // Pull in the default configuration values foreach ($defaultKeys as $key) { if (isset($config[$key])) { $this->{$key} = $config[$key]; } } // Set the baseUrl $this->baseUrl = Url::fromString(isset($config['baseUrl']) ? $config['baseUrl'] : ''); // Ensure that the models and operations properties are always arrays $this->models = (array) $this->models; $this->operations = (array) $this->operations; // We want to add operations differently than adding the other properties $defaultKeys[] = 'operations'; // Create operations for each operation if (isset($config['operations'])) { foreach ($config['operations'] as $name => $operation) { if (!is_array($operation)) { throw new \InvalidArgumentException('Operations must be arrays'); } $this->operations[$name] = $operation; } } // Get all of the additional properties of the service description and // store them in a data array foreach (array_diff(array_keys($config), $defaultKeys) as $key) { $this->extraData[$key] = $config[$key]; } // Configure the schema formatter if (isset($options['formatter'])) { $this->formatter = $options['formatter']; } else { static $defaultFormatter; if (!$defaultFormatter) { $defaultFormatter = new SchemaFormatter(); } $this->formatter = $defaultFormatter; } }
/** * Create a signed Amazon CloudFront URL. * * Keep in mind that URLs meant for use in media/flash players may have * different requirements for URL formats (e.g. some require that the * extension be removed, some require the file name to be prefixed * - mp4:<path>, some require you to add "/cfx/st" into your URL). * * @param string $url URL to sign (can include query * string string and wildcards * @param string|integer|null $expires UTC Unix timestamp used when signing * with a canned policy. Not required * when passing a custom $policy. * @param string $policy JSON policy. Use this option when * creating a signed URL for a custom * policy. * * @return string The file URL with authentication parameters * @throws \InvalidArgumentException if the URL provided is invalid * @link http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/WorkingWithStreamingDistributions.html */ public function getUrlSigner($url, $expires = null, $policy = null) { // Determine the scheme of the url $urlSections = explode('://', $url); if (count($urlSections) < 2) { throw new \InvalidArgumentException("Invalid URL: {$url}"); } // Get the real scheme by removing wildcards from the scheme $scheme = str_replace('*', '', $urlSections[0]); if ($policy) { $isCustom = true; } else { $isCustom = false; $policy = $this->createCannedPolicy($scheme, $url, $expires); } $policy = str_replace(' ', '', $policy); $url = Url::fromString($scheme . '://' . $urlSections[1]); $this->prepareQuery($isCustom, $policy, $url->getQuery(), $expires); return $scheme === 'rtmp' ? $this->createRtmpUrl($url) : (string) $url; }
/** * * @param string $url * @return HttpRequest[] */ private function buildRequestSet($url) { $useEncodingOptions = $this->getConfiguration()->getToggleUrlEncoding() ? array(true, false) : array(true); $requests = array(); $userAgentSelection = $this->getConfiguration()->getUserAgentSelectionForRequest(); foreach ($userAgentSelection as $userAgent) { foreach ($this->getConfiguration()->getHttpMethodList() as $methodIndex => $method) { foreach ($useEncodingOptions as $useEncoding) { $requestUrl = GuzzleUrl::fromString($url); $requestUrl->getQuery()->setEncodingType($useEncoding ? GuzzleQuery::RFC3986 : false); $request = $this->getConfiguration()->getHttpClient()->createRequest('GET', $requestUrl); $request->setHeader('user-agent', $userAgent); if ($this->getConfiguration()->hasReferrer()) { $request->setHeader('Referer', $this->getConfiguration()->getReferrer()); } $requests[] = $request; } } } return $requests; }
private function extractHeaders(BrowserKitRequest $request) { $headers = array(); $server = $request->getServer(); $uri = Url::fromString($request->getUri()); $server['HTTP_HOST'] = $uri->getHost(); $port = $uri->getPort(); if ($port !== null && $port !== 443 && $port != 80) { $server['HTTP_HOST'] .= ':' . $port; } $contentHeaders = array('Content-Length' => true, 'Content-Md5' => true, 'Content-Type' => true); foreach ($server as $header => $val) { $header = implode('-', array_map('ucfirst', explode('-', strtolower(str_replace('_', '-', $header))))); if (strpos($header, 'Http-') === 0) { $headers[substr($header, 5)] = $val; } elseif (isset($contentHeaders[$header])) { $headers[$header] = $val; } } $zendHeaders = new HttpHeaders(); $zendHeaders->addHeaders($headers); return $zendHeaders; }
/** * Subscribes to a feed. */ public function onPostFetch(FetchEvent $event) { $feed = $event->getFeed(); $fetcher = $feed->getType()->getFetcher(); $subscription = $this->storage->load($feed->id()); if (!$fetcher->getConfiguration('use_pubsubhubbub')) { return $this->unsubscribe($feed, $subscription); } if (!($hub = $this->findRelation($event->getFetcherResult(), 'hub'))) { $hub = $fetcher->getConfiguration('fallback_hub'); } // No hub found. if (!$hub) { return $this->unsubscribe($feed, $subscription); } // Used to make other URLs absolute. $source_url = Url::fromString($feed->getSource()); $hub = (string) $source_url->combine($hub); // If there is a rel="self" relation. if ($topic = $this->findRelation($event->getFetcherResult(), 'self')) { $topic = (string) $source_url->combine($topic); $feed->setSource($topic); } else { $topic = $feed->getSource(); } // Subscription does not exist yet. if (!$subscription) { $subscription = $this->storage->create(['fid' => $feed->id(), 'topic' => $topic, 'hub' => $hub]); return $this->subscribe($feed, $subscription); } if ($topic !== $subscription->getTopic() || $subscription->getHub() !== $hub || $subscription->getState() !== 'subscribed') { // Unsubscribe from the old feed. $this->unsubscribe($feed, $subscription); $subscription = $this->storage->create(['fid' => $feed->id(), 'topic' => $topic, 'hub' => $hub]); return $this->subscribe($feed, $subscription); } }
public function setUrl($url) { $this->url = $url instanceof Url ? $url : Url::fromString($url); $this->updateHostHeaderFromUrl(); return $this; }
public function getSsoUrl() { $params = array('response_type' => 'code', 'client_id' => $this->config['ssoClientId'], 'redirect_uri' => $this->config['ssoRedirectUrl'], 'scope' => AuthenticationSubscriber::SSO_SCOPE); $url = Url::fromString($this->config['ssoBaseUrl']); $url->setPath('/oauth/authorize'); $url->setQuery($params); return (string) $url; }
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()); }
/** * 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); }
private function configureBaseUrl(&$config) { if (!isset($config['base_url'])) { $this->baseUrl = new Url('', ''); } elseif (is_array($config['base_url'])) { $this->baseUrl = Url::fromString(\GuzzleHttp\uri_template($config['base_url'][0], $config['base_url'][1])); $config['base_url'] = (string) $this->baseUrl; } else { $this->baseUrl = Url::fromString($config['base_url']); } }
/** * Resolve the route to a generated url * * @param array $item * * @return string */ private function resolveRouteToLink(array $item) { $param = !empty($item['param']) ? $item['param'] : []; if (isset($item['add'])) { $this->app['logger.system']->warning(Trans::__('Menu item property "add" is deprecated. Use "#" under "param" instead.'), ['event' => 'deprecated']); $add = $item['add']; if (!empty($add) && $add[0] !== '?') { $add = '?' . $add; } $url = Url::fromString($add); $param = array_merge($param, $url->getQuery()->toArray()); $param['#'] = $url->getFragment(); } return $this->app['url_generator']->generate($item['route'], $param); }
public function testCorrectlyEncodesPathWithoutDoubleEncoding() { $url = Url::fromString('http://foo.com/baz%20 bar:boo/baz!'); $this->assertEquals('/baz%20%20bar:boo/baz!', $url->getPath()); }
private function configureBaseUrl(&$config) { if (!isset($config['base_url'])) { $this->baseUrl = new Url('', ''); } elseif (!is_array($config['base_url'])) { $this->baseUrl = Url::fromString($config['base_url']); } elseif (count($config['base_url']) < 2) { throw new \InvalidArgumentException('You must provide a hash of ' . 'varname options in the second element of a base_url array.'); } else { $this->baseUrl = Url::fromString(Utils::uriTemplate($config['base_url'][0], $config['base_url'][1])); $config['base_url'] = (string) $this->baseUrl; } }
protected function parseConnections($options, $defaultHost, $defaultPort) { if (isset($options['host']) || isset($options['port'])) { $options['connections'][] = $options; } /** @var Url[] $toParse */ $toParse = []; if (isset($options['connections'])) { foreach ((array) $options['connections'] as $alias => $conn) { if (is_string($conn)) { $conn = ['host' => $conn]; } $scheme = isset($conn['scheme']) ? $conn['scheme'] : 'tcp'; $host = isset($conn['host']) ? $conn['host'] : $defaultHost; $url = new Url($scheme, $host); $url->setPort(isset($conn['port']) ? $conn['port'] : $defaultPort); if (isset($conn['path'])) { $url->setPath($conn['path']); } if (isset($conn['password'])) { $url->setPassword($conn['password']); } $url->getQuery()->replace($conn); $toParse[] = $url; } } elseif (isset($options['save_path'])) { foreach (explode(',', $options['save_path']) as $conn) { $toParse[] = Url::fromString($conn); } } $connections = []; foreach ($toParse as $url) { $connections[] = ['scheme' => $url->getScheme(), 'host' => $url->getHost(), 'port' => $url->getPort(), 'path' => $url->getPath(), 'alias' => $url->getQuery()->get('alias'), 'prefix' => $url->getQuery()->get('prefix'), 'password' => $url->getPassword(), 'database' => $url->getQuery()->get('database'), 'persistent' => $url->getQuery()->get('persistent'), 'weight' => $url->getQuery()->get('weight'), 'timeout' => $url->getQuery()->get('timeout')]; } return $connections; }
/** * @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)); }
public function testCanBeUrlObject() { $config = array_merge($this->minimal, ['authorizationUri' => Url::fromString('https://another/uri')]); $o = new OAuth2($config); $this->assertEquals('/uri', $o->buildFullAuthorizationUri()->getPath()); }
/** * 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); }
/** * 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); }
/** * @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(); }