Example #1
0
 public function sign(apiHttpRequest $request)
 {
     if ($this->developerKey) {
         $request->setUrl($request->getUrl() . (strpos($request->getUrl(), '?') === false ? '?' : '&') . 'key=' . urlencode($this->developerKey));
     }
     return $request;
 }
Example #2
0
 public function testDecodeResponse()
 {
     $url = 'http://localhost';
     $response = new apiHttpRequest($url);
     $response->setResponseHttpCode(204);
     $decoded = $this->rest->decodeHttpResponse($response);
     $this->assertEquals(null, $decoded);
     foreach (array(200, 201) as $code) {
         $headers = array('foo', 'bar');
         $response = new apiHttpRequest($url, 'GET', $headers);
         $response->setResponseBody('{"a": 1}');
         $response->setResponseHttpCode($code);
         $decoded = $this->rest->decodeHttpResponse($response);
         $this->assertEquals(array("a" => 1), $decoded);
     }
     $response = new apiHttpRequest($url);
     $response->setResponseHttpCode(500);
     $error = "";
     try {
         $this->rest->decodeHttpResponse($response);
     } catch (Exception $e) {
         $error = $e->getMessage();
     }
     $this->assertEquals(trim($error), "Error calling GET http://localhost: (500)");
 }
 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");
     }
 }
Example #4
0
 /**
  * Decode an HTTP Response.
  * @static
  * @throws apiServiceException
  * @param apiHttpRequest $response The http response to be decoded.
  * @return mixed|null
  */
 static function decodeHttpResponse($response)
 {
     $code = $response->getResponseHttpCode();
     $body = $response->getResponseBody();
     $decoded = null;
     if ($code != '200' && $code != '201' && $code != '204') {
         $decoded = json_decode($body, true);
         $err = 'Error calling ' . $response->getMethod() . ' ' . $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 apiServiceException($err);
     }
     // 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) {
             throw new apiServiceException("Invalid json in service response: {$body}");
         }
     }
     return $decoded;
 }
 public function sign(apiHttpRequest $request)
 {
     if ($this->developerKey) {
         $url = $request->getUrl();
         $url .= (strpos($url, '?') === false ? '?' : '&') . 'key=' . urlencode($this->developerKey);
     }
     // else noop
     return $request;
 }
Example #6
0
 public function testDecodeEmptyResponse()
 {
     $url = 'http://localhost';
     $response = new apiHttpRequest($url, 'GET', array());
     $response->setResponseBody('{}');
     $response->setResponseHttpCode(200);
     $decoded = $this->rest->decodeHttpResponse($response);
     $this->assertEquals(array(), $decoded);
 }
 public function sign(apiHttpRequest $request)
 {
     global $apiConfig;
     $sig = "";
     if ($this->key) {
         if ($this->secret) {
             $sig = md5($this->key . $this->secret . (string) time());
         }
         $request->setUrl($request->getUrl() . (strpos($request->getUrl(), '?') === false ? '?' : '&') . $apiConfig['key_name'] . '=' . urlencode($this->key) . ($sig ? '&' . $apiConfig['signature_name'] . '=' . urlencode($sig) : ''));
         /*
          * Mod above - static "key" parameter name changed
          * to global $apiConfig variable "key_name" add signature
          * if secret exists.
          */
     }
     return $request;
 }
Example #8
0
 /**
  * @static
  * @param apiHttpRequest $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(apiHttpRequest $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 (in_array('max-age', $cacheControl)) {
         $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;
 }
 public function parseResponse(apiHttpRequest $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 = apiCurlIO::parseResponseHeaders($metaHeaders);
                 $status = substr($part, 0, strpos($part, "\n"));
                 $status = explode(" ", $status);
                 $status = $status[1];
                 list($partHeaders, $partBody) = apiCurlIO::parseHttpResponse($part, false);
                 $response = new apiHttpRequest("");
                 $response->setResponseHttpCode($status);
                 $response->setResponseHeaders($partHeaders);
                 $response->setResponseBody($partBody);
                 $response = apiREST::decodeHttpResponse($response);
                 // Need content id.
                 $responses[$metaHeaders['content-id']] = $response;
             }
         }
         return $responses;
     }
     return null;
 }
 /**
  * @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;
 }
 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");
 }
 /**
  * Sign the request using OAuth. This uses the consumer token and key
  *
  * @param string $method the method (get/put/delete/post)
  * @param string $url the url to sign (http://site/social/rest/people/1/@me)
  * @param array $params the params that should be appended to the url (count=20 fields=foo, etc)
  * @param string $postBody for POST/PUT requests, the postBody is included in the signature
  * @return string the signed url
  */
 public function sign(apiHttpRequest $request)
 {
     // add the developer key to the request before signing it
     if ($this->developerKey) {
         $url = $request->getUrl();
         $url .= (strpos($url, '?') === false ? '?' : '&') . 'key=' . urlencode($this->developerKey);
     }
     // and sign the request
     $oauthRequest = OAuthRequest::from_request($request->getMethod(), $request->getBaseUrl(), $request->getQueryParams());
     $params = $this->mergeParameters($request->getQueryParams());
     foreach ($params as $key => $val) {
         if (is_array($val)) {
             $val = implode(',', $val);
         }
         $oauthRequest->set_parameter($key, $val);
     }
     $oauthRequest->sign_request($this->signatureMethod, $this->consumerToken, $this->accessToken);
     $signedUrl = $oauthRequest->to_url();
     // Set an originalUrl property that can be used to cache the resource
     $request->originalUrl = $request->getUrl();
     // and add the access token key to it (since it doesn't include the secret, it's still secure to store this in cache)
     $request->accessKey = $this->accessToken->key;
     $request->setUrl($signedUrl);
     return $request;
 }
Example #13
0
 /**
  * Executes a apiServiceRequest using a RESTful call by transforming it into a apiHttpRequest, execute it via apiIO::authenticatedRequest()
  * and returning the json decoded result
  *
  * @param apiServiceRequest $request
  * @return array decoded result
  * @throws apiServiceException on server side error (ie: not authenticated, invalid or malformed post body, invalid url, etc)
  */
 public static function execute(apiServiceRequest $request)
 {
     global $apiTypeHandlers;
     $result = null;
     $requestUrl = $request->getRestBasePath() . $request->getRestPath();
     $uriTemplateVars = array();
     $queryVars = array();
     foreach ($request->getParameters() as $paramName => $paramSpec) {
         // Discovery v1.0 puts the canonical location under the 'location' field.
         if (!isset($paramSpec['location'])) {
             $paramSpec['location'] = $paramSpec['restParameterType'];
         }
         if ($paramSpec['location'] == 'path') {
             $uriTemplateVars[$paramName] = $paramSpec['value'];
         } else {
             if ($paramSpec['type'] == 'boolean') {
                 $paramSpec['value'] = $paramSpec['value'] ? 'true' : 'false';
             }
             if (isset($paramSpec['repeated']) && is_array($paramSpec['value'])) {
                 foreach ($paramSpec['value'] as $value) {
                     $queryVars[] = $paramName . '=' . rawurlencode($value);
                 }
             } else {
                 $queryVars[] = $paramName . '=' . rawurlencode($paramSpec['value']);
             }
         }
     }
     $queryVars[] = 'alt=json';
     if (count($uriTemplateVars)) {
         $uriTemplateParser = new URI_Template_Parser($requestUrl);
         $requestUrl = $uriTemplateParser->expand($uriTemplateVars);
     }
     //FIXME work around for the the uri template lib which url encodes the @'s & confuses our servers
     $requestUrl = str_replace('%40', '@', $requestUrl);
     //EOFIX
     //FIXME temp work around to make @groups/{@following,@followers} work (something which we should really be fixing in our API)
     if (strpos($requestUrl, '/@groups') && (strpos($requestUrl, '/@following') || strpos($requestUrl, '/@followers'))) {
         $requestUrl = str_replace('/@self', '', $requestUrl);
     }
     //EOFIX
     if (count($queryVars)) {
         $requestUrl .= '?' . implode($queryVars, '&');
     }
     $httpRequest = new apiHttpRequest($requestUrl, $request->getHttpMethod(), null, $request->getPostBody());
     // Add a content-type: application/json header so the server knows how to interpret the post body
     if ($request->getPostBody()) {
         $contentTypeHeader = array('Content-Type: application/json; charset=UTF-8', 'Content-Length: ' . self::getStrLen($request->getPostBody()));
         if ($httpRequest->getHeaders()) {
             $contentTypeHeader = array_merge($httpRequest->getHeaders(), $contentTypeHeader);
         }
         $httpRequest->setHeaders($contentTypeHeader);
     }
     $httpRequest = $request->getIo()->authenticatedRequest($httpRequest);
     if ($httpRequest->getResponseHttpCode() != '200' && $httpRequest->getResponseHttpCode() != '201' && $httpRequest->getResponseHttpCode() != '204') {
         $responseBody = $httpRequest->getResponseBody();
         if (($responseBody = json_decode($responseBody, true)) != null && isset($responseBody['error']['message']) && isset($responseBody['error']['code'])) {
             // if we're getting a json encoded error definition, use that instead of the raw response body for improved readability
             $errorMessage = "Error calling " . $httpRequest->getUrl() . ": ({$responseBody['error']['code']}) {$responseBody['error']['message']}";
         } else {
             $errorMessage = "Error calling " . $httpRequest->getMethod() . " " . $httpRequest->getUrl() . ": (" . $httpRequest->getResponseHttpCode() . ") " . $httpRequest->getResponseBody();
         }
         throw new apiServiceException($errorMessage);
     }
     $decodedResponse = null;
     if ($httpRequest->getResponseHttpCode() != '204') {
         // Only attempt to decode the response, if the response code wasn't (204) 'no content'
         if (($decodedResponse = json_decode($httpRequest->getResponseBody(), true)) == null) {
             throw new apiServiceException("Invalid json in service response: " . $httpRequest->getResponseBody());
         }
     }
     //FIXME currently everything is wrapped in a data envelope, but hopefully this might change some day
     $ret = isset($decodedResponse['data']) ? $decodedResponse['data'] : $decodedResponse;
     // Add a 'continuationToken' element to the response if the response contains a next link (so you can call it using the 'c' param)
     $ret = self::checkNextLink($ret);
     // if the response type has a registered type handler, call & return it instead of the raw response array
     if (isset($ret['kind']) && isset($apiTypeHandlers[$ret['kind']])) {
         $ret = new $apiTypeHandlers[$ret['kind']]($ret);
     }
     return $ret;
 }
Example #14
0
 /**
  * Normalize all HTTP headers.
  * @param apiHttpRequest $request
  * @return array
  */
 private function getNormalizedHeaders(apiHttpRequest $request)
 {
     if (!is_array($request->getResponseHeaders())) {
         return array();
     }
     $headers = $request->getResponseHeaders();
     $newHeaders = array();
     foreach ($headers as $key => $val) {
         $newHeaders[strtolower($key)] = $val;
     }
     return $newHeaders;
 }
Example #15
0
 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);
 }
Example #16
0
 public function testIsExpired()
 {
     $now = time();
     $future = $now + 365 * 24 * 60 * 60;
     // Expires 1 year in the future. Response is fresh.
     $resp = new apiHttpRequest('GET');
     $resp->setResponseHttpCode('200');
     $resp->setResponseHeaders(array('Expires' => gmdate('D, d M Y H:i:s', $future) . ' GMT', 'Date' => gmdate('D, d M Y H:i:s', $now) . ' GMT'));
     $this->assertFalse(apiCacheParser::isExpired($resp));
     // The response expires soon. Response is fresh.
     $resp = new apiHttpRequest('GET');
     $resp->setResponseHttpCode('200');
     $resp->setResponseHeaders(array('Expires' => gmdate('D, d M Y H:i:s', $now + 2), 'Date' => gmdate('D, d M Y H:i:s', $now) . ' GMT'));
     $this->assertFalse(apiCacheParser::isExpired($resp));
     // Expired 1 year ago. Response is stale.
     $future = $now - 365 * 24 * 60 * 60;
     $resp = new apiHttpRequest('GET');
     $resp->setResponseHttpCode('200');
     $resp->setResponseHeaders(array('Expires' => gmdate('D, d M Y H:i:s', $future) . ' GMT', 'Date' => gmdate('D, d M Y H:i:s', $now) . ' GMT'));
     $this->assertTrue(apiCacheParser::isExpired($resp));
     // Invalid expires header. Response is stale.
     $resp = new apiHttpRequest('GET');
     $resp->setResponseHttpCode('200');
     $resp->setResponseHeaders(array('Expires' => '-1', 'Date' => gmdate('D, d M Y H:i:s', $now) . ' GMT'));
     $this->assertTrue(apiCacheParser::isExpired($resp));
     // The response expires immediately. G+ APIs do this. Response is stale.
     $resp = new apiHttpRequest('GET');
     $resp->setResponseHttpCode('200');
     $resp->setResponseHeaders(array('Expires' => gmdate('D, d M Y H:i:s', $now), 'Date' => gmdate('D, d M Y H:i:s', $now) . ' GMT'));
     $this->assertTrue(apiCacheParser::isExpired($resp));
 }
 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");
 }
Example #18
0
 /**
  * Sign the request using OAuth. This uses the consumer token and key
  *
  * @param string $method the method (get/put/delete/post)
  * @param string $url the url to sign (http://site/social/rest/people/1/@me)
  * @param array $params the params that should be appended to the url (count=20 fields=foo, etc)
  * @param string $postBody for POST/PUT requests, the postBody is included in the signature
  * @return string the signed url
  */
 public function sign(apiHttpRequest $request)
 {
     // add the developer key to the request before signing it
     if ($this->developerKey) {
         $request->setUrl($request->getUrl() . (strpos($request->getUrl(), '?') === false ? '?' : '&') . 'key=' . urlencode($this->developerKey));
     }
     // and sign the request
     $oauthRequest = apiClientOAuthRequest::from_request($request->getMethod(), $request->getBaseUrl(), $request->getQueryParams());
     $params = $this->mergeParameters($request->getQueryParams());
     foreach ($params as $key => $val) {
         if (is_array($val)) {
             $val = implode(',', $val);
         }
         $oauthRequest->set_parameter($key, $val);
     }
     $oauthRequest->sign_request($this->signatureMethod, $this->consumerToken, $this->accessToken);
     $authHeaders = $oauthRequest->to_header();
     $headers = $request->getHeaders();
     $headers[] = $authHeaders;
     $request->setHeaders($headers);
     // and add the access token key to it (since it doesn't include the secret, it's still secure to store this in cache)
     $request->accessKey = $this->accessToken->key;
     return $request;
 }
Example #19
0
  public function sign(apiHttpRequest $request) {
    // add the developer key to the request before signing it
    if ($this->developerKey) {
      $request->setUrl($request->getUrl() . ((strpos($request->getUrl(), '?') === false) ? '?' : '&') . 'key=' . urlencode($this->developerKey));
    }

    // Cannot sign the request without an OAuth access token.
    if (null == $this->accessToken) {
      return $request;
    }

    if (($this->accessToken['created'] + ($this->accessToken['expires_in'] - 30)) < time()) {
      // if the token is set to expire in the next 30 seconds (or has already expired), refresh it and set the new token
      //FIXME this is mostly a copy and paste mashup from the authenticate and setAccessToken functions, should generalize them into a function instead of this mess
      $refreshRequest = $this->io->makeRequest(new apiHttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), array(
          'client_id' => $this->clientId,
          'client_secret' => $this->clientSecret,
          'refresh_token' => $this->accessToken['refresh_token'],
          'grant_type' => 'refresh_token'
      )));
      
      if ((int)$refreshRequest->getResponseHttpCode() == 200) {
        $token = json_decode($refreshRequest->getResponseBody(), true);
        if ($token == null) {
          throw new apiAuthException("Could not json decode the access token");
        }
        if (! isset($token['access_token']) || ! isset($token['expires_in'])) {
          throw new apiAuthException("Invalid token format");
        }
        $this->accessToken['access_token'] = $token['access_token'];
        $this->accessToken['expires_in'] = $token['expires_in'];
        $this->accessToken['created'] = time();
      } else {
        $response = $refreshRequest->getResponseBody();
        $decodedResponse = json_decode($response, true);
        if ($decodedResponse != $response && $decodedResponse != null && $decodedResponse['error']) {
          $response = $decodedResponse['error'];
        }
        throw new apiAuthException("Error refreshing the OAuth2 token, message: '$response'", $refreshRequest->getResponseHttpCode());
      }
    }

    // Add the OAuth2 header to the request
    $headers = $request->getHeaders();
    $headers[] = "Authorization: OAuth " . $this->accessToken['access_token'];
    $request->setHeaders($headers);

    return $request;
  }
Example #20
0
 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 apiHttpRequest('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(apiCacheParser::mustRevalidate($resp));
     // Contains the max-age=3600 directive, but was created 2 hours ago.
     // Must revalidate.
     $past = $now - 2 * 60 * 60;
     $resp = new apiHttpRequest('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(apiCacheParser::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 apiHttpRequest('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(apiCacheParser::mustRevalidate($resp));
 }
Example #21
0
 /**
  * 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;
 }
 /**
  * @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);
 }