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).

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