/**
  * Decode an HTTP Response.
  * @static
  * @throws Google_ServiceException
  * @param Google_HttpRequest $response The http response to be decoded.
  * @return mixed|null
  */
 public static function decodeHttpResponse($response)
 {
     $code = $response->getResponseHttpCode();
     $body = $response->getResponseBody();
     $decoded = null;
     if (intVal($code) >= 300) {
         $decoded = json_decode($body, true);
         $err = 'Error calling ' . $response->getRequestMethod() . ' ' . $response->getUrl();
         if ($decoded != null && isset($decoded['error']['message']) && isset($decoded['error']['code'])) {
             // if we're getting a json encoded error definition, use that instead of the raw response
             // body for improved readability
             $err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}";
         } else {
             $err .= ": ({$code}) {$body}";
         }
         throw new Google_ServiceException($err, $code, null, $decoded['error']['errors']);
     }
     // Only attempt to decode the response, if the response code wasn't (204) 'no content'
     if ($code != '204') {
         $decoded = json_decode($body, true);
         if ($decoded === null || $decoded === "") {
             throw new Google_ServiceException("Invalid json in service response: {$body}");
         }
     }
     return $decoded;
 }
Exemple #2
0
 public function sign(Google_HttpRequest $request)
 {
     if ($this->key) {
         $request->setUrl($request->getUrl() . (strpos($request->getUrl(), '?') === false ? '?' : '&') . 'key=' . urlencode($this->key));
     }
     return $request;
 }
 public function testDecodeEmptyResponse()
 {
     $url = 'http://localhost';
     $response = new Google_HttpRequest($url, 'GET', array());
     $response->setResponseBody('{}');
     $response->setResponseHttpCode(200);
     $decoded = $this->rest->decodeHttpResponse($response);
     $this->assertEquals(array(), $decoded);
 }
 public function parseResponse(Google_HttpRequest $response)
 {
     $contentType = $response->getResponseHeader('content-type');
     $contentType = explode(';', $contentType);
     $boundary = false;
     foreach ($contentType as $part) {
         $part = explode('=', $part, 2);
         if (isset($part[0]) && 'boundary' == trim($part[0])) {
             $boundary = $part[1];
         }
     }
     $body = $response->getResponseBody();
     if ($body) {
         $body = str_replace("--{$boundary}--", "--{$boundary}", $body);
         $parts = explode("--{$boundary}", $body);
         $responses = array();
         foreach ($parts as $part) {
             $part = trim($part);
             if (!empty($part)) {
                 list($metaHeaders, $part) = explode("\r\n\r\n", $part, 2);
                 $metaHeaders = Google_CurlIO::parseResponseHeaders($metaHeaders);
                 $status = substr($part, 0, strpos($part, "\n"));
                 $status = explode(" ", $status);
                 $status = $status[1];
                 list($partHeaders, $partBody) = Google_CurlIO::parseHttpResponse($part, false);
                 $response = new Google_HttpRequest("");
                 $response->setResponseHttpCode($status);
                 $response->setResponseHeaders($partHeaders);
                 $response->setResponseBody($partBody);
                 $response = Google_REST::decodeHttpResponse($response);
                 // Need content id.
                 $responses[$metaHeaders['content-id']] = $response;
             }
         }
         return $responses;
     }
     return null;
 }
 /**
  * Send the request via our curl object.
  *
  * @param curl $curl prepared curl object.
  * @param Google_HttpRequest $request The request.
  * @return string result of the request.
  */
 private function do_request($curl, $request)
 {
     $url = $request->getUrl();
     $method = $request->getRequestMethod();
     switch (strtoupper($method)) {
         case 'POST':
             $ret = $curl->post($url, $request->getPostBody());
             break;
         case 'GET':
             $ret = $curl->get($url);
             break;
         case 'HEAD':
             $ret = $curl->head($url);
             break;
         case 'PUT':
             $ret = $curl->put($url);
             break;
         default:
             throw new coding_exception('Unknown request type: ' . $method);
             break;
     }
     return $ret;
 }
Exemple #6
0
 /**
  * Include an accessToken in a given apiHttpRequest.
  * @param Google_HttpRequest $request
  * @return Google_HttpRequest
  * @throws Google_AuthException
  */
 public function sign(Google_HttpRequest $request)
 {
     // add the developer key to the request before signing it
     if ($this->developerKey) {
         $requestUrl = $request->getUrl();
         $requestUrl .= strpos($request->getUrl(), '?') === false ? '?' : '&';
         $requestUrl .= 'key=' . urlencode($this->developerKey);
         $request->setUrl($requestUrl);
     }
     // Cannot sign the request without an OAuth access token.
     if (null == $this->token && null == $this->assertionCredentials) {
         return $request;
     }
     // Check if the token is set to expire in the next 30 seconds
     // (or has already expired).
     if ($this->isAccessTokenExpired()) {
         if ($this->assertionCredentials) {
             $this->refreshTokenWithAssertion();
         } else {
             if (!array_key_exists('refresh_token', $this->token)) {
                 throw new Google_AuthException("The OAuth 2.0 access token has expired, " . "and a refresh token is not available. Refresh tokens are not " . "returned for responses that were auto-approved.");
             }
             $this->refreshToken($this->token['refresh_token']);
         }
     }
     // Add the OAuth2 header to the request
     $request->setRequestHeaders(array('Authorization' => 'Bearer ' . $this->token['access_token']));
     return $request;
 }
 /**
  * @static
  * @param Google_HttpRequest $resp
  * @return bool True if the HTTP response is considered to be expired.
  * False if it is considered to be fresh.
  */
 public static function isExpired(Google_HttpRequest $resp)
 {
     // HTTP/1.1 clients and caches MUST treat other invalid date formats,
     // especially including the value “0”, as in the past.
     $parsedExpires = false;
     $responseHeaders = $resp->getResponseHeaders();
     if (isset($responseHeaders['expires'])) {
         $rawExpires = $responseHeaders['expires'];
         // Check for a malformed expires header first.
         if (empty($rawExpires) || is_numeric($rawExpires) && $rawExpires <= 0) {
             return true;
         }
         // See if we can parse the expires header.
         $parsedExpires = strtotime($rawExpires);
         if (false == $parsedExpires || $parsedExpires <= 0) {
             return true;
         }
     }
     // Calculate the freshness of an http response.
     $freshnessLifetime = false;
     $cacheControl = $resp->getParsedCacheControl();
     if (isset($cacheControl['max-age'])) {
         $freshnessLifetime = $cacheControl['max-age'];
     }
     $rawDate = $resp->getResponseHeader('date');
     $parsedDate = strtotime($rawDate);
     if (empty($rawDate) || false == $parsedDate) {
         $parsedDate = time();
     }
     if (false == $freshnessLifetime && isset($responseHeaders['expires'])) {
         $freshnessLifetime = $parsedExpires - $parsedDate;
     }
     if (false == $freshnessLifetime) {
         return true;
     }
     // Calculate the age of an http response.
     $age = max(0, time() - $parsedDate);
     if (isset($responseHeaders['age'])) {
         $age = max($age, strtotime($responseHeaders['age']));
     }
     return $freshnessLifetime <= $age;
 }
Exemple #8
0
 /**
  * Update a cached request, using the headers from the last response.
  * @param Google_HttpRequest $cached A previously cached response.
  * @param mixed Associative array of response headers from the last request.
  */
 protected function updateCachedRequest($cached, $responseHeaders)
 {
     if (isset($responseHeaders['connection'])) {
         $hopByHop = array_merge(self::$HOP_BY_HOP, explode(',', $responseHeaders['connection']));
         $endToEnd = array();
         foreach ($hopByHop as $key) {
             if (isset($responseHeaders[$key])) {
                 $endToEnd[$key] = $responseHeaders[$key];
             }
         }
         $cached->setResponseHeaders($endToEnd);
     }
 }
 /**
  * @param $name
  * @param $arguments
  * @return Google_HttpRequest|array
  * @throws Google_Exception
  */
 public function __call($name, $arguments)
 {
     if (!isset($this->methods[$name])) {
         throw new Google_Exception("Unknown function: {$this->serviceName}->{$this->resourceName}->{$name}()");
     }
     $method = $this->methods[$name];
     $parameters = $arguments[0];
     // postBody is a special case since it's not defined in the discovery document as parameter, but we abuse the param entry for storing it
     $postBody = null;
     if (isset($parameters['postBody'])) {
         if (is_object($parameters['postBody'])) {
             $this->stripNull($parameters['postBody']);
         }
         // Some APIs require the postBody to be set under the data key.
         if (is_array($parameters['postBody']) && 'latitude' == $this->serviceName) {
             if (!isset($parameters['postBody']['data'])) {
                 $rawBody = $parameters['postBody'];
                 unset($parameters['postBody']);
                 $parameters['postBody']['data'] = $rawBody;
             }
         }
         $postBody = is_array($parameters['postBody']) || is_object($parameters['postBody']) ? json_encode($parameters['postBody']) : $parameters['postBody'];
         unset($parameters['postBody']);
         if (isset($parameters['optParams'])) {
             $optParams = $parameters['optParams'];
             unset($parameters['optParams']);
             $parameters = array_merge($parameters, $optParams);
         }
     }
     if (!isset($method['parameters'])) {
         $method['parameters'] = array();
     }
     $method['parameters'] = array_merge($method['parameters'], $this->stackParameters);
     foreach ($parameters as $key => $val) {
         if ($key != 'postBody' && !isset($method['parameters'][$key])) {
             throw new Google_Exception("({$name}) unknown parameter: '{$key}'");
         }
     }
     if (isset($method['parameters'])) {
         foreach ($method['parameters'] as $paramName => $paramSpec) {
             if (isset($paramSpec['required']) && $paramSpec['required'] && !isset($parameters[$paramName])) {
                 throw new Google_Exception("({$name}) missing required param: '{$paramName}'");
             }
             if (isset($parameters[$paramName])) {
                 $value = $parameters[$paramName];
                 $parameters[$paramName] = $paramSpec;
                 $parameters[$paramName]['value'] = $value;
                 unset($parameters[$paramName]['required']);
             } else {
                 unset($parameters[$paramName]);
             }
         }
     }
     // Discovery v1.0 puts the canonical method id under the 'id' field.
     if (!isset($method['id'])) {
         $method['id'] = $method['rpcMethod'];
     }
     // Discovery v1.0 puts the canonical path under the 'path' field.
     if (!isset($method['path'])) {
         $method['path'] = $method['restPath'];
     }
     $servicePath = $this->service->servicePath;
     // Process Media Request
     $contentType = false;
     if (isset($method['mediaUpload'])) {
         $media = Google_MediaFileUpload::process($postBody, $parameters);
         if ($media) {
             $contentType = isset($media['content-type']) ? $media['content-type'] : null;
             $postBody = isset($media['postBody']) ? $media['postBody'] : null;
             $servicePath = $method['mediaUpload']['protocols']['simple']['path'];
             $method['path'] = '';
         }
     }
     $url = Google_REST::createRequestUri($servicePath, $method['path'], $parameters);
     $httpRequest = new Google_HttpRequest($url, $method['httpMethod'], null, $postBody);
     if ($postBody) {
         $contentTypeHeader = array();
         if (isset($contentType) && $contentType) {
             $contentTypeHeader['content-type'] = $contentType;
         } else {
             $contentTypeHeader['content-type'] = 'application/json; charset=UTF-8';
             $contentTypeHeader['content-length'] = Google_Utils::getStrLen($postBody);
         }
         $httpRequest->setRequestHeaders($contentTypeHeader);
     }
     $httpRequest = Google_Client::$auth->sign($httpRequest);
     if (Google_Client::$useBatch) {
         return $httpRequest;
     }
     // Terminate immediatly if this is a resumable request.
     if (isset($parameters['uploadType']['value']) && 'resumable' == $parameters['uploadType']['value']) {
         return $httpRequest;
     }
     return Google_REST::execute($httpRequest);
 }
Exemple #10
0
 /**
  * Send an API request to Google.
  *
  * This method overwrite the parent one so that the Google SDK will use our class
  * curl to proceed with the requests. This allows us to have control over the
  * proxy parameters and other stuffs.
  *
  * Note that the caching support of the Google SDK has been removed from this function.
  *
  * @param Google_HttpRequest $request the http request to be executed
  * @return Google_HttpRequest http request with the response http code, response
  * headers and response body filled in
  * @throws Google_IOException on curl or IO error
  */
 public function makeRequest(Google_HttpRequest $request)
 {
     if (array_key_exists($request->getRequestMethod(), self::$ENTITY_HTTP_METHODS)) {
         $request = $this->processEntityRequest($request);
     }
     $curl = new curl();
     $curl->setopt($this->curlParams);
     $curl->setopt(array('CURLOPT_URL' => $request->getUrl()));
     $requestHeaders = $request->getRequestHeaders();
     if ($requestHeaders && is_array($requestHeaders)) {
         $parsed = array();
         foreach ($requestHeaders as $k => $v) {
             $parsed[] = "{$k}: {$v}";
         }
         $curl->setHeader($parsed);
     }
     $curl->setopt(array('CURLOPT_CUSTOMREQUEST' => $request->getRequestMethod(), 'CURLOPT_USERAGENT' => $request->getUserAgent()));
     $respdata = $this->do_request($curl, $request);
     // Retry if certificates are missing.
     if ($curl->get_errno() == CURLE_SSL_CACERT) {
         error_log('SSL certificate problem, verify that the CA cert is OK.' . ' Retrying with the CA cert bundle from google-api-php-client.');
         $curl->setopt(array('CURLOPT_CAINFO' => dirname(__FILE__) . '/io/cacerts.pem'));
         $respdata = $this->do_request($curl, $request);
     }
     $infos = $curl->get_info();
     $respheadersize = $infos['header_size'];
     $resphttpcode = (int) $infos['http_code'];
     $curlerrornum = $curl->get_errno();
     $curlerror = $curl->error;
     if ($curlerrornum != CURLE_OK) {
         throw new Google_IOException("HTTP Error: ({$resphttpcode}) {$curlerror}");
     }
     // Parse out the raw response into usable bits.
     list($responseHeaders, $responseBody) = self::parseHttpResponse($respdata, $respheadersize);
     // Fill in the apiHttpRequest with the response values.
     $request->setResponseHttpCode($resphttpcode);
     $request->setResponseHeaders($responseHeaders);
     $request->setResponseBody($responseBody);
     return $request;
 }
Exemple #11
0
 /**
  * Update a cached request, using the headers from the last response.
  * @param Google_HttpRequest $cached A previously cached response.
  * @param mixed Associative array of response headers from the last request.
  */
 protected function updateCachedRequest($cached, $responseHeaders)
 {
     $hopByHop = self::$HOP_BY_HOP;
     if (!empty($responseHeaders['connection'])) {
         $connectionHeaders = array_map('strtolower', array_filter(array_map('trim', explode(',', $responseHeaders['connection']))));
         $hopByHop += array_fill_keys($connectionHeaders, true);
     }
     $endToEnd = array_diff_key($responseHeaders, $hopByHop);
     $cached->setResponseHeaders($endToEnd);
 }
 public function testAuthCache()
 {
     $io = new Google_CurlIO();
     $url = "http://www.googleapis.com/protected/resource";
     // Create a cacheable request/response, but it should not be cached.
     $cacheReq = new Google_HttpRequest($url, "GET");
     $cacheReq->setRequestHeaders(array("Accept" => "*/*", "Authorization" => "Bearer Foo"));
     $cacheReq->setResponseBody("{\"a\": \"foo\"}");
     $cacheReq->setResponseHttpCode(200);
     $cacheReq->setResponseHeaders(array("Cache-Control" => "private", "ETag" => "\"this-is-an-etag\"", "Expires" => "Sun, 22 Jan 2022 09:00:56 GMT", "Date: Sun, 1 Jan 2012 09:00:56 GMT", "Content-Type" => "application/json; charset=UTF-8"));
     $result = $io->setCachedRequest($cacheReq);
     $this->assertFalse($result);
 }
Exemple #13
0
 /**
  * @visible for testing
  * Process an http request that contains an enclosed entity.
  * @param Google_HttpRequest $request
  * @return Google_HttpRequest Processed request with the enclosed entity.
  */
 public function processEntityRequest(Google_HttpRequest $request)
 {
     $postBody = $request->getPostBody();
     $contentType = $request->getRequestHeader("content-type");
     // Set the default content-type as application/x-www-form-urlencoded.
     if (false == $contentType) {
         $contentType = self::FORM_URLENCODED;
         $request->setRequestHeaders(array('content-type' => $contentType));
     }
     // Force the payload to match the content-type asserted in the header.
     if ($contentType == self::FORM_URLENCODED && is_array($postBody)) {
         $postBody = http_build_query($postBody, '', '&');
         $request->setPostBody($postBody);
     }
     // Make sure the content-length header is set.
     if (!$postBody || is_string($postBody)) {
         $postsLength = strlen($postBody);
         $request->setRequestHeaders(array('content-length' => $postsLength));
     }
     return $request;
 }
 private function getResumeUri(Google_HttpRequest $httpRequest)
 {
     $result = null;
     $body = $httpRequest->getPostBody();
     if ($body) {
         $httpRequest->setRequestHeaders(array('content-type' => 'application/json; charset=UTF-8', 'content-length' => Google_Utils::getStrLen($body), 'x-upload-content-type' => $this->mimeType, 'x-upload-content-length' => $this->size, 'expect' => ''));
     }
     $response = Google_Client::$io->makeRequest($httpRequest);
     $location = $response->getResponseHeader('location');
     $code = $response->getResponseHttpCode();
     if (200 == $code && true == $location) {
         return $location;
     }
     throw new Google_Exception("Failed to start the resumable upload");
 }
 public function testMustRevalidate()
 {
     $now = time();
     // Expires 1 year in the future, and contains the must-revalidate directive.
     // Don't revalidate. must-revalidate only applies to expired entries.
     $future = $now + 365 * 24 * 60 * 60;
     $resp = new Google_HttpRequest('http://localhost', 'GET');
     $resp->setResponseHttpCode('200');
     $resp->setResponseHeaders(array('Cache-Control' => 'max-age=3600, must-revalidate', 'Expires' => gmdate('D, d M Y H:i:s', $future) . ' GMT', 'Date' => gmdate('D, d M Y H:i:s', $now) . ' GMT'));
     $this->assertFalse(Google_CacheParser::mustRevalidate($resp));
     // Contains the max-age=3600 directive, but was created 2 hours ago.
     // Must revalidate.
     $past = $now - 2 * 60 * 60;
     $resp = new Google_HttpRequest('http://localhost', 'GET');
     $resp->setResponseHttpCode('200');
     $resp->setResponseHeaders(array('Cache-Control' => 'max-age=3600', 'Expires' => gmdate('D, d M Y H:i:s', $future) . ' GMT', 'Date' => gmdate('D, d M Y H:i:s', $past) . ' GMT'));
     $this->assertTrue(Google_CacheParser::mustRevalidate($resp));
     // Contains the max-age=3600 directive, and was created 600 seconds ago.
     // No need to revalidate, regardless of the expires header.
     $past = $now - 600;
     $resp = new Google_HttpRequest('http://localhost', 'GET');
     $resp->setResponseHttpCode('200');
     $resp->setResponseHeaders(array('Cache-Control' => 'max-age=3600', 'Expires' => gmdate('D, d M Y H:i:s', $past) . ' GMT', 'Date' => gmdate('D, d M Y H:i:s', $past) . ' GMT'));
     $this->assertFalse(Google_CacheParser::mustRevalidate($resp));
 }
Exemple #16
0
 /**
  * Update a cached request, using the headers from the last response.
  * @param Google_HttpRequest $cached A previously cached response.
  * @param mixed Associative array of response headers from the last request.
  */
 protected function updateCachedRequest($cached, $responseHeaders)
 {
     $hopByHop = self::$HOP_BY_HOP;
     if (!empty($responseHeaders['connection'])) {
         $connectionHeaders = array_map('strtolower', array_filter(array_map('trim', explode(',', $responseHeaders['connection']))));
         $hopByHop += array_fill_keys($connectionHeaders, true);
     }
     $endToEnd = array();
     foreach ($responseHeaders as $key => $val) {
         if (empty($hopByHop[$key])) {
             $endToEnd[$key] = $val;
         }
     }
     $cached->setResponseHeaders($endToEnd);
 }