/** * Decode an HTTP Response. * @static * @throws displetretsidx_Google_ServiceException * @param displetretsidx_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 displetretsidx_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 displetretsidx_Google_ServiceException("Invalid json in service response: {$body}"); } } return $decoded; }
public function sign(displetretsidx_Google_HttpRequest $request) { if ($this->key) { $request->setUrl($request->getUrl() . (strpos($request->getUrl(), '?') === false ? '?' : '&') . 'key=' . urlencode($this->key)); } return $request; }
public function parseResponse(displetretsidx_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 = displetretsidx_Google_CurlIO::parseResponseHeaders($metaHeaders); $status = substr($part, 0, strpos($part, "\n")); $status = explode(" ", $status); $status = $status[1]; list($partHeaders, $partBody) = displetretsidx_Google_CurlIO::parseHttpResponse($part, false); $response = new displetretsidx_Google_HttpRequest(""); $response->setResponseHttpCode($status); $response->setResponseHeaders($partHeaders); $response->setResponseBody($partBody); $response = displetretsidx_Google_REST::decodeHttpResponse($response); // Need content id. $responses[$metaHeaders['content-id']] = $response; } } return $responses; } return null; }
/** * Include an accessToken in a given apiHttpRequest. * @param displetretsidx_Google_HttpRequest $request * @return displetretsidx_Google_HttpRequest * @throws displetretsidx_Google_AuthException */ public function sign(displetretsidx_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 displetretsidx_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; }
/** * @param $name * @param $arguments * @return displetretsidx_Google_HttpRequest|array * @throws displetretsidx_Google_Exception */ public function __call($name, $arguments) { if (!isset($this->methods[$name])) { throw new displetretsidx_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 displetretsidx_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 displetretsidx_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 = displetretsidx_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 = displetretsidx_Google_REST::createRequestUri($servicePath, $method['path'], $parameters); $httpRequest = new displetretsidx_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'] = displetretsidx_Google_Utils::getStrLen($postBody); } $httpRequest->setRequestHeaders($contentTypeHeader); } $httpRequest = displetretsidx_Google_Client::$auth->sign($httpRequest); if (displetretsidx_Google_Client::$useBatch) { return $httpRequest; } // Terminate immediately if this is a resumable request. if (isset($parameters['uploadType']['value']) && displetretsidx_Google_MediaFileUpload::UPLOAD_RESUMABLE_TYPE == $parameters['uploadType']['value']) { $contentTypeHeader = array(); if (isset($contentType) && $contentType) { $contentTypeHeader['content-type'] = $contentType; } $httpRequest->setRequestHeaders($contentTypeHeader); if ($postBody) { $httpRequest->setPostBody($postBody); } return $httpRequest; } return displetretsidx_Google_REST::execute($httpRequest); }
/** * @visible for testing * Process an http request that contains an enclosed entity. * @param displetretsidx_Google_HttpRequest $request * @return displetretsidx_Google_HttpRequest Processed request with the enclosed entity. */ public function processEntityRequest(displetretsidx_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; }
/** * @static * @param displetretsidx_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(displetretsidx_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; }
private function getResumeUri(displetretsidx_Google_HttpRequest $httpRequest) { $result = null; $body = $httpRequest->getPostBody(); if ($body) { $httpRequest->setRequestHeaders(array('content-type' => 'application/json; charset=UTF-8', 'content-length' => displetretsidx_Google_Utils::getStrLen($body), 'x-upload-content-type' => $this->mimeType, 'x-upload-content-length' => $this->size, 'expect' => '')); } $response = displetretsidx_Google_Client::$io->makeRequest($httpRequest); $location = $response->getResponseHeader('location'); $code = $response->getResponseHttpCode(); if (200 == $code && true == $location) { return $location; } throw new displetretsidx_Google_Exception("Failed to start the resumable upload"); }