[ Index ] |
PHP Cross Reference of moodle-2.8 |
[Summary view] [Print] [Text view]
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 require_once 'Google/Auth/AssertionCredentials.php'; 19 require_once 'Google/Cache/File.php'; 20 require_once 'Google/Cache/Memcache.php'; 21 require_once 'Google/Config.php'; 22 require_once 'Google/Collection.php'; 23 require_once 'Google/Exception.php'; 24 require_once 'Google/IO/Curl.php'; 25 require_once 'Google/IO/Stream.php'; 26 require_once 'Google/Model.php'; 27 require_once 'Google/Service.php'; 28 require_once 'Google/Service/Resource.php'; 29 30 /** 31 * The Google API Client 32 * http://code.google.com/p/google-api-php-client/ 33 * 34 * @author Chris Chabot <[email protected]> 35 * @author Chirag Shah <[email protected]> 36 */ 37 class Google_Client 38 { 39 const LIBVER = "1.0.5-beta"; 40 const USER_AGENT_SUFFIX = "google-api-php-client/"; 41 /** 42 * @var Google_Auth_Abstract $auth 43 */ 44 private $auth; 45 46 /** 47 * @var Google_IO_Abstract $io 48 */ 49 private $io; 50 51 /** 52 * @var Google_Cache_Abstract $cache 53 */ 54 private $cache; 55 56 /** 57 * @var Google_Config $config 58 */ 59 private $config; 60 61 /** 62 * @var boolean $deferExecution 63 */ 64 private $deferExecution = false; 65 66 /** @var array $scopes */ 67 // Scopes requested by the client 68 protected $requestedScopes = array(); 69 70 // definitions of services that are discovered. 71 protected $services = array(); 72 73 // Used to track authenticated state, can't discover services after doing authenticate() 74 private $authenticated = false; 75 76 /** 77 * Construct the Google Client. 78 * 79 * @param $config Google_Config or string for the ini file to load 80 */ 81 public function __construct($config = null) 82 { 83 if (is_string($config) && strlen($config)) { 84 $config = new Google_Config($config); 85 } else if ( !($config instanceof Google_Config)) { 86 $config = new Google_Config(); 87 88 if ($this->isAppEngine()) { 89 // Automatically use Memcache if we're in AppEngine. 90 $config->setCacheClass('Google_Cache_Memcache'); 91 } 92 93 if (version_compare(phpversion(), "5.3.4", "<=") || $this->isAppEngine()) { 94 // Automatically disable compress.zlib, as currently unsupported. 95 $config->setClassConfig('Google_Http_Request', 'disable_gzip', true); 96 } 97 } 98 99 if ($config->getIoClass() == Google_Config::USE_AUTO_IO_SELECTION) { 100 if (function_exists('curl_version') && function_exists('curl_exec')) { 101 $config->setIoClass("Google_IO_Curl"); 102 } else { 103 $config->setIoClass("Google_IO_Stream"); 104 } 105 } 106 107 $this->config = $config; 108 } 109 110 /** 111 * Get a string containing the version of the library. 112 * 113 * @return string 114 */ 115 public function getLibraryVersion() 116 { 117 return self::LIBVER; 118 } 119 120 /** 121 * Attempt to exchange a code for an valid authentication token. 122 * Helper wrapped around the OAuth 2.0 implementation. 123 * 124 * @param $code string code from accounts.google.com 125 * @return string token 126 */ 127 public function authenticate($code) 128 { 129 $this->authenticated = true; 130 return $this->getAuth()->authenticate($code); 131 } 132 133 /** 134 * Set the auth config from the JSON string provided. 135 * This structure should match the file downloaded from 136 * the "Download JSON" button on in the Google Developer 137 * Console. 138 * @param string $json the configuration json 139 */ 140 public function setAuthConfig($json) 141 { 142 $data = json_decode($json); 143 $key = isset($data->installed) ? 'installed' : 'web'; 144 if (!isset($data->$key)) { 145 throw new Google_Exception("Invalid client secret JSON file."); 146 } 147 $this->setClientId($data->$key->client_id); 148 $this->setClientSecret($data->$key->client_secret); 149 if (isset($data->$key->redirect_uris)) { 150 $this->setRedirectUri($data->$key->redirect_uris[0]); 151 } 152 } 153 154 /** 155 * Set the auth config from the JSON file in the path 156 * provided. This should match the file downloaded from 157 * the "Download JSON" button on in the Google Developer 158 * Console. 159 * @param string $file the file location of the client json 160 */ 161 public function setAuthConfigFile($file) 162 { 163 $this->setAuthConfig(file_get_contents($file)); 164 } 165 166 /** 167 * @return array 168 * @visible For Testing 169 */ 170 public function prepareScopes() 171 { 172 if (empty($this->requestedScopes)) { 173 throw new Google_Auth_Exception("No scopes specified"); 174 } 175 $scopes = implode(' ', $this->requestedScopes); 176 return $scopes; 177 } 178 179 /** 180 * Set the OAuth 2.0 access token using the string that resulted from calling createAuthUrl() 181 * or Google_Client#getAccessToken(). 182 * @param string $accessToken JSON encoded string containing in the following format: 183 * {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer", 184 * "expires_in":3600, "id_token":"TOKEN", "created":1320790426} 185 */ 186 public function setAccessToken($accessToken) 187 { 188 if ($accessToken == 'null') { 189 $accessToken = null; 190 } 191 $this->getAuth()->setAccessToken($accessToken); 192 } 193 194 195 196 /** 197 * Set the authenticator object 198 * @param Google_Auth_Abstract $auth 199 */ 200 public function setAuth(Google_Auth_Abstract $auth) 201 { 202 $this->config->setAuthClass(get_class($auth)); 203 $this->auth = $auth; 204 } 205 206 /** 207 * Set the IO object 208 * @param Google_Io_Abstract $auth 209 */ 210 public function setIo(Google_Io_Abstract $io) 211 { 212 $this->config->setIoClass(get_class($io)); 213 $this->io = $io; 214 } 215 216 /** 217 * Set the Cache object 218 * @param Google_Cache_Abstract $auth 219 */ 220 public function setCache(Google_Cache_Abstract $cache) 221 { 222 $this->config->setCacheClass(get_class($cache)); 223 $this->cache = $cache; 224 } 225 226 /** 227 * Construct the OAuth 2.0 authorization request URI. 228 * @return string 229 */ 230 public function createAuthUrl() 231 { 232 $scopes = $this->prepareScopes(); 233 return $this->getAuth()->createAuthUrl($scopes); 234 } 235 236 /** 237 * Get the OAuth 2.0 access token. 238 * @return string $accessToken JSON encoded string in the following format: 239 * {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer", 240 * "expires_in":3600,"id_token":"TOKEN", "created":1320790426} 241 */ 242 public function getAccessToken() 243 { 244 $token = $this->getAuth()->getAccessToken(); 245 // The response is json encoded, so could be the string null. 246 // It is arguable whether this check should be here or lower 247 // in the library. 248 return (null == $token || 'null' == $token || '[]' == $token) ? null : $token; 249 } 250 251 /** 252 * Returns if the access_token is expired. 253 * @return bool Returns True if the access_token is expired. 254 */ 255 public function isAccessTokenExpired() 256 { 257 return $this->getAuth()->isAccessTokenExpired(); 258 } 259 260 /** 261 * Set OAuth 2.0 "state" parameter to achieve per-request customization. 262 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-3.1.2.2 263 * @param string $state 264 */ 265 public function setState($state) 266 { 267 $this->getAuth()->setState($state); 268 } 269 270 /** 271 * @param string $accessType Possible values for access_type include: 272 * {@code "offline"} to request offline access from the user. 273 * {@code "online"} to request online access from the user. 274 */ 275 public function setAccessType($accessType) 276 { 277 $this->config->setAccessType($accessType); 278 } 279 280 /** 281 * @param string $approvalPrompt Possible values for approval_prompt include: 282 * {@code "force"} to force the approval UI to appear. (This is the default value) 283 * {@code "auto"} to request auto-approval when possible. 284 */ 285 public function setApprovalPrompt($approvalPrompt) 286 { 287 $this->config->setApprovalPrompt($approvalPrompt); 288 } 289 290 /** 291 * Set the login hint, email address or sub id. 292 * @param string $loginHint 293 */ 294 public function setLoginHint($loginHint) 295 { 296 $this->config->setLoginHint($loginHint); 297 } 298 299 /** 300 * Set the application name, this is included in the User-Agent HTTP header. 301 * @param string $applicationName 302 */ 303 public function setApplicationName($applicationName) 304 { 305 $this->config->setApplicationName($applicationName); 306 } 307 308 /** 309 * Set the OAuth 2.0 Client ID. 310 * @param string $clientId 311 */ 312 public function setClientId($clientId) 313 { 314 $this->config->setClientId($clientId); 315 } 316 317 /** 318 * Set the OAuth 2.0 Client Secret. 319 * @param string $clientSecret 320 */ 321 public function setClientSecret($clientSecret) 322 { 323 $this->config->setClientSecret($clientSecret); 324 } 325 326 /** 327 * Set the OAuth 2.0 Redirect URI. 328 * @param string $redirectUri 329 */ 330 public function setRedirectUri($redirectUri) 331 { 332 $this->config->setRedirectUri($redirectUri); 333 } 334 335 /** 336 * If 'plus.login' is included in the list of requested scopes, you can use 337 * this method to define types of app activities that your app will write. 338 * You can find a list of available types here: 339 * @link https://developers.google.com/+/api/moment-types 340 * 341 * @param array $requestVisibleActions Array of app activity types 342 */ 343 public function setRequestVisibleActions($requestVisibleActions) 344 { 345 if (is_array($requestVisibleActions)) { 346 $requestVisibleActions = join(" ", $requestVisibleActions); 347 } 348 $this->config->setRequestVisibleActions($requestVisibleActions); 349 } 350 351 /** 352 * Set the developer key to use, these are obtained through the API Console. 353 * @see http://code.google.com/apis/console-help/#generatingdevkeys 354 * @param string $developerKey 355 */ 356 public function setDeveloperKey($developerKey) 357 { 358 $this->config->setDeveloperKey($developerKey); 359 } 360 361 /** 362 * Fetches a fresh OAuth 2.0 access token with the given refresh token. 363 * @param string $refreshToken 364 * @return void 365 */ 366 public function refreshToken($refreshToken) 367 { 368 return $this->getAuth()->refreshToken($refreshToken); 369 } 370 371 /** 372 * Revoke an OAuth2 access token or refresh token. This method will revoke the current access 373 * token, if a token isn't provided. 374 * @throws Google_Auth_Exception 375 * @param string|null $token The token (access token or a refresh token) that should be revoked. 376 * @return boolean Returns True if the revocation was successful, otherwise False. 377 */ 378 public function revokeToken($token = null) 379 { 380 return $this->getAuth()->revokeToken($token); 381 } 382 383 /** 384 * Verify an id_token. This method will verify the current id_token, if one 385 * isn't provided. 386 * @throws Google_Auth_Exception 387 * @param string|null $token The token (id_token) that should be verified. 388 * @return Google_Auth_LoginTicket Returns an apiLoginTicket if the verification was 389 * successful. 390 */ 391 public function verifyIdToken($token = null) 392 { 393 return $this->getAuth()->verifyIdToken($token); 394 } 395 396 /** 397 * Verify a JWT that was signed with your own certificates. 398 * 399 * @param $jwt the token 400 * @param $certs array of certificates 401 * @param $required_audience the expected consumer of the token 402 * @param [$issuer] the expected issues, defaults to Google 403 * @param [$max_expiry] the max lifetime of a token, defaults to MAX_TOKEN_LIFETIME_SECS 404 * @return token information if valid, false if not 405 */ 406 public function verifySignedJwt($id_token, $cert_location, $audience, $issuer, $max_expiry = null) 407 { 408 $auth = new Google_Auth_OAuth2($this); 409 $certs = $auth->retrieveCertsFromLocation($cert_location); 410 return $auth->verifySignedJwtWithCerts($id_token, $certs, $audience, $issuer, $max_expiry); 411 } 412 413 /** 414 * @param Google_Auth_AssertionCredentials $creds 415 * @return void 416 */ 417 public function setAssertionCredentials(Google_Auth_AssertionCredentials $creds) 418 { 419 $this->getAuth()->setAssertionCredentials($creds); 420 } 421 422 /** 423 * Set the scopes to be requested. Must be called before createAuthUrl(). 424 * Will remove any previously configured scopes. 425 * @param array $scopes, ie: array('https://www.googleapis.com/auth/plus.login', 426 * 'https://www.googleapis.com/auth/moderator') 427 */ 428 public function setScopes($scopes) 429 { 430 $this->requestedScopes = array(); 431 $this->addScope($scopes); 432 } 433 434 /** 435 * This functions adds a scope to be requested as part of the OAuth2.0 flow. 436 * Will append any scopes not previously requested to the scope parameter. 437 * A single string will be treated as a scope to request. An array of strings 438 * will each be appended. 439 * @param $scope_or_scopes string|array e.g. "profile" 440 */ 441 public function addScope($scope_or_scopes) 442 { 443 if (is_string($scope_or_scopes) && !in_array($scope_or_scopes, $this->requestedScopes)) { 444 $this->requestedScopes[] = $scope_or_scopes; 445 } else if (is_array($scope_or_scopes)) { 446 foreach ($scope_or_scopes as $scope) { 447 $this->addScope($scope); 448 } 449 } 450 } 451 452 /** 453 * Returns the list of scopes requested by the client 454 * @return array the list of scopes 455 * 456 */ 457 public function getScopes() 458 { 459 return $this->requestedScopes; 460 } 461 462 /** 463 * Declare whether batch calls should be used. This may increase throughput 464 * by making multiple requests in one connection. 465 * 466 * @param boolean $useBatch True if the batch support should 467 * be enabled. Defaults to False. 468 */ 469 public function setUseBatch($useBatch) 470 { 471 // This is actually an alias for setDefer. 472 $this->setDefer($useBatch); 473 } 474 475 /** 476 * Declare whether making API calls should make the call immediately, or 477 * return a request which can be called with ->execute(); 478 * 479 * @param boolean $defer True if calls should not be executed right away. 480 */ 481 public function setDefer($defer) 482 { 483 $this->deferExecution = $defer; 484 } 485 486 /** 487 * Helper method to execute deferred HTTP requests. 488 * 489 * @returns object of the type of the expected class or array. 490 */ 491 public function execute($request) 492 { 493 if ($request instanceof Google_Http_Request) { 494 $request->setUserAgent( 495 $this->getApplicationName() 496 . " " . self::USER_AGENT_SUFFIX 497 . $this->getLibraryVersion() 498 ); 499 if (!$this->getClassConfig("Google_Http_Request", "disable_gzip")) { 500 $request->enableGzip(); 501 } 502 $request->maybeMoveParametersToBody(); 503 return Google_Http_REST::execute($this, $request); 504 } else if ($request instanceof Google_Http_Batch) { 505 return $request->execute(); 506 } else { 507 throw new Google_Exception("Do not know how to execute this type of object."); 508 } 509 } 510 511 /** 512 * Whether or not to return raw requests 513 * @return boolean 514 */ 515 public function shouldDefer() 516 { 517 return $this->deferExecution; 518 } 519 520 /** 521 * @return Google_Auth_Abstract Authentication implementation 522 */ 523 public function getAuth() 524 { 525 if (!isset($this->auth)) { 526 $class = $this->config->getAuthClass(); 527 $this->auth = new $class($this); 528 } 529 return $this->auth; 530 } 531 532 /** 533 * @return Google_IO_Abstract IO implementation 534 */ 535 public function getIo() 536 { 537 if (!isset($this->io)) { 538 $class = $this->config->getIoClass(); 539 $this->io = new $class($this); 540 } 541 return $this->io; 542 } 543 544 /** 545 * @return Google_Cache_Abstract Cache implementation 546 */ 547 public function getCache() 548 { 549 if (!isset($this->cache)) { 550 $class = $this->config->getCacheClass(); 551 $this->cache = new $class($this); 552 } 553 return $this->cache; 554 } 555 556 /** 557 * Retrieve custom configuration for a specific class. 558 * @param $class string|object - class or instance of class to retrieve 559 * @param $key string optional - key to retrieve 560 */ 561 public function getClassConfig($class, $key = null) 562 { 563 if (!is_string($class)) { 564 $class = get_class($class); 565 } 566 return $this->config->getClassConfig($class, $key); 567 } 568 569 /** 570 * Set configuration specific to a given class. 571 * $config->setClassConfig('Google_Cache_File', 572 * array('directory' => '/tmp/cache')); 573 * @param $class The class name for the configuration 574 * @param $config string key or an array of configuration values 575 * @param $value optional - if $config is a key, the value 576 * 577 */ 578 public function setClassConfig($class, $config, $value = null) 579 { 580 if (!is_string($class)) { 581 $class = get_class($class); 582 } 583 return $this->config->setClassConfig($class, $config, $value); 584 585 } 586 587 /** 588 * @return string the base URL to use for calls to the APIs 589 */ 590 public function getBasePath() 591 { 592 return $this->config->getBasePath(); 593 } 594 595 /** 596 * @return string the name of the application 597 */ 598 public function getApplicationName() 599 { 600 return $this->config->getApplicationName(); 601 } 602 603 /** 604 * Are we running in Google AppEngine? 605 * return bool 606 */ 607 public function isAppEngine() 608 { 609 return (isset($_SERVER['SERVER_SOFTWARE']) && 610 strpos($_SERVER['SERVER_SOFTWARE'], 'Google App Engine') !== false); 611 } 612 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated: Fri Nov 28 20:29:05 2014 | Cross-referenced by PHPXref 0.7.1 |