1<?php
2/*
3 * Copyright 2010 Google Inc.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18/**
19 * This class implements the RESTful transport of apiServiceRequest()'s
20 *
21 * @author Chris Chabot <chabotc@google.com>
22 * @author Chirag Shah <chirags@google.com>
23 */
24class Google_REST {
25  /**
26   * Executes a apiServiceRequest using a RESTful call by transforming it into
27   * an apiHttpRequest, and executed via apiIO::authenticatedRequest().
28   *
29   * @param Google_HttpRequest $req
30   * @return array decoded result
31   * @throws Google_ServiceException on server side error (ie: not authenticated,
32   *  invalid or malformed post body, invalid url)
33   */
34  static public function execute(Google_HttpRequest $req) {
35    $httpRequest = Google_Client::$io->makeRequest($req);
36    $decodedResponse = self::decodeHttpResponse($httpRequest);
37    $ret = isset($decodedResponse['data'])
38        ? $decodedResponse['data'] : $decodedResponse;
39    return $ret;
40  }
41
42
43  /**
44   * Decode an HTTP Response.
45   * @static
46   * @throws Google_ServiceException
47   * @param Google_HttpRequest $response The http response to be decoded.
48   * @return mixed|null
49   */
50  public static function decodeHttpResponse($response) {
51    $code = $response->getResponseHttpCode();
52    $body = $response->getResponseBody();
53    $decoded = null;
54
55    if ((intVal($code)) >= 300) {
56      $decoded = json_decode($body, true);
57      $err = 'Error calling ' . $response->getRequestMethod() . ' ' . $response->getUrl();
58      if ($decoded != null && isset($decoded['error']['message'])  && isset($decoded['error']['code'])) {
59        // if we're getting a json encoded error definition, use that instead of the raw response
60        // body for improved readability
61        $err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}";
62      } else {
63        $err .= ": ($code) $body";
64      }
65
66      throw new Google_ServiceException($err, $code, null, $decoded['error']['errors']);
67    }
68
69    // Only attempt to decode the response, if the response code wasn't (204) 'no content'
70    if ($code != '204') {
71      $decoded = json_decode($body, true);
72      if ($decoded === null || $decoded === "") {
73        throw new Google_ServiceException("Invalid json in service response: $body");
74      }
75    }
76    return $decoded;
77  }
78
79  /**
80   * Parse/expand request parameters and create a fully qualified
81   * request uri.
82   * @static
83   * @param string $servicePath
84   * @param string $restPath
85   * @param array $params
86   * @return string $requestUrl
87   */
88  static function createRequestUri($servicePath, $restPath, $params) {
89    $requestUrl = $servicePath . $restPath;
90    $uriTemplateVars = array();
91    $queryVars = array();
92    foreach ($params as $paramName => $paramSpec) {
93      // Discovery v1.0 puts the canonical location under the 'location' field.
94      if (! isset($paramSpec['location'])) {
95        $paramSpec['location'] = $paramSpec['restParameterType'];
96      }
97
98      if ($paramSpec['type'] == 'boolean') {
99        $paramSpec['value'] = ($paramSpec['value']) ? 'true' : 'false';
100      }
101      if ($paramSpec['location'] == 'path') {
102        $uriTemplateVars[$paramName] = $paramSpec['value'];
103      } else {
104        if (isset($paramSpec['repeated']) && is_array($paramSpec['value'])) {
105          foreach ($paramSpec['value'] as $value) {
106            $queryVars[] = $paramName . '=' . rawurlencode($value);
107          }
108        } else {
109          $queryVars[] = $paramName . '=' . rawurlencode($paramSpec['value']);
110        }
111      }
112    }
113
114    if (count($uriTemplateVars)) {
115      $uriTemplateParser = new URI_Template_Parser($requestUrl);
116      $requestUrl = $uriTemplateParser->expand($uriTemplateVars);
117    }
118    //FIXME work around for the the uri template lib which url encodes
119    // the @'s & confuses our servers.
120    $requestUrl = str_replace('%40', '@', $requestUrl);
121
122    if (count($queryVars)) {
123      $requestUrl .= '?' . implode($queryVars, '&');
124    }
125
126    return $requestUrl;
127  }
128}
129