PluginProbe
InfiniteWP Client / trunk
InfiniteWP Client vtrunk
1.13.10 1.13.7 trunk 0.1.4 0.1.5 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.1.0 1.1.1 1.1.10 1.1.2 1.1.3 1.1.4 1.1.5 1.1.6 1.1.7 1.1.8 1.1.9 1.11.0 1.11.1 1.12.1 1.12.3 All 92 releases
iwp-client / lib / Google / Client.php

Client.php in InfiniteWP Client trunk, at lib/Google/Client.php

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