/google_api/Client.php

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