Google_Client

The Google API Client http://code.google.com/p/google-api-php-client/.

Defined (1)

The class is defined in the following location(s).

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