private function parseVirtualHosted(Url $url, array $matches) { $result = self::$defaultResult; $result['path_style'] = false; // Remove trailing "." from the prefix to get the bucket $result['bucket'] = substr($matches[1], 0, -1); $path = $url->getPath(); // Check if a key was present, and if so, removing the leading "/" $result['key'] = !$path || $path == '/' ? null : substr($path, 1); return $result; }
/** * Builds the URI template for a REST based request. * * @param Operation $operation * @param array $args * * @return array */ private function buildEndpoint(Operation $operation, array $args) { $varspecs = []; if ($operation->getInput()->getType() !== 'list') { // Create an associative array of varspecs used in expansions foreach ($operation->getInput()->getMembers() as $name => $member) { if ($member['location'] == 'uri') { $varspecs[$member['locationName'] ?: $name] = isset($args[$name]) ? $args[$name] : null; } } } // Expand path place holders using Amazon's slightly different URI // template syntax. return $this->endpoint->combine(preg_replace_callback('/\\{([^\\}]+)\\}/', 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]); } }, $operation['http']['requestUri'])); }
/** * {@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); }
/** * Ensures that the url of the certificate is one belonging to AWS, and not * just something from the amazonaws domain, which includes S3 buckets. * * @param Url $url * * @throws MessageValidatorException if the cert url is invalid */ private function validateUrl(Url $url) { // The cert URL must be https, a .pem, and match the following pattern. $hostPattern = '/^sns\\.[a-zA-Z0-9\\-]{3,}\\.amazonaws\\.com(\\.cn)?$/'; if ($url->getScheme() !== 'https' || substr($url, -4) !== '.pem' || !preg_match($hostPattern, $url->getHost())) { throw new MessageValidatorException('The certificate is located ' . 'on an invalid domain.'); } }
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'); }
/** * Create a request or response object from an HTTP message string * * @param string $message Message to parse * * @return RequestInterface|ResponseInterface * @throws \InvalidArgumentException if unable to parse a message */ public function fromMessage($message) { static $parser; if (!$parser) { $parser = new MessageParser(); } // Parse a response if (strtoupper(substr($message, 0, 4)) == 'HTTP') { $data = $parser->parseResponse($message); return $this->createResponse($data['code'], $data['headers'], $data['body'] === '' ? null : $data['body'], $data); } // Parse a request if (!($data = $parser->parseRequest($message))) { throw new \InvalidArgumentException('Unable to parse request'); } return $this->createRequest($data['method'], Url::buildUrl($data['request_url']), ['headers' => $data['headers'], 'body' => $data['body'] === '' ? null : $data['body'], 'config' => ['protocol_version' => $data['protocol_version']]]); }
/** * @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; } }
/** * * @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; }
/** * Returns an absolute URL for the passed URI with the current URL * as the base path. * * @param string $uri the absolute or relative URI * @return string the absolute URL * @throws Codeception\Exception\TestRuntime if either the current * URL or the passed URI can't be parsed */ protected function getAbsoluteUrlFor($uri) { $currentUrl = $this->client->getHistory()->current()->getUri(); if (empty($uri) || $uri === '#') { return $currentUrl; } $build = parse_url($currentUrl); $uriParts = parse_url($uri); if ($build === false) { throw new TestRuntime("URL '{$currentUrl}' is malformed"); } elseif ($uriParts === false) { throw new TestRuntime("URI '{$uri}' is malformed"); } $abs = $this->mergeUrls($build, $uriParts); return \GuzzleHttp\Url::buildUrl($abs); }
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; }
/** * 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 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)); }