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