Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

Differences Between: [Versions 310 and 402] [Versions 311 and 402] [Versions 39 and 402] [Versions 400 and 402] [Versions 401 and 402]

   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  if (!class_exists('Google_Client')) {
  19    require_once dirname(__FILE__) . '/../autoload.php';
  20  }
  21  
  22  /**
  23   * This class implements the RESTful transport of apiServiceRequest()'s
  24   */
  25  #[AllowDynamicProperties]
  26  class Google_Http_REST
  27  {
  28    /**
  29     * Executes a Google_Http_Request and (if applicable) automatically retries
  30     * when errors occur.
  31     *
  32     * @param Google_Client $client
  33     * @param Google_Http_Request $req
  34     * @return array decoded result
  35     * @throws Google_Service_Exception on server side error (ie: not authenticated,
  36     *  invalid or malformed post body, invalid url)
  37     */
  38    public static function execute(Google_Client $client, Google_Http_Request $req)
  39    {
  40      $runner = new Google_Task_Runner(
  41          $client,
  42          sprintf('%s %s', $req->getRequestMethod(), $req->getUrl()),
  43          array(self::class, 'doExecute'),
  44          array($client, $req)
  45      );
  46  
  47      return $runner->run();
  48    }
  49  
  50    /**
  51     * Executes a Google_Http_Request
  52     *
  53     * @param Google_Client $client
  54     * @param Google_Http_Request $req
  55     * @return array decoded result
  56     * @throws Google_Service_Exception on server side error (ie: not authenticated,
  57     *  invalid or malformed post body, invalid url)
  58     */
  59    public static function doExecute(Google_Client $client, Google_Http_Request $req)
  60    {
  61      $httpRequest = $client->getIo()->makeRequest($req);
  62      $httpRequest->setExpectedClass($req->getExpectedClass());
  63      return self::decodeHttpResponse($httpRequest, $client);
  64    }
  65  
  66    /**
  67     * Decode an HTTP Response.
  68     * @static
  69     * @throws Google_Service_Exception
  70     * @param Google_Http_Request $response The http response to be decoded.
  71     * @param Google_Client $client
  72     * @return mixed|null
  73     */
  74    public static function decodeHttpResponse($response, Google_Client $client = null)
  75    {
  76      $code = $response->getResponseHttpCode();
  77      $body = $response->getResponseBody();
  78      $decoded = null;
  79  
  80      if ((intVal($code)) >= 300) {
  81        $decoded = json_decode($body, true);
  82        $err = 'Error calling ' . $response->getRequestMethod() . ' ' . $response->getUrl();
  83        if (isset($decoded['error']) &&
  84            isset($decoded['error']['message'])  &&
  85            isset($decoded['error']['code'])) {
  86          // if we're getting a json encoded error definition, use that instead of the raw response
  87          // body for improved readability
  88          $err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}";
  89        } else {
  90          $err .= ": ($code) $body";
  91        }
  92  
  93        $errors = null;
  94        // Specific check for APIs which don't return error details, such as Blogger.
  95        if (isset($decoded['error']) && isset($decoded['error']['errors'])) {
  96          $errors = $decoded['error']['errors'];
  97        }
  98  
  99        $map = null;
 100        if ($client) {
 101          $client->getLogger()->error(
 102              $err,
 103              array('code' => $code, 'errors' => $errors)
 104          );
 105  
 106          $map = $client->getClassConfig(
 107              'Google_Service_Exception',
 108              'retry_map'
 109          );
 110        }
 111        throw new Google_Service_Exception($err, $code, null, $errors, $map);
 112      }
 113  
 114      // Only attempt to decode the response, if the response code wasn't (204) 'no content'
 115      if ($code != '204') {
 116        if ($response->getExpectedRaw()) {
 117          return $body;
 118        }
 119        
 120        $decoded = json_decode($body, true);
 121        if ($decoded === null || $decoded === "") {
 122          $error = "Invalid json in service response: $body";
 123          if ($client) {
 124            $client->getLogger()->error($error);
 125          }
 126          throw new Google_Service_Exception($error);
 127        }
 128  
 129        if ($response->getExpectedClass()) {
 130          $class = $response->getExpectedClass();
 131          $decoded = new $class($decoded);
 132        }
 133      }
 134      return $decoded;
 135    }
 136  
 137    /**
 138     * Parse/expand request parameters and create a fully qualified
 139     * request uri.
 140     * @static
 141     * @param string $servicePath
 142     * @param string $restPath
 143     * @param array $params
 144     * @return string $requestUrl
 145     */
 146    public static function createRequestUri($servicePath, $restPath, $params)
 147    {
 148      $requestUrl = $servicePath . $restPath;
 149      $uriTemplateVars = array();
 150      $queryVars = array();
 151      foreach ($params as $paramName => $paramSpec) {
 152        if ($paramSpec['type'] == 'boolean') {
 153          $paramSpec['value'] = ($paramSpec['value']) ? 'true' : 'false';
 154        }
 155        if ($paramSpec['location'] == 'path') {
 156          $uriTemplateVars[$paramName] = $paramSpec['value'];
 157        } else if ($paramSpec['location'] == 'query') {
 158          if (isset($paramSpec['repeated']) && is_array($paramSpec['value'])) {
 159            foreach ($paramSpec['value'] as $value) {
 160              $queryVars[] = $paramName . '=' . rawurlencode(rawurldecode($value));
 161            }
 162          } else {
 163            $queryVars[] = $paramName . '=' . rawurlencode(rawurldecode($paramSpec['value']));
 164          }
 165        }
 166      }
 167  
 168      if (count($uriTemplateVars)) {
 169        $uriTemplateParser = new Google_Utils_URITemplate();
 170        $requestUrl = $uriTemplateParser->parse($requestUrl, $uriTemplateVars);
 171      }
 172  
 173      if (count($queryVars)) {
 174        $requestUrl .= '?' . implode('&', $queryVars);
 175      }
 176  
 177      return $requestUrl;
 178    }
 179  }