public static function execute($requests) { $jsonRpcRequest = array(); foreach ($requests as $request) { $parameters = array(); foreach ($request->getParameters() as $parameterName => $parameterVal) { $parameters[$parameterName] = $parameterVal['value']; } $jsonRpcRequest[] = array('id' => $request->getBatchKey(), 'method' => $request->getRpcName(), 'params' => $parameters, 'apiVersion' => 'v1'); } $httpRequest = new apiHttpRequest($request->getRpcPath()); $httpRequest->setRequestHeaders(array('Content-Type' => 'application/json')); $httpRequest->setRequestMethod('POST'); $httpRequest->setPostBody(json_encode($jsonRpcRequest)); $httpRequest = apiClient::$io->authenticatedRequest($httpRequest); if (($decodedResponse = json_decode($httpRequest->getResponseBody(), true)) != false) { $ret = array(); foreach ($decodedResponse as $response) { $ret[$response['id']] = self::checkNextLink($response['result']); } return $ret; } else { throw new apiServiceException("Invalid json returned by the json-rpc end-point"); } }
public function testIsResponseCacheable() { $resp = new apiHttpRequest('http://localhost', 'POST'); $result = apiCacheParser::isResponseCacheable($resp); $this->assertFalse($result); // The response has expired, and we don't have an etag for // revalidation. $resp = new apiHttpRequest('http://localhost', 'GET'); $resp->setResponseHttpCode('200'); $resp->setResponseHeaders(array('Cache-Control' => 'max-age=3600, must-revalidate', 'Expires' => 'Fri, 30 Oct 1998 14:19:41 GMT', 'Date' => 'Mon, 29 Jun 1998 02:28:12 GMT', 'Last-Modified' => 'Mon, 29 Jun 1998 02:28:12 GMT')); $result = apiCacheParser::isResponseCacheable($resp); $this->assertFalse($result); // Verify cacheable responses. $resp = new apiHttpRequest('http://localhost', 'GET'); $resp->setResponseHttpCode('200'); $resp->setResponseHeaders(array('Cache-Control' => 'max-age=3600, must-revalidate', 'Expires' => 'Fri, 30 Oct 2013 14:19:41 GMT', 'Date' => 'Mon, 29 Jun 2011 02:28:12 GMT', 'Last-Modified' => 'Mon, 29 Jun 2011 02:28:12 GMT', 'ETag' => '3e86-410-3596fbbc')); $result = apiCacheParser::isResponseCacheable($resp); $this->assertTrue($result); // Verify that responses to HEAD requests are cacheable. $resp = new apiHttpRequest('http://localhost', 'HEAD'); $resp->setResponseHttpCode('200'); $resp->setResponseBody(null); $resp->setResponseHeaders(array('Cache-Control' => 'max-age=3600, must-revalidate', 'Expires' => 'Fri, 30 Oct 2013 14:19:41 GMT', 'Date' => 'Mon, 29 Jun 2011 02:28:12 GMT', 'Last-Modified' => 'Mon, 29 Jun 2011 02:28:12 GMT', 'ETag' => '3e86-410-3596fbbc')); $result = apiCacheParser::isResponseCacheable($resp); $this->assertTrue($result); // Verify that Vary: * cannot get cached. $resp = new apiHttpRequest('http://localhost', 'GET'); $resp->setResponseHttpCode('200'); $resp->setResponseHeaders(array('Cache-Control' => 'max-age=3600, must-revalidate', 'Expires' => 'Fri, 30 Oct 2013 14:19:41 GMT', 'Date' => 'Mon, 29 Jun 2011 02:28:12 GMT', 'Last-Modified' => 'Mon, 29 Jun 2011 02:28:12 GMT', 'Vary' => 'foo', 'ETag' => '3e86-410-3596fbbc')); $result = apiCacheParser::isResponseCacheable($resp); $this->assertFalse($result); // Verify 201s cannot get cached. $resp = new apiHttpRequest('http://localhost', 'GET'); $resp->setResponseHttpCode('201'); $resp->setResponseBody(null); $resp->setResponseHeaders(array('Cache-Control' => 'max-age=3600, must-revalidate', 'Expires' => 'Fri, 30 Oct 2013 14:19:41 GMT', 'Last-Modified' => 'Mon, 29 Jun 2011 02:28:12 GMT', 'ETag' => '3e86-410-3596fbbc')); $result = apiCacheParser::isResponseCacheable($resp); $this->assertFalse($result); // Verify pragma: no-cache. $resp = new apiHttpRequest('http://localhost', 'GET'); $resp->setResponseHttpCode('200'); $resp->setResponseHeaders(array('Expires' => 'Wed, 11 Jan 2012 04:03:37 GMT', 'Date' => 'Wed, 11 Jan 2012 04:03:37 GMT', 'Pragma' => 'no-cache', 'Cache-Control' => 'private, max-age=0, must-revalidate, no-transform', 'ETag' => '3e86-410-3596fbbc')); $result = apiCacheParser::isResponseCacheable($resp); $this->assertFalse($result); // Verify Cache-Control: no-store. $resp = new apiHttpRequest('GET'); $resp->setResponseHttpCode('200'); $resp->setResponseHeaders(array('Expires' => 'Wed, 11 Jan 2012 04:03:37 GMT', 'Date' => 'Wed, 11 Jan 2012 04:03:37 GMT', 'Cache-Control' => 'no-store', 'ETag' => '3e86-410-3596fbbc')); $result = apiCacheParser::isResponseCacheable($resp); $this->assertFalse($result); // Verify that authorized responses are not cacheable. $resp = new apiHttpRequest('http://localhost', 'GET'); $resp->setRequestHeaders(array('Authorization' => 'Bearer Token')); $resp->setResponseHttpCode('200'); $resp->setResponseHeaders(array('Cache-Control' => 'max-age=3600, must-revalidate', 'Expires' => 'Fri, 30 Oct 2013 14:19:41 GMT', 'Last-Modified' => 'Mon, 29 Jun 2011 02:28:12 GMT', 'ETag' => '3e86-410-3596fbbc')); $result = apiCacheParser::isResponseCacheable($resp); $this->assertFalse($result); }
public function execute() { $body = ''; /** @var apiHttpRequest $req */ foreach ($this->requests as $key => $req) { $body .= "--{$this->boundary}\n"; $body .= $req->toBatchString($key) . "\n"; } $body = rtrim($body); $body .= "\n--{$this->boundary}--"; global $apiConfig; $url = $apiConfig['basePath'] . '/batch'; $httpRequest = new apiHttpRequest($url, 'POST'); $httpRequest->setRequestHeaders(array('Content-Type' => 'multipart/mixed; boundary=' . $this->boundary)); $httpRequest->setPostBody($body); $response = apiClient::$io->makeRequest($httpRequest); $response = $this->parseResponse($response); return $response; }
/** * Executes a apiServiceRequest using a RESTful call by transforming it into * an apiHttpRequest, and executed via apiIO::authenticatedRequest(). * * @param apiServiceRequest $req * @return array decoded result * @throws apiServiceException on server side error (ie: not authenticated, invalid or * malformed post body, invalid url) */ public static function execute(apiServiceRequest $req) { $result = null; $postBody = $req->getPostBody(); $url = self::createRequestUri($req->getRestBasePath(), $req->getRestPath(), $req->getParameters()); $httpRequest = new apiHttpRequest($url, $req->getHttpMethod(), null, $postBody); if ($postBody) { $contentTypeHeader = array(); if (isset($req->contentType) && $req->contentType) { $contentTypeHeader['content-type'] = $req->contentType; } else { $contentTypeHeader['content-type'] = 'application/json; charset=UTF-8'; $contentTypeHeader['content-length'] = apiUtils::getStrLen($postBody); } $httpRequest->setRequestHeaders($contentTypeHeader); } $httpRequest = apiClient::$io->authenticatedRequest($httpRequest); $decodedResponse = self::decodeHttpResponse($httpRequest); //FIXME currently everything is wrapped in a data envelope, but hopefully this might change some day $ret = isset($decodedResponse['data']) ? $decodedResponse['data'] : $decodedResponse; return $ret; }
/** * Include an accessToken in a given apiHttpRequest. * @param apiHttpRequest $request * @return apiHttpRequest * @throws apiAuthException */ public function sign(apiHttpRequest $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->accessToken) { return $request; } // If the token is set to expire in the next 30 seconds (or has already // expired), refresh it and set the new token. $expired = $this->accessToken['created'] + ($this->accessToken['expires_in'] - 30) < time(); if ($expired) { if (!array_key_exists('refresh_token', $this->accessToken)) { throw new apiAuthException("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->accessToken['refresh_token']); } // Add the OAuth2 header to the request $request->setRequestHeaders(array('Authorization' => 'Bearer ' . $this->accessToken['access_token'])); return $request; }
/** * @visible for testing * Process an http request that contains an enclosed entity. * @param apiHttpRequest $request * @return apiHttpRequest Processed request with the enclosed entity. */ public function processEntityRequest(apiHttpRequest $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; }
public function testAuthCache() { $io = new apiCurlIO(); $url = "http://www.googleapis.com/protected/resource"; // Create a cacheable request/response, but it should not be cached. $cacheReq = new apiHttpRequest($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); }
private function getResumeUri(apiHttpRequest $httpRequest) { $result = null; $body = $httpRequest->getPostBody(); if ($body) { $httpRequest->setRequestHeaders(array('content-type' => 'application/json; charset=UTF-8', 'content-length' => apiUtils::getStrLen($body), 'x-upload-content-type' => $this->mimeType, 'expect' => '')); } $response = apiClient::$io->makeRequest($httpRequest); $location = $response->getResponseHeader('location'); $code = $response->getResponseHttpCode(); if (200 == $code && true == $location) { return $location; } throw new apiException("Failed to start the resumable upload"); }
private function getResumeUri(apiServiceRequest $req) { $result = null; $postBody = $req->getPostBody(); $url = apiREST::createRequestUri($req->getRestBasePath(), $req->getRestPath(), $req->getParameters()); $httpRequest = new apiHttpRequest($url, $req->getHttpMethod(), null, $postBody); if ($postBody) { $httpRequest->setRequestHeaders(array('content-type' => 'application/json; charset=UTF-8', 'content-length' => apiUtils::getStrLen($postBody), 'x-upload-content-type' => $this->mimeType, 'expect' => '')); } $response = apiClient::$io->authenticatedRequest($httpRequest); $location = $response->getResponseHeader('location'); $code = $response->getResponseHttpCode(); if (200 == $code && true == $location) { return $location; } throw new apiException("Failed to start the resumable upload"); }
/** * @param $name * @param $arguments * @return apiHttpRequest|array * @throws apiException */ public function __call($name, $arguments) { if (!isset($this->methods[$name])) { throw new apiException("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 apiException("({$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 apiException("({$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']; } $restBasePath = $this->service->restBasePath; // Process Media Request $contentType = false; if (isset($method['mediaUpload'])) { $media = apiMediaFileUpload::process($postBody, $parameters); if ($media) { $contentType = isset($media['content-type']) ? $media['content-type'] : null; $postBody = isset($media['postBody']) ? $media['postBody'] : null; $restBasePath = $method['mediaUpload']['protocols']['simple']['path']; $method['path'] = ''; } } $url = apiREST::createRequestUri($restBasePath, $method['path'], $parameters); $httpRequest = new apiHttpRequest($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'] = apiUtils::getStrLen($postBody); } $httpRequest->setRequestHeaders($contentTypeHeader); } $httpRequest = apiClient::$auth->sign($httpRequest); if (apiClient::$useBatch) { return $httpRequest; } // Terminate immediatly if this is a resumable request. if (isset($parameters['uploadType']['value']) && 'resumable' == $parameters['uploadType']['value']) { return $httpRequest; } return apiREST::execute($httpRequest); }