Пример #1
0
 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->setHeaders(array('Content-Type: application/json'));
     $httpRequest->setMethod('POST');
     $httpRequest->setPostBody(json_encode($jsonRpcRequest));
     $httpRequest = $request->getIo()->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");
     }
 }
Пример #2
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 $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());
     //var_dump($url);
     $httpRequest = new apiHttpRequest($url, $req->getHttpMethod(), null, $postBody);
     // Add a content-type: application/json header so the server knows how to interpret the post body
     if ($postBody) {
         $contentTypeHeader = array('Content-Type: application/json; charset=UTF-8', 'Content-Length: ' . apiUtils::getStrLen($postBody));
         if ($httpRequest->getHeaders()) {
             $contentTypeHeader = array_merge($httpRequest->getHeaders(), $contentTypeHeader);
         }
         $httpRequest->setHeaders($contentTypeHeader);
     }
     // TODO : ajout didier pour passage adresse IP client
     //        $newHeader = array(
     //            //'X-Forwarded-For: ' . $_SERVER['SERVER_ADDR']
     //            'X-Forwarded-For: 88.176.177.141'
     //        );
     //        if ($httpRequest->getHeaders()) {
     //            $newHeader = array_merge($httpRequest->getHeaders(), $newHeader);
     //        }
     //        $httpRequest->setHeaders($newHeader);
     //
     //        var_dump($httpRequest);
     $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;
 }
Пример #3
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 $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);
     // Add a content-type: application/json header so the server knows how to interpret the post body
     if ($postBody) {
         $contentTypeHeader = array('Content-Type: application/json; charset=UTF-8', 'Content-Length: ' . apiUtils::getStrLen($postBody));
         if ($httpRequest->getHeaders()) {
             $contentTypeHeader = array_merge($httpRequest->getHeaders(), $contentTypeHeader);
         }
         $httpRequest->setHeaders($contentTypeHeader);
     }
     $httpRequest = $req->getIo()->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;
 }
Пример #4
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;
 }
Пример #5
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;
 }
Пример #6
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
     $headers = $request->getHeaders();
     $headers[] = "Authorization: Bearer " . $this->accessToken['access_token'];
     $request->setHeaders($headers);
     return $request;
 }
Пример #7
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;
  }