Example #1
0
 /**
  * @param RequestInterface|EntityEnclosingRequestInterface $request
  * @param Credentials $credentials
  */
 public function signRequest($request, $credentials)
 {
     $request->setHeader('X-HMB-Signature-Method', self::DEFAULT_METHOD);
     $request->setHeader('X-HMB-Signature-Version', self::DEFAULT_SIGN_VERSION);
     $request->setHeader('X-HMB-TimeStamp', time());
     $contentMd5 = $request instanceof EntityEnclosingRequestInterface ? md5($request->getBody()) : '';
     if ($contentMd5) {
         $request->setHeader('Content-MD5', $contentMd5);
     }
     $sign = array();
     $sign[] = strtoupper($request->getMethod());
     $sign[] = $request->getHost();
     if ($request->getHeader('Content-MD5')) {
         $sign[] = $request->getHeader('Content-MD5');
     }
     if ($request->getHeader('Content-Type')) {
         $sign[] = $request->getHeader('Content-Type');
     }
     $sign[] = $request->getHeader('X-HMB-Signature-Method');
     $sign[] = $request->getHeader('X-HMB-Signature-Version');
     $sign[] = $request->getHeader('X-HMB-TimeStamp');
     if ($request->getHeader('X-HMB-User-Session-Token')) {
         $sign[] = $request->getHeader('X-HMB-User-Session-Token');
     }
     $sign[] = $request->getQuery(true) ? $request->getPath() . '?' . $request->getQuery(true) : $request->getPath();
     $signature = base64_encode(hash_hmac(strtolower($request->getHeader('X-HMB-Signature-Method')), implode("\n", $sign), $credentials->getSecret()));
     $request->setHeader('Authorization', sprintf('%s %s:%s', self::AUTHORIZATION_SCHME, $credentials->getKey(), $signature));
 }
Example #2
0
 /**
  * {@inheritdoc}
  * @throws \UnexpectedValueException If a controller is not \Ratchet\Http\HttpServerInterface
  */
 public function onOpen(ConnectionInterface $conn, RequestInterface $request = null)
 {
     if (null === $request) {
         throw new \UnexpectedValueException('$request can not be null');
     }
     $context = $this->_matcher->getContext();
     $context->setMethod($request->getMethod());
     $context->setHost($request->getHost());
     try {
         $route = $this->_matcher->match($request->getPath());
     } catch (MethodNotAllowedException $nae) {
         return $this->close($conn, 403);
     } catch (ResourceNotFoundException $nfe) {
         return $this->close($conn, 404);
     }
     if (is_string($route['_controller']) && class_exists($route['_controller'])) {
         $route['_controller'] = new $route['_controller']();
     }
     if (!$route['_controller'] instanceof HttpServerInterface) {
         throw new \UnexpectedValueException('All routes must implement Ratchet\\Http\\HttpServerInterface');
     }
     $parameters = array();
     foreach ($route as $key => $value) {
         if (is_string($key) && '_' !== substr($key, 0, 1)) {
             $parameters[$key] = $value;
         }
     }
     $parameters = array_merge($parameters, $request->getQuery()->getAll());
     $url = Url::factory($request->getPath());
     $url->setQuery($parameters);
     $request->setUrl($url);
     $conn->controller = $route['_controller'];
     $conn->controller->onOpen($conn, $request);
 }
 private function addQueryString(array $queryString, RequestInterface $request)
 {
     ksort($queryString);
     foreach ($queryString as $key => $value) {
         $request->getQuery()->set($key, $value);
     }
 }
Example #4
0
 /**
  * Sign the Pusher request
  *
  * @link  http://pusher.com/docs/rest_api#authentication
  * @param RequestInterface $request
  * @param Credentials $credentials
  */
 public function signRequest(RequestInterface $request, Credentials $credentials)
 {
     $queryParameters = array('auth_key' => $credentials->getKey(), 'auth_timestamp' => time(), 'auth_version' => self::AUTH_VERSION);
     if ($request instanceof EntityEnclosingRequestInterface) {
         $body = $request->getBody();
         $queryParameters['body_md5'] = $body->getContentLength() ? $body->getContentMd5() : '';
     }
     // The signature algorithm asks that keys are all lowercased
     $queryParameters = array_change_key_case($request->getQuery()->toArray()) + $queryParameters;
     $queryParameters = array_filter($queryParameters);
     ksort($queryParameters);
     $method = strtoupper($request->getMethod());
     $requestPath = $request->getPath();
     $query = urldecode(http_build_query($queryParameters));
     $signature = $this->signString(implode("\n", array($method, $requestPath, $query)), $credentials);
     $queryParameters['auth_signature'] = $signature;
     $request->getQuery()->replace($queryParameters);
 }
 public function onOpen(ConnectionInterface $from, RequestInterface $request = null)
 {
     $requestPath = $request->getPath();
     $pathParts = explode('/', preg_replace('#^/peerjs/#', '', $requestPath));
     //Remove /peerjs
     $action = array_pop($pathParts);
     $query = $request->getQuery();
     $peerId = isset($query['id']) ? $query['id'] : null;
     $peerToken = isset($query['token']) ? $query['token'] : null;
     $respStatus = 200;
     $respHeaders = array('Access-Control-Allow-Origin' => '*');
     $respBody = null;
     switch ($action) {
         case 'id':
             $respHeaders['Content-Type'] = 'text/html';
             if ($peerId === null) {
                 do {
                     $peerId = substr(sha1(uniqid('', true) . mt_rand()), 0, self::PEERID_LENGTH);
                 } while ($this->peerServer->peerIdExists($peerId));
             }
             $respBody = $peerId;
             break;
         case 'peers':
             if (self::ALLOW_DISCOVERY) {
                 $peers = $this->peerServer->listPeers();
                 $list = array();
                 foreach ($peers as $peer) {
                     $list[] = $peer['id'];
                 }
                 $respBody = $list;
             } else {
                 $respStatus = 401;
                 // Access denied
             }
             break;
         case 'offer':
         case 'candidate':
         case 'answer':
         case 'leave':
             //TODO: start streaming?
         //TODO: start streaming?
         default:
             $respStatus = 400;
             //Bad request
     }
     if (is_array($respBody)) {
         // Encode to JSON
         $respHeaders['Content-Type'] = 'application/json';
         $respBody = json_encode($respBody);
     }
     //Send response
     $response = new Response($respStatus, $respHeaders, (string) $respBody);
     $from->send((string) $response);
     $from->close();
 }
Example #6
0
 public function getParamsToSign(RequestInterface $request, $timestamp, $nonce)
 {
     $params = $this->getOauthParams($timestamp, $nonce);
     $params->merge($request->getQuery());
     if ($this->shouldPostFieldsBeSigned($request)) {
         $params->merge($request->getPostFields());
     }
     $params = $params->toArray();
     ksort($params);
     return $params;
 }
Example #7
0
 public function onCommand(RequestInterface $request)
 {
     $applicationName = $request->getQuery()->get('app');
     $module = $request->getQuery()->get('module');
     if (!$module) {
         $module = 'index';
     }
     try {
         $application = $this->applications->get($applicationName);
         $this->get('event_dispatcher')->dispatch($application->getName() . '.state.activate', new InteractionEvent($request));
         $this->get('event_dispatcher')->dispatch($this->currentApplication->getName() . '.state.deactivate', new InteractionEvent($request));
         $this->get('server.web_socket')->switchApp($applicationName, $module);
         $this->currentApplication = $application;
         $this->currentModule = $module;
     } catch (ApplicationNotFoundException $e) {
         return $this->jsonResponse(404, 'This application does not exist.');
     } catch (ApplicationInitializationException $e) {
         return $this->jsonResponse(400, $e->getMessage());
     }
     return $this->jsonResponse(200, 'Application switched.');
 }
 /**
  * Get the issue count from the provided request.
  *
  *
  * @param array $request
  *   Guzzle request for the first page of results.
  * @return number
  *   The total number of issues for the search paramaters of the request.
  */
 public function getCount(\Guzzle\Http\Message\RequestInterface $request)
 {
     // Make sure page isn't set from a previous call on the same request object.
     $request->getQuery()->remove('page');
     $issueRowCount = 0;
     while (true) {
         $document = new DomCrawler\Crawler((string) $request->send()->getBody());
         $issueView = $document->filter('.view-project-issue-search-project-searchapi');
         $issueRowCount += $issueView->filter('table.views-table tbody tr')->reduce(function (DomCrawler\Crawler $element) {
             // Drupal.org is returning rows where all cells are empty,
             // which bumps up the count incorrectly.
             return $element->filter('td')->first()->filter('a')->count() > 0;
         })->count();
         $pagerNext = $issueView->filter('.pager-next a');
         if (!$pagerNext->count()) {
             break;
         }
         preg_match('/page=(\\d+)/', $pagerNext->attr('href'), $urlMatches);
         $request->getQuery()->set('page', (int) $urlMatches[1]);
     }
     return $issueRowCount;
 }
Example #9
0
 /**
  * Get the canonicalized query/parameter string for a request
  *
  * @param RequestInterface $request Request used to build canonicalized string
  *
  * @return string
  */
 public function getCanonicalizedParameterString(RequestInterface $request)
 {
     if ($request->getMethod() == 'POST') {
         $params = $request->getPostFields()->toArray();
     } else {
         $params = $request->getQuery()->toArray();
     }
     // Don't resign a previous signature value
     unset($params['Signature']);
     uksort($params, 'strcmp');
     $str = '';
     foreach ($params as $key => $val) {
         $str .= rawurlencode($key) . '=' . rawurlencode($val) . '&';
     }
     return substr($str, 0, -1);
 }
Example #10
0
 /**
  * Returns an HTML-formatted string representation of the exception.
  *
  * @return string
  * @internal
  */
 public function __toString()
 {
     $msg = $this->getMessage();
     if (is_object($this->requestObj) && $this->requestObj instanceof \Guzzle\Http\Message\Request) {
         $request = array('url' => $this->requestObj->getUrl(), 'host' => $this->requestObj->getHost(), 'headers' => $this->requestObj->getRawHeaders(), 'query' => (string) $this->requestObj->getQuery());
         if ($this->requestObj instanceof \Guzzle\Http\Message\EntityEnclosingRequestInterface) {
             $request_body = $this->requestObj->getBody();
             $request['content-type'] = $request_body->getContentType();
             $request['content-length'] = $request_body->getContentLength();
             $request['body'] = $request_body->__toString();
         }
         $msg .= "\n\nRequest: <pre>" . htmlspecialchars(print_r($request, true)) . '</pre>';
     }
     if (is_object($this->responseObj) && $this->responseObj instanceof \Guzzle\Http\Message\Response) {
         $response = array('status' => $this->responseObj->getStatusCode(), 'headers' => $this->responseObj->getRawHeaders(), 'body' => $this->responseBody);
         $msg .= "\n\nResponse: <pre>" . htmlspecialchars(print_r($response, true)) . '</pre>';
     }
     return $msg;
 }
 /**
  * Get the canonicalized query string for a request
  *
  * @param  RequestInterface $request
  * @return string
  */
 protected function getCanonicalizedQueryString(RequestInterface $request)
 {
     $queryParams = $request->getQuery()->getAll();
     unset($queryParams['X-Amz-Signature']);
     if (empty($queryParams)) {
         return '';
     }
     $qs = '';
     ksort($queryParams);
     foreach ($queryParams as $key => $values) {
         if (is_array($values)) {
             sort($values);
         } elseif (!$values) {
             $values = array('');
         }
         foreach ((array) $values as $value) {
             $qs .= rawurlencode($key) . '=' . rawurlencode($value) . '&';
         }
     }
     return substr($qs, 0, -1);
 }
Example #12
0
 public function getParamsToSign(RequestInterface $request, $timestamp, $nonce)
 {
     $params = new Collection(array('oauth_consumer_key' => $this->config['consumer_key'], 'oauth_nonce' => $nonce, 'oauth_signature_method' => $this->config['signature_method'], 'oauth_timestamp' => $timestamp, 'oauth_version' => $this->config['version']));
     // Filter out oauth_token during temp token step, as in request_token.
     if ($this->config['token'] !== false) {
         $params->add('oauth_token', $this->config['token']);
     }
     // Add call back uri
     if (isset($this->config['callback_uri']) && !empty($this->config['callback_uri'])) {
         $params->add('oauth_callback', $this->config['callback_uri']);
     }
     // Add query string parameters
     $params->merge($request->getQuery());
     // Add POST fields to signing string
     if (!$this->config->get('disable_post_params') && $request instanceof EntityEnclosingRequestInterface && false !== strpos($request->getHeader('Content-Type'), 'application/x-www-form-urlencoded')) {
         $params->merge($request->getPostFields());
     }
     // Sort params
     $params = $params->getAll();
     ksort($params);
     return $params;
 }
Example #13
0
 public function onActivate(RequestInterface $request)
 {
     $this->message = $request->getQuery()->get('message');
 }
Example #14
0
 /**
  * Parameters sorted and filtered in order to properly sign a request
  *
  * @param RequestInterface $request   Request to generate a signature for
  * @param integer          $timestamp Timestamp to use for nonce
  * @param string           $nonce
  *
  * @return array
  */
 public function getParamsToSign(RequestInterface $request, $timestamp, $nonce)
 {
     $params = new Collection(array('oauth_consumer_key' => $this->config['consumer_key'], 'oauth_nonce' => $nonce, 'oauth_signature_method' => $this->config['signature_method'], 'oauth_timestamp' => $timestamp, 'oauth_token' => $this->config['token'], 'oauth_version' => $this->config['version']));
     if (array_key_exists('callback', $this->config) == true) {
         $params['oauth_callback'] = $this->config['callback'];
     }
     if (array_key_exists('verifier', $this->config) == true) {
         $params['oauth_verifier'] = $this->config['verifier'];
     }
     // Add query string parameters
     $params->merge($request->getQuery());
     // Add POST fields to signing string if required
     if ($this->shouldPostFieldsBeSigned($request)) {
         $params->merge($request->getPostFields());
     }
     // Sort params
     $params = $params->toArray();
     ksort($params);
     return $params;
 }
Example #15
0
protected function visit_query(RequestInterface $request, $value, $flags)
{
if (!is_array($value)) {
throw new InvalidArgumentException('query value must be an array');
}

if ($flags & self::OPTIONS_AS_DEFAULTS) {

 $query = $request->getQuery();
$query->overwriteWith(array_diff_key($value, $query->toArray()));
} else {
$request->getQuery()->overwriteWith($value);
}
}
Example #16
0
 private function moveHeadersToQuery(RequestInterface $request)
 {
     $query = $request->getQuery();
     foreach ($request->getHeaders() as $name => $header) {
         if (substr($name, 0, 5) == 'x-amz') {
             $query[$header->getName()] = (string) $header;
         }
         if ($name !== 'host') {
             $request->removeHeader($name);
         }
     }
 }
Example #17
0
 /**
  * Get the collection of key value pairs that will be used as the query
  * string in the request
  *
  * @return QueryString
  */
 public function getQuery()
 {
     return $this->wrapped->getQuery();
 }
 /**
  * @param RequestInterface $request
  * @param array $params
  * @return $this
  */
 protected function addFilters(RequestInterface $request, $params = array())
 {
     $filters = array();
     foreach ($params as $key => $value) {
         if (!$value) {
             continue;
         }
         $filters[] = array('field' => $key, 'value' => '%' . $value . '%', 'operator' => 'like');
     }
     $request->getQuery()->set('filters', $filters);
     return $this;
 }
Example #19
0
 private function prepareRequest(RequestInterface $request, $options = array())
 {
     $request->setAuth($this->apiKey, $this->secretKey);
     $query = $request->getQuery();
     $query->add('output', $this->getRealOutputFormat());
     foreach ($options as $option => $value) {
         $query->add($option, $value);
     }
 }
Example #20
0
 /**
  * Sets the cdbxml version query parameter on a HTTP request.
  *
  * @param RequestInterface $request
  */
 private function addVersionToRequest(RequestInterface $request)
 {
     if (version_compare($this->cdbXmlVersion, '3.3', '>=')) {
         $request->getQuery()->add('version', $this->cdbXmlVersion);
     }
 }
 /**
  * Add a query string signature to a request
  *
  * @param RequestInterface $request Request to modify
  */
 public function addQueryStringSignature(RequestInterface $request)
 {
     $qs = $request->getQuery();
     // Create a string that needs to be signed using the request settings
     $strToSign = $this->signature->calculateStringToSign($qs->getAll(), array('endpoint' => $request->getUrl(), 'method' => $request->getMethod()));
     // Add the signature to the query string of the request
     $qs->set('Signature', $this->signature->signString($strToSign));
     return true;
 }
Example #22
0
 /**
  * {@inheritdoc}
  */
 public function visit(CommandInterface $command, RequestInterface $request, $key, $value)
 {
     $request->getQuery()->set($key, $value);
 }
 /**
  * @return string
  */
 public function getQuery()
 {
     $qs = (string) $this->request->getQuery();
     return !empty($qs) ? $qs : null;
 }
 /**
  * Collect & sanitize data about a Guzzle request
  *
  * @param Guzzle\Http\Message\RequestInterface $request
  *
  * @return array
  */
 private function collectRequest(GuzzleRequestInterface $request)
 {
     $body = null;
     if ($request instanceof EntityEnclosingRequestInterface) {
         $body = (string) $request->getBody();
     }
     return array('headers' => $request->getHeaders(), 'method' => $request->getMethod(), 'scheme' => $request->getScheme(), 'host' => $request->getHost(), 'port' => $request->getPort(), 'path' => $request->getPath(), 'query' => $request->getQuery(), 'body' => $body);
 }
Example #25
0
 private function addQueryStringValues(RequestInterface $request, $credential, $expires)
 {
     // Set query params required for pre-signed URLs
     $request->getQuery()->set('X-Amz-Algorithm', 'AWS4-HMAC-SHA256')->set('X-Amz-Credential', $credential)->set('X-Amz-SignedHeaders', 'Host')->set('X-Amz-Expires', $expires);
 }
 public function onFeed(RequestInterface $request)
 {
     $statuses = $this->get('twitter')->search(array('q' => $this->hashtag, 'since_id' => $request->getQuery()->get('sinceId'), 'count' => 10));
     return new Response(200, array('Content-Type' => 'application/json'), json_encode($statuses));
 }
Example #27
0
 /**
  * Calculate the hash key of a request object
  *
  * @param RequestInterface $request Request to hash
  * @param string           $raw     Set to TRUE to retrieve the un-encoded string for debugging
  *
  * @return string
  */
 public function getCacheKey(RequestInterface $request, $raw = false)
 {
     // See if the key has already been calculated
     $key = $request->getParams()->get('cache.key');
     // Always recalculate when using the raw option
     if (!$key || $raw) {
         // Generate the start of the key
         $key = $request->getScheme() . '_' . $request->getHost() . $request->getPath();
         $filterHeaders = array('Cache-Control');
         $filterQuery = array();
         // Check to see how and if the key should be filtered
         foreach (explode(';', $request->getParams()->get('cache.key_filter')) as $part) {
             $pieces = array_map('trim', explode('=', $part));
             if (isset($pieces[1])) {
                 $remove = array_map('trim', explode(',', $pieces[1]));
                 if ($pieces[0] == 'header') {
                     $filterHeaders = array_merge($filterHeaders, $remove);
                 } elseif ($pieces[0] == 'query') {
                     $filterQuery = array_merge($filterQuery, $remove);
                 }
             }
         }
         // Use the filtered query string
         $queryString = (string) $request->getQuery()->filter(function ($key, $value) use($filterQuery) {
             return !in_array($key, $filterQuery);
         });
         // Use the filtered headers
         $headerString = http_build_query($request->getHeaders()->map(function ($key, $value) {
             return count($value) == 1 ? $value[0] : $value;
         })->filter(function ($key, $value) use($filterHeaders) {
             return !in_array($key, $filterHeaders);
         })->getAll());
         if ($raw) {
             $key = strtolower('gz_' . $key . $queryString . '_' . $headerString);
         } else {
             $key = strtolower('gz_' . md5($key . $queryString . '_' . $headerString));
             $request->getParams()->set('cache.key', $key);
         }
     }
     return $key;
 }
 /**
  * Get all of the parameters required to sign a request including:
  * * The oauth params
  * * The request GET params
  * * The params passed in the POST body (with a content-type of application/x-www-form-urlencoded)
  *
  * @param RequestInterface $request   Request to generate a signature for
  * @param integer          $timestamp Timestamp to use for nonce
  * @param string           $nonce
  *
  * @return array
  */
 public function getParamsToSign(RequestInterface $request, $timestamp, $nonce)
 {
     $params = $this->getOauthParams($timestamp, $nonce);
     // Add query string parameters
     $params->merge($request->getQuery());
     // Add POST fields to signing string if required
     if ($this->shouldPostFieldsBeSigned($request)) {
         $params->merge($request->getPostFields());
     }
     // Sort params
     $params = $params->toArray();
     ksort($params);
     return $params;
 }
Example #29
0
 public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value)
 {
     $request->getQuery()->set($param->getWireName(), $this->prepareValue($value, $param));
 }
 /**
  * Add the request's signature
  * 
  * @param RequestInterface $request Request which will be modified
  */
 protected function addQueryStringSignature(RequestInterface $request)
 {
     $qs = $request->getQuery();
     $requestToSign = $this->signature->composeRequestToSign($qs->getAll(), array('endpoint' => $request->getUrl(), 'method' => $request->getMethod()));
     $qs->set('Signature', $this->signature->signRequest($requestToSign));
     return true;
 }