/google-api-php-client/api-code/Google_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. // Check for the json extension, the Google APIs PHP Client won't function 
  19. // without it. 
  20. if (! function_exists('json_decode')) { 
  21. throw new Exception('Google PHP API Client requires the JSON PHP extension'); 
  22.  
  23. if (! function_exists('http_build_query')) { 
  24. throw new Exception('Google PHP API Client requires http_build_query()'); 
  25.  
  26. if (! ini_get('date.timezone') && function_exists('date_default_timezone_set')) { 
  27. date_default_timezone_set('UTC'); 
  28.  
  29. // hack around with the include paths a bit so the library 'just works' 
  30. set_include_path(dirname(__FILE__) . PATH_SEPARATOR . get_include_path()); 
  31.  
  32. require_once "config.php"; 
  33. // If a local configuration file is found, merge it's values with the default configuration 
  34. if (file_exists(dirname(__FILE__) . '/local_config.php')) { 
  35. $defaultConfig = $apiConfig; 
  36. require_once (dirname(__FILE__) . '/local_config.php'); 
  37. $apiConfig = array_merge($defaultConfig, $apiConfig); 
  38.  
  39. // Include the top level classes, they each include their own dependencies 
  40. require_once 'service/Google_Model.php'; 
  41. require_once 'service/Google_Service.php'; 
  42. require_once 'service/Google_ServiceResource.php'; 
  43. require_once 'auth/Google_AssertionCredentials.php'; 
  44. require_once 'auth/Google_Signer.php'; 
  45. require_once 'auth/Google_P12Signer.php'; 
  46. require_once 'service/Google_BatchRequest.php'; 
  47. require_once 'external/URITemplateParser.php'; 
  48. require_once 'auth/Google_Auth.php'; 
  49. require_once 'cache/Google_Cache.php'; 
  50. require_once 'io/Google_IO.php'; 
  51. require_once('service/Google_MediaFileUpload.php'); 
  52.  
  53. /** 
  54. * The Google API Client 
  55. * http://code.google.com/p/google-api-php-client/ 
  56. * 
  57. * @author Chris Chabot <chabotc@google.com> 
  58. * @author Chirag Shah <chirags@google.com> 
  59. */ 
  60. if ( ! class_exists( 'Google_Client' ) ) { 
  61. class Google_Client { 
  62. /** 
  63. * @static 
  64. * @var Google_Auth $auth 
  65. */ 
  66. static $auth; 
  67.  
  68. /** 
  69. * @static 
  70. * @var Google_IO $io 
  71. */ 
  72. static $io; 
  73.  
  74. /** 
  75. * @static 
  76. * @var Google_Cache $cache 
  77. */ 
  78. static $cache; 
  79.  
  80. /** 
  81. * @static 
  82. * @var boolean $useBatch 
  83. */ 
  84. static $useBatch = false; 
  85.  
  86. /** @var array $scopes */ 
  87. protected $scopes = array(); 
  88.  
  89. /** @var bool $useObjects */ 
  90. protected $useObjects = false; 
  91.  
  92. // definitions of services that are discovered. 
  93. protected $services = array(); 
  94.  
  95. // Used to track authenticated state, can't discover services after doing authenticate() 
  96. private $authenticated = false; 
  97.  
  98. public function __construct($config = array()) { 
  99. global $apiConfig; 
  100. $apiConfig = array_merge($apiConfig, $config); 
  101. self::$cache = new $apiConfig['cacheClass'](); 
  102. self::$auth = new $apiConfig['authClass'](); 
  103. self::$io = new $apiConfig['ioClass'](); 
  104.  
  105. /** 
  106. * Add a service 
  107. */ 
  108. public function addService($service, $version = false) { 
  109. global $apiConfig; 
  110. if ($this->authenticated) { 
  111. throw new Google_Exception('Cant add services after having authenticated'); 
  112. $this->services[$service] = array(); 
  113. if (isset($apiConfig['services'][$service])) { 
  114. // Merge the service descriptor with the default values 
  115. $this->services[$service] = array_merge($this->services[$service], $apiConfig['services'][$service]); 
  116.  
  117. public function authenticate($code = null) { 
  118. $service = $this->prepareService(); 
  119. $this->authenticated = true; 
  120. return self::$auth->authenticate($service, $code); 
  121.  
  122. /** 
  123. * @return array 
  124. * @visible For Testing 
  125. */ 
  126. public function prepareService() { 
  127. $service = array(); 
  128. $scopes = array(); 
  129. if ($this->scopes) { 
  130. $scopes = $this->scopes; 
  131. } else { 
  132. foreach ($this->services as $key => $val) { 
  133. if (isset($val['scope'])) { 
  134. if (is_array($val['scope'])) { 
  135. $scopes = array_merge($val['scope'], $scopes); 
  136. } else { 
  137. $scopes[] = $val['scope']; 
  138. } else { 
  139. $scopes[] = 'https://www.googleapis.com/auth/' . $key; 
  140. unset($val['discoveryURI']); 
  141. unset($val['scope']); 
  142. $service = array_merge($service, $val); 
  143. $service['scope'] = implode(' ', $scopes); 
  144. return $service; 
  145.  
  146. /** 
  147. * Set the OAuth 2.0 access token using the string that resulted from calling authenticate() 
  148. * or Google_Client#getAccessToken(). 
  149. * @param string $accessToken JSON encoded string containing in the following format: 
  150. * {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",  
  151. * "expires_in":3600, "id_token":"TOKEN", "created":1320790426} 
  152. */ 
  153. public function setAccessToken($accessToken) { 
  154. if ($accessToken == null || 'null' == $accessToken) { 
  155. $accessToken = null; 
  156. self::$auth->setAccessToken($accessToken); 
  157.  
  158. /** 
  159. * Set the type of Auth class the client should use. 
  160. * @param string $authClassName 
  161. */ 
  162. public function setAuthClass($authClassName) { 
  163. self::$auth = new $authClassName(); 
  164.  
  165. /** 
  166. * Construct the OAuth 2.0 authorization request URI. 
  167. * @return string 
  168. */ 
  169. public function createAuthUrl() { 
  170. $service = $this->prepareService(); 
  171. return self::$auth->createAuthUrl($service['scope']); 
  172.  
  173. /** 
  174. * Get the OAuth 2.0 access token. 
  175. * @return string $accessToken JSON encoded string in the following format: 
  176. * {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",  
  177. * "expires_in":3600, "id_token":"TOKEN", "created":1320790426} 
  178. */ 
  179. public function getAccessToken() { 
  180. $token = self::$auth->getAccessToken(); 
  181. return (null == $token || 'null' == $token) ? null : $token; 
  182.  
  183. /** 
  184. * Returns if the access_token is expired. 
  185. * @return bool Returns True if the access_token is expired. 
  186. */ 
  187. public function isAccessTokenExpired() { 
  188. return self::$auth->isAccessTokenExpired(); 
  189.  
  190. /** 
  191. * Set the developer key to use, these are obtained through the API Console. 
  192. * @see http://code.google.com/apis/console-help/#generatingdevkeys 
  193. * @param string $developerKey 
  194. */ 
  195. public function setDeveloperKey($developerKey) { 
  196. self::$auth->setDeveloperKey($developerKey); 
  197.  
  198. /** 
  199. * Set OAuth 2.0 "state" parameter to achieve per-request customization. 
  200. * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-3.1.2.2 
  201. * @param string $state 
  202. */ 
  203. public function setState($state) { 
  204. self::$auth->setState($state); 
  205.  
  206. /** 
  207. * @param string $accessType Possible values for access_type include: 
  208. * {@code "offline"} to request offline access from the user. (This is the default value) 
  209. * {@code "online"} to request online access from the user. 
  210. */ 
  211. public function setAccessType($accessType) { 
  212. self::$auth->setAccessType($accessType); 
  213.  
  214. /** 
  215. * @param string $approvalPrompt Possible values for approval_prompt include: 
  216. * {@code "force"} to force the approval UI to appear. (This is the default value) 
  217. * {@code "auto"} to request auto-approval when possible. 
  218. */ 
  219. public function setApprovalPrompt($approvalPrompt) { 
  220. self::$auth->setApprovalPrompt($approvalPrompt); 
  221.  
  222. /** 
  223. * Set the application name, this is included in the User-Agent HTTP header. 
  224. * @param string $applicationName 
  225. */ 
  226. public function setApplicationName($applicationName) { 
  227. global $apiConfig; 
  228. $apiConfig['application_name'] = $applicationName; 
  229.  
  230. /** 
  231. * Set the OAuth 2.0 Client ID. 
  232. * @param string $clientId 
  233. */ 
  234. public function setClientId($clientId) { 
  235. global $apiConfig; 
  236. $apiConfig['oauth2_client_id'] = $clientId; 
  237. self::$auth->clientId = $clientId; 
  238.  
  239. /** 
  240. * Get the OAuth 2.0 Client ID. 
  241. */ 
  242. public function getClientId() { 
  243. return self::$auth->clientId; 
  244.  
  245. /** 
  246. * Set the OAuth 2.0 Client Secret. 
  247. * @param string $clientSecret 
  248. */ 
  249. public function setClientSecret($clientSecret) { 
  250. global $apiConfig; 
  251. $apiConfig['oauth2_client_secret'] = $clientSecret; 
  252. self::$auth->clientSecret = $clientSecret; 
  253.  
  254. /** 
  255. * Get the OAuth 2.0 Client Secret. 
  256. */ 
  257. public function getClientSecret() { 
  258. return self::$auth->clientSecret; 
  259.  
  260. /** 
  261. * Set the OAuth 2.0 Redirect URI. 
  262. * @param string $redirectUri 
  263. */ 
  264. public function setRedirectUri($redirectUri) { 
  265. global $apiConfig; 
  266. $apiConfig['oauth2_redirect_uri'] = $redirectUri; 
  267. self::$auth->redirectUri = $redirectUri; 
  268.  
  269. /** 
  270. * Get the OAuth 2.0 Redirect URI. 
  271. */ 
  272. public function getRedirectUri() { 
  273. return self::$auth->redirectUri; 
  274.  
  275. /** 
  276. * Fetches a fresh OAuth 2.0 access token with the given refresh token. 
  277. * @param string $refreshToken 
  278. * @return void 
  279. */ 
  280. public function refreshToken($refreshToken) { 
  281. self::$auth->refreshToken($refreshToken); 
  282.  
  283. /** 
  284. * Revoke an OAuth2 access token or refresh token. This method will revoke the current access 
  285. * token, if a token isn't provided. 
  286. * @throws Google_AuthException 
  287. * @param string|null $token The token (access token or a refresh token) that should be revoked. 
  288. * @return boolean Returns True if the revocation was successful, otherwise False. 
  289. */ 
  290. public function revokeToken($token = null) { 
  291. self::$auth->revokeToken($token); 
  292.  
  293. /** 
  294. * Verify an id_token. This method will verify the current id_token, if one 
  295. * isn't provided. 
  296. * @throws Google_AuthException 
  297. * @param string|null $token The token (id_token) that should be verified. 
  298. * @return Google_LoginTicket Returns an apiLoginTicket if the verification was 
  299. * successful. 
  300. */ 
  301. public function verifyIdToken($token = null) { 
  302. return self::$auth->verifyIdToken($token); 
  303.  
  304. /** 
  305. * @param Google_AssertionCredentials $creds 
  306. * @return void 
  307. */ 
  308. public function setAssertionCredentials(Google_AssertionCredentials $creds) { 
  309. self::$auth->setAssertionCredentials($creds); 
  310.  
  311. /** 
  312. * This function allows you to overrule the automatically generated scopes,  
  313. * so that you can ask for more or less permission in the auth flow 
  314. * Set this before you call authenticate() though! 
  315. * @param array $scopes, ie: array('https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/moderator') 
  316. */ 
  317. public function setScopes($scopes) { 
  318. $this->scopes = is_string($scopes) ? explode(" ", $scopes) : $scopes; 
  319.  
  320. /** 
  321. * Returns the list of scopes set on the client 
  322. * @return array the list of scopes 
  323. * 
  324. */ 
  325. public function getScopes() { 
  326. return $this->scopes; 
  327.  
  328. /** 
  329. * If 'plus.login' is included in the list of requested scopes, you can use 
  330. * this method to define types of app activities that your app will write. 
  331. * You can find a list of available types here: 
  332. * @link https://developers.google.com/+/api/moment-types 
  333. * 
  334. * @param array $requestVisibleActions Array of app activity types 
  335. */ 
  336. public function setRequestVisibleActions($requestVisibleActions) { 
  337. self::$auth->requestVisibleActions = 
  338. join(" ", $requestVisibleActions); 
  339.  
  340. /** 
  341. * Declare if objects should be returned by the api service classes. 
  342. * 
  343. * @param boolean $useObjects True if objects should be returned by the service classes. 
  344. * False if associative arrays should be returned (default behavior). 
  345. * @experimental 
  346. */ 
  347. public function setUseObjects($useObjects) { 
  348. global $apiConfig; 
  349. $apiConfig['use_objects'] = $useObjects; 
  350.  
  351. /** 
  352. * Declare if objects should be returned by the api service classes. 
  353. * 
  354. * @param boolean $useBatch True if the experimental batch support should 
  355. * be enabled. Defaults to False. 
  356. * @experimental 
  357. */ 
  358. public function setUseBatch($useBatch) { 
  359. self::$useBatch = $useBatch; 
  360.  
  361. /** 
  362. * @static 
  363. * @return Google_Auth the implementation of apiAuth. 
  364. */ 
  365. public static function getAuth() { 
  366. return Google_Client::$auth; 
  367.  
  368. /** 
  369. * @static 
  370. * @return Google_IO the implementation of apiIo. 
  371. */ 
  372. public static function getIo() { 
  373. return Google_Client::$io; 
  374.  
  375. /** 
  376. * @return Google_Cache the implementation of apiCache. 
  377. */ 
  378. public function getCache() { 
  379. return Google_Client::$cache; 
  380.  
  381. // Exceptions that the Google PHP API Library can throw 
  382. if ( ! class_exists( 'Google_Exception' ) ) { 
  383. class Google_Exception extends Exception {} 
  384.  
  385. if ( ! class_exists( 'Google_AuthException' ) ) { 
  386. class Google_AuthException extends Google_Exception {} 
  387.  
  388. if ( ! class_exists( 'Google_CacheException' ) ) { 
  389. class Google_CacheException extends Google_Exception {} 
  390.  
  391. if ( ! class_exists( 'Google_IOException' ) ) { 
  392. class Google_IOException extends Google_Exception {} 
  393.  
  394. if ( ! class_exists( 'Google_ServiceException' ) ) { 
  395. class Google_ServiceException extends Google_Exception { 
  396. /** 
  397. * Optional list of errors returned in a JSON body of an HTTP error response. 
  398. */ 
  399. protected $errors = array(); 
  400.  
  401. /** 
  402. * Override default constructor to add ability to set $errors. 
  403. * 
  404. * @param string $message 
  405. * @param int $code 
  406. * @param Exception|null $previous 
  407. * @param [{string, string}] errors List of errors returned in an HTTP 
  408. * response. Defaults to []. 
  409. */ 
  410. public function __construct($message, $code = 0, Exception $previous = null,  
  411. $errors = array()) { 
  412. if(version_compare(PHP_VERSION, '5.3.0') >= 0) { 
  413. parent::__construct($message, $code, $previous); 
  414. } else { 
  415. parent::__construct($message, $code); 
  416.  
  417. $this->errors = $errors; 
  418.  
  419. /** 
  420. * An example of the possible errors returned. 
  421. * 
  422. * { 
  423. * "domain": "global",  
  424. * "reason": "authError",  
  425. * "message": "Invalid Credentials",  
  426. * "locationType": "header",  
  427. * "location": "Authorization",  
  428. * } 
  429. * 
  430. * @return [{string, string}] List of errors return in an HTTP response or []. 
  431. */ 
  432. public function getErrors() { 
  433. return $this->errors; 
.