PluginProbe
WP-Stateless – Google Cloud Storage / 2.2.0
WP-Stateless – Google Cloud Storage v2.2.0
4.4.3 2.1.7 2.1.8 2.1.9 2.2.0 2.2.1 2.2.2 2.2.3 2.2.4 2.2.5 2.2.6 2.2.7 2.3.0 2.3.1 2.3.2 3.0 3.0.1 3.0.2 3.0.3 3.0.4 3.1.0 3.1.1 3.2.0 3.2.1 3.2.2 All 62 releases
wp-stateless / lib / Google / src / Google / Client.php

Client.php in WP-Stateless – Google Cloud Storage 2.2.0, at lib/Google/src/Google/Client.php

1,130 lines 31.2 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 namespace wpCloud\StatelessMedia\Google_Client;
18
19 use Google\Auth\ApplicationDefaultCredentials;
20 use Google\Auth\Cache\MemoryCacheItemPool;
21 use Google\Auth\CredentialsLoader;
22 use Google\Auth\HttpHandler\HttpHandlerFactory;
23 use Google\Auth\OAuth2;
24 use Google\Auth\Credentials\ServiceAccountCredentials;
25 use Google\Auth\Credentials\UserRefreshCredentials;
26 use GuzzleHttp\Client;
27 use GuzzleHttp\ClientInterface;
28 use GuzzleHttp\Ring\Client\StreamHandler;
29 use Psr\Cache\CacheItemPoolInterface;
30 use Psr\Http\Message\RequestInterface;
31 use Psr\Log\LoggerInterface;
32 use Monolog\Logger;
33 use Monolog\Handler\StreamHandler as MonologStreamHandler;
34 use Monolog\Handler\SyslogHandler as MonologSyslogHandler;
35
36 /**
37 * The Google API Client
38 * https://github.com/google/google-api-php-client
39 */
40 class Google_Client
41 {
42 const LIBVER = "2.2.2";
43 const USER_AGENT_SUFFIX = "google-api-php-client/";
44 const OAUTH2_REVOKE_URI = 'https://accounts.google.com/o/oauth2/revoke';
45 const OAUTH2_TOKEN_URI = 'https://www.googleapis.com/oauth2/v4/token';
46 const OAUTH2_AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';
47 const API_BASE_PATH = 'https://www.googleapis.com';
48
49 /**
50 * @var Google\Auth\OAuth2 $auth
51 */
52 private $auth;
53
54 /**
55 * @var GuzzleHttp\ClientInterface $http
56 */
57 private $http;
58
59 /**
60 * @var Psr\Cache\CacheItemPoolInterface $cache
61 */
62 private $cache;
63
64 /**
65 * @var array access token
66 */
67 private $token;
68
69 /**
70 * @var array $config
71 */
72 private $config;
73
74 /**
75 * @var Psr\Log\LoggerInterface $logger
76 */
77 private $logger;
78
79 /**
80 * @var boolean $deferExecution
81 */
82 private $deferExecution = false;
83
84 /** @var array $scopes */
85 // Scopes requested by the client
86 protected $requestedScopes = [];
87
88 /**
89 * Construct the Google Client.
90 *
91 * @param array $config
92 */
93 public function __construct(array $config = array())
94 {
95 $this->config = array_merge(
96 [
97 'application_name' => '',
98
99 // Don't change these unless you're working against a special development
100 // or testing environment.
101 'base_path' => self::API_BASE_PATH,
102
103 // https://developers.google.com/console
104 'client_id' => '',
105 'client_secret' => '',
106 'redirect_uri' => null,
107 'state' => null,
108
109 // Simple API access key, also from the API console. Ensure you get
110 // a Server key, and not a Browser key.
111 'developer_key' => '',
112
113 // For use with Google Cloud Platform
114 // fetch the ApplicationDefaultCredentials, if applicable
115 // @see https://developers.google.com/identity/protocols/application-default-credentials
116 'use_application_default_credentials' => false,
117 'signing_key' => null,
118 'signing_algorithm' => null,
119 'subject' => null,
120
121 // Other OAuth2 parameters.
122 'hd' => '',
123 'prompt' => '',
124 'openid.realm' => '',
125 'include_granted_scopes' => null,
126 'login_hint' => '',
127 'request_visible_actions' => '',
128 'access_type' => 'online',
129 'approval_prompt' => 'auto',
130
131 // Task Runner retry configuration
132 // @see Google_Task_Runner
133 'retry' => array(),
134
135 // cache config for downstream auth caching
136 'cache_config' => [],
137
138 // function to be called when an access token is fetched
139 // follows the signature function ($cacheKey, $accessToken)
140 'token_callback' => null,
141
142 // Service class used in Google_Client::verifyIdToken.
143 // Explicitly pass this in to avoid setting JWT::$leeway
144 'jwt' => null,
145 ],
146 $config
147 );
148 }
149
150 /**
151 * Get a string containing the version of the library.
152 *
153 * @return string
154 */
155 public function getLibraryVersion()
156 {
157 return self::LIBVER;
158 }
159
160 /**
161 * For backwards compatibility
162 * alias for fetchAccessTokenWithAuthCode
163 *
164 * @param $code string code from accounts.google.com
165 * @return array access token
166 * @deprecated
167 */
168 public function authenticate($code)
169 {
170 return $this->fetchAccessTokenWithAuthCode($code);
171 }
172
173 /**
174 * Attempt to exchange a code for an valid authentication token.
175 * Helper wrapped around the OAuth 2.0 implementation.
176 *
177 * @param $code string code from accounts.google.com
178 * @return array access token
179 */
180 public function fetchAccessTokenWithAuthCode($code)
181 {
182 if (strlen($code) == 0) {
183 throw new \InvalidArgumentException("Invalid code");
184 }
185
186 $auth = $this->getOAuth2Service();
187 $auth->setCode($code);
188 $auth->setRedirectUri($this->getRedirectUri());
189
190 $httpHandler = HttpHandlerFactory::build($this->getHttpClient());
191 $creds = $auth->fetchAuthToken($httpHandler);
192 if ($creds && isset($creds['access_token'])) {
193 $creds['created'] = time();
194 $this->setAccessToken($creds);
195 }
196
197 return $creds;
198 }
199
200 /**
201 * For backwards compatibility
202 * alias for fetchAccessTokenWithAssertion
203 *
204 * @return array access token
205 * @deprecated
206 */
207 public function refreshTokenWithAssertion()
208 {
209 return $this->fetchAccessTokenWithAssertion();
210 }
211
212 /**
213 * Fetches a fresh access token with a given assertion token.
214 * @param ClientInterface $authHttp optional.
215 * @return array access token
216 */
217 public function fetchAccessTokenWithAssertion(ClientInterface $authHttp = null)
218 {
219 if (!$this->isUsingApplicationDefaultCredentials()) {
220 throw new \DomainException(
221 'set the JSON service account credentials using'
222 . ' Google_Client::setAuthConfig or set the path to your JSON file'
223 . ' with the "GOOGLE_APPLICATION_CREDENTIALS" environment variable'
224 . ' and call Google_Client::useApplicationDefaultCredentials to'
225 . ' refresh a token with assertion.'
226 );
227 }
228
229 $this->getLogger()->log(
230 'info',
231 'OAuth2 access token refresh with Signed JWT assertion grants.'
232 );
233
234 $credentials = $this->createApplicationDefaultCredentials();
235
236 $httpHandler = HttpHandlerFactory::build($authHttp);
237 $creds = $credentials->fetchAuthToken($httpHandler);
238 if ($creds && isset($creds['access_token'])) {
239 $creds['created'] = time();
240 $this->setAccessToken($creds);
241 }
242
243 return $creds;
244 }
245
246 /**
247 * For backwards compatibility
248 * alias for fetchAccessTokenWithRefreshToken
249 *
250 * @param string $refreshToken
251 * @return array access token
252 */
253 public function refreshToken($refreshToken)
254 {
255 return $this->fetchAccessTokenWithRefreshToken($refreshToken);
256 }
257
258 /**
259 * Fetches a fresh OAuth 2.0 access token with the given refresh token.
260 * @param string $refreshToken
261 * @return array access token
262 */
263 public function fetchAccessTokenWithRefreshToken($refreshToken = null)
264 {
265 if (null === $refreshToken) {
266 if (!isset($this->token['refresh_token'])) {
267 throw new \LogicException(
268 'refresh token must be passed in or set as part of setAccessToken'
269 );
270 }
271 $refreshToken = $this->token['refresh_token'];
272 }
273 $this->getLogger()->info('OAuth2 access token refresh');
274 $auth = $this->getOAuth2Service();
275 $auth->setRefreshToken($refreshToken);
276
277 $httpHandler = HttpHandlerFactory::build($this->getHttpClient());
278 $creds = $auth->fetchAuthToken($httpHandler);
279 if ($creds && isset($creds['access_token'])) {
280 $creds['created'] = time();
281 if (!isset($creds['refresh_token'])) {
282 $creds['refresh_token'] = $refreshToken;
283 }
284 $this->setAccessToken($creds);
285 }
286
287 return $creds;
288 }
289
290 /**
291 * Create a URL to obtain user authorization.
292 * The authorization endpoint allows the user to first
293 * authenticate, and then grant/deny the access request.
294 * @param string|array $scope The scope is expressed as an array or list of space-delimited strings.
295 * @return string
296 */
297 public function createAuthUrl($scope = null)
298 {
299 if (empty($scope)) {
300 $scope = $this->prepareScopes();
301 }
302 if (is_array($scope)) {
303 $scope = implode(' ', $scope);
304 }
305
306 // only accept one of prompt or approval_prompt
307 $approvalPrompt = $this->config['prompt']
308 ? null
309 : $this->config['approval_prompt'];
310
311 // include_granted_scopes should be string "true", string "false", or null
312 $includeGrantedScopes = $this->config['include_granted_scopes'] === null
313 ? null
314 : var_export($this->config['include_granted_scopes'], true);
315
316 $params = array_filter(
317 [
318 'access_type' => $this->config['access_type'],
319 'approval_prompt' => $approvalPrompt,
320 'hd' => $this->config['hd'],
321 'include_granted_scopes' => $includeGrantedScopes,
322 'login_hint' => $this->config['login_hint'],
323 'openid.realm' => $this->config['openid.realm'],
324 'prompt' => $this->config['prompt'],
325 'response_type' => 'code',
326 'scope' => $scope,
327 'state' => $this->config['state'],
328 ]
329 );
330
331 // If the list of scopes contains plus.login, add request_visible_actions
332 // to auth URL.
333 $rva = $this->config['request_visible_actions'];
334 if (strlen($rva) > 0 && false !== strpos($scope, 'plus.login')) {
335 $params['request_visible_actions'] = $rva;
336 }
337
338 $auth = $this->getOAuth2Service();
339
340 return (string) $auth->buildFullAuthorizationUri($params);
341 }
342
343 /**
344 * Adds auth listeners to the HTTP client based on the credentials
345 * set in the Google API Client object
346 *
347 * @param GuzzleHttp\ClientInterface $http the http client object.
348 * @return GuzzleHttp\ClientInterface the http client object
349 */
350 public function authorize(ClientInterface $http = null)
351 {
352 $credentials = null;
353 $token = null;
354 $scopes = null;
355 if (null === $http) {
356 $http = $this->getHttpClient();
357 }
358
359 // These conditionals represent the decision tree for authentication
360 // 1. Check for Application Default Credentials
361 // 2. Check for API Key
362 // 3a. Check for an Access Token
363 // 3b. If access token exists but is expired, try to refresh it
364 if ($this->isUsingApplicationDefaultCredentials()) {
365 $credentials = $this->createApplicationDefaultCredentials();
366 } elseif ($token = $this->getAccessToken()) {
367 $scopes = $this->prepareScopes();
368 // add refresh subscriber to request a new token
369 if (isset($token['refresh_token']) && $this->isAccessTokenExpired()) {
370 $credentials = $this->createUserRefreshCredentials(
371 $scopes,
372 $token['refresh_token']
373 );
374 }
375 }
376
377 $authHandler = $this->getAuthHandler();
378
379 if ($credentials) {
380 $callback = $this->config['token_callback'];
381 $http = $authHandler->attachCredentials($http, $credentials, $callback);
382 } elseif ($token) {
383 $http = $authHandler->attachToken($http, $token, (array) $scopes);
384 } elseif ($key = $this->config['developer_key']) {
385 $http = $authHandler->attachKey($http, $key);
386 }
387
388 return $http;
389 }
390
391 /**
392 * Set the configuration to use application default credentials for
393 * authentication
394 *
395 * @see https://developers.google.com/identity/protocols/application-default-credentials
396 * @param boolean $useAppCreds
397 */
398 public function useApplicationDefaultCredentials($useAppCreds = true)
399 {
400 $this->config['use_application_default_credentials'] = $useAppCreds;
401 }
402
403 /**
404 * To prevent useApplicationDefaultCredentials from inappropriately being
405 * called in a conditional
406 *
407 * @see https://developers.google.com/identity/protocols/application-default-credentials
408 */
409 public function isUsingApplicationDefaultCredentials()
410 {
411 return $this->config['use_application_default_credentials'];
412 }
413
414 /**
415 * @param string|array $token
416 * @throws \InvalidArgumentException
417 */
418 public function setAccessToken($token)
419 {
420 if (is_string($token)) {
421 if ($json = json_decode($token, true)) {
422 $token = $json;
423 } else {
424 // assume $token is just the token string
425 $token = array(
426 'access_token' => $token,
427 );
428 }
429 }
430 if ($token == null) {
431 throw new \InvalidArgumentException('invalid json token');
432 }
433 if (!isset($token['access_token'])) {
434 throw new \InvalidArgumentException("Invalid token format");
435 }
436 $this->token = $token;
437 }
438
439 public function getAccessToken()
440 {
441 return $this->token;
442 }
443
444 /**
445 * @return string|null
446 */
447 public function getRefreshToken()
448 {
449 if (isset($this->token['refresh_token'])) {
450 return $this->token['refresh_token'];
451 }
452
453 return null;
454 }
455
456 /**
457 * Returns if the access_token is expired.
458 * @return bool Returns True if the access_token is expired.
459 */
460 public function isAccessTokenExpired()
461 {
462 if (!$this->token) {
463 return true;
464 }
465
466 $created = 0;
467 if (isset($this->token['created'])) {
468 $created = $this->token['created'];
469 } elseif (isset($this->token['id_token'])) {
470 // check the ID token for "iat"
471 // signature verification is not required here, as we are just
472 // using this for convenience to save a round trip request
473 // to the Google API server
474 $idToken = $this->token['id_token'];
475 if (substr_count($idToken, '.') == 2) {
476 $parts = explode('.', $idToken);
477 $payload = json_decode(base64_decode($parts[1]), true);
478 if ($payload && isset($payload['iat'])) {
479 $created = $payload['iat'];
480 }
481 }
482 }
483
484 // If the token is set to expire in the next 30 seconds.
485 return ($created + ($this->token['expires_in'] - 30)) < time();
486 }
487
488 /**
489 * @deprecated See UPGRADING.md for more information
490 */
491 public function getAuth()
492 {
493 throw new \BadMethodCallException(
494 'This function no longer exists. See UPGRADING.md for more information'
495 );
496 }
497
498 /**
499 * @deprecated See UPGRADING.md for more information
500 */
501 public function setAuth($auth)
502 {
503 throw new \BadMethodCallException(
504 'This function no longer exists. See UPGRADING.md for more information'
505 );
506 }
507
508 /**
509 * Set the OAuth 2.0 Client ID.
510 * @param string $clientId
511 */
512 public function setClientId($clientId)
513 {
514 $this->config['client_id'] = $clientId;
515 }
516
517 public function getClientId()
518 {
519 return $this->config['client_id'];
520 }
521
522 /**
523 * Set the OAuth 2.0 Client Secret.
524 * @param string $clientSecret
525 */
526 public function setClientSecret($clientSecret)
527 {
528 $this->config['client_secret'] = $clientSecret;
529 }
530
531 public function getClientSecret()
532 {
533 return $this->config['client_secret'];
534 }
535
536 /**
537 * Set the OAuth 2.0 Redirect URI.
538 * @param string $redirectUri
539 */
540 public function setRedirectUri($redirectUri)
541 {
542 $this->config['redirect_uri'] = $redirectUri;
543 }
544
545 public function getRedirectUri()
546 {
547 return $this->config['redirect_uri'];
548 }
549
550 /**
551 * Set OAuth 2.0 "state" parameter to achieve per-request customization.
552 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-3.1.2.2
553 * @param string $state
554 */
555 public function setState($state)
556 {
557 $this->config['state'] = $state;
558 }
559
560 /**
561 * @param string $accessType Possible values for access_type include:
562 * {@code "offline"} to request offline access from the user.
563 * {@code "online"} to request online access from the user.
564 */
565 public function setAccessType($accessType)
566 {
567 $this->config['access_type'] = $accessType;
568 }
569
570 /**
571 * @param string $approvalPrompt Possible values for approval_prompt include:
572 * {@code "force"} to force the approval UI to appear.
573 * {@code "auto"} to request auto-approval when possible. (This is the default value)
574 */
575 public function setApprovalPrompt($approvalPrompt)
576 {
577 $this->config['approval_prompt'] = $approvalPrompt;
578 }
579
580 /**
581 * Set the login hint, email address or sub id.
582 * @param string $loginHint
583 */
584 public function setLoginHint($loginHint)
585 {
586 $this->config['login_hint'] = $loginHint;
587 }
588
589 /**
590 * Set the application name, this is included in the User-Agent HTTP header.
591 * @param string $applicationName
592 */
593 public function setApplicationName($applicationName)
594 {
595 $this->config['application_name'] = $applicationName;
596 }
597
598 /**
599 * If 'plus.login' is included in the list of requested scopes, you can use
600 * this method to define types of app activities that your app will write.
601 * You can find a list of available types here:
602 * @link https://developers.google.com/+/api/moment-types
603 *
604 * @param array $requestVisibleActions Array of app activity types
605 */
606 public function setRequestVisibleActions($requestVisibleActions)
607 {
608 if (is_array($requestVisibleActions)) {
609 $requestVisibleActions = implode(" ", $requestVisibleActions);
610 }
611 $this->config['request_visible_actions'] = $requestVisibleActions;
612 }
613
614 /**
615 * Set the developer key to use, these are obtained through the API Console.
616 * @see http://code.google.com/apis/console-help/#generatingdevkeys
617 * @param string $developerKey
618 */
619 public function setDeveloperKey($developerKey)
620 {
621 $this->config['developer_key'] = $developerKey;
622 }
623
624 /**
625 * Set the hd (hosted domain) parameter streamlines the login process for
626 * Google Apps hosted accounts. By including the domain of the user, you
627 * restrict sign-in to accounts at that domain.
628 * @param $hd string - the domain to use.
629 */
630 public function setHostedDomain($hd)
631 {
632 $this->config['hd'] = $hd;
633 }
634
635 /**
636 * Set the prompt hint. Valid values are none, consent and select_account.
637 * If no value is specified and the user has not previously authorized
638 * access, then the user is shown a consent screen.
639 * @param $prompt string
640 */
641 public function setPrompt($prompt)
642 {
643 $this->config['prompt'] = $prompt;
644 }
645
646 /**
647 * openid.realm is a parameter from the OpenID 2.0 protocol, not from OAuth
648 * 2.0. It is used in OpenID 2.0 requests to signify the URL-space for which
649 * an authentication request is valid.
650 * @param $realm string - the URL-space to use.
651 */
652 public function setOpenidRealm($realm)
653 {
654 $this->config['openid.realm'] = $realm;
655 }
656
657 /**
658 * If this is provided with the value true, and the authorization request is
659 * granted, the authorization will include any previous authorizations
660 * granted to this user/application combination for other scopes.
661 * @param $include boolean - the URL-space to use.
662 */
663 public function setIncludeGrantedScopes($include)
664 {
665 $this->config['include_granted_scopes'] = $include;
666 }
667
668 /**
669 * sets function to be called when an access token is fetched
670 * @param callable $tokenCallback - function ($cacheKey, $accessToken)
671 */
672 public function setTokenCallback(callable $tokenCallback)
673 {
674 $this->config['token_callback'] = $tokenCallback;
675 }
676
677 /**
678 * Revoke an OAuth2 access token or refresh token. This method will revoke the current access
679 * token, if a token isn't provided.
680 *
681 * @param string|null $token The token (access token or a refresh token) that should be revoked.
682 * @return boolean Returns True if the revocation was successful, otherwise False.
683 */
684 public function revokeToken($token = null)
685 {
686 $tokenRevoker = new Google_AccessToken_Revoke(
687 $this->getHttpClient()
688 );
689
690 return $tokenRevoker->revokeToken($token ?: $this->getAccessToken());
691 }
692
693 /**
694 * Verify an id_token. This method will verify the current id_token, if one
695 * isn't provided.
696 *
697 * @throws \LogicException
698 * @param string|null $idToken The token (id_token) that should be verified.
699 * @return array|false Returns the token payload as an array if the verification was
700 * successful, false otherwise.
701 */
702 public function verifyIdToken($idToken = null)
703 {
704 $tokenVerifier = new Google_AccessToken_Verify(
705 $this->getHttpClient(),
706 $this->getCache(),
707 $this->config['jwt']
708 );
709
710 if (null === $idToken) {
711 $token = $this->getAccessToken();
712 if (!isset($token['id_token'])) {
713 throw new \LogicException(
714 'id_token must be passed in or set as part of setAccessToken'
715 );
716 }
717 $idToken = $token['id_token'];
718 }
719
720 return $tokenVerifier->verifyIdToken(
721 $idToken,
722 $this->getClientId()
723 );
724 }
725
726 /**
727 * Set the scopes to be requested. Must be called before createAuthUrl().
728 * Will remove any previously configured scopes.
729 * @param array $scopes, ie: array('https://www.googleapis.com/auth/plus.login',
730 * 'https://www.googleapis.com/auth/moderator')
731 */
732 public function setScopes($scopes)
733 {
734 $this->requestedScopes = array();
735 $this->addScope($scopes);
736 }
737
738 /**
739 * This functions adds a scope to be requested as part of the OAuth2.0 flow.
740 * Will append any scopes not previously requested to the scope parameter.
741 * A single string will be treated as a scope to request. An array of strings
742 * will each be appended.
743 * @param $scope_or_scopes string|array e.g. "profile"
744 */
745 public function addScope($scope_or_scopes)
746 {
747 if (is_string($scope_or_scopes) && !in_array($scope_or_scopes, $this->requestedScopes)) {
748 $this->requestedScopes[] = $scope_or_scopes;
749 } else if (is_array($scope_or_scopes)) {
750 foreach ($scope_or_scopes as $scope) {
751 $this->addScope($scope);
752 }
753 }
754 }
755
756 /**
757 * Returns the list of scopes requested by the client
758 * @return array the list of scopes
759 *
760 */
761 public function getScopes()
762 {
763 return $this->requestedScopes;
764 }
765
766 /**
767 * @return string|null
768 * @visible For Testing
769 */
770 public function prepareScopes()
771 {
772 if (empty($this->requestedScopes)) {
773 return null;
774 }
775
776 return implode(' ', $this->requestedScopes);
777 }
778
779 /**
780 * Helper method to execute deferred HTTP requests.
781 *
782 * @param $request Psr\Http\Message\RequestInterface|Google_Http_Batch
783 * @throws Google_Exception
784 * @return object of the type of the expected class or Psr\Http\Message\ResponseInterface.
785 */
786 public function execute(RequestInterface $request, $expectedClass = null)
787 {
788 $request = $request->withHeader(
789 'User-Agent',
790 $this->config['application_name']
791 . " " . self::USER_AGENT_SUFFIX
792 . $this->getLibraryVersion()
793 );
794
795 // call the authorize method
796 // this is where most of the grunt work is done
797 $http = $this->authorize();
798
799 return Google_Http_REST::execute($http, $request, $expectedClass, $this->config['retry']);
800 }
801
802 /**
803 * Declare whether batch calls should be used. This may increase throughput
804 * by making multiple requests in one connection.
805 *
806 * @param boolean $useBatch True if the batch support should
807 * be enabled. Defaults to False.
808 */
809 public function setUseBatch($useBatch)
810 {
811 // This is actually an alias for setDefer.
812 $this->setDefer($useBatch);
813 }
814
815 /**
816 * Are we running in Google AppEngine?
817 * return bool
818 */
819 public function isAppEngine()
820 {
821 return (isset($_SERVER['SERVER_SOFTWARE']) &&
822 strpos($_SERVER['SERVER_SOFTWARE'], 'Google App Engine') !== false);
823 }
824
825 public function setConfig($name, $value)
826 {
827 $this->config[$name] = $value;
828 }
829
830 public function getConfig($name, $default = null)
831 {
832 return isset($this->config[$name]) ? $this->config[$name] : $default;
833 }
834
835 /**
836 * For backwards compatibility
837 * alias for setAuthConfig
838 *
839 * @param string $file the configuration file
840 * @throws Google_Exception
841 * @deprecated
842 */
843 public function setAuthConfigFile($file)
844 {
845 $this->setAuthConfig($file);
846 }
847
848 /**
849 * Set the auth config from new or deprecated JSON config.
850 * This structure should match the file downloaded from
851 * the "Download JSON" button on in the Google Developer
852 * Console.
853 * @param string|array $config the configuration json
854 * @throws Google_Exception
855 */
856 public function setAuthConfig($config)
857 {
858 if (is_string($config)) {
859 if (!file_exists($config)) {
860 throw new \InvalidArgumentException('file does not exist');
861 }
862
863 $json = file_get_contents($config);
864
865 if (!$config = json_decode($json, true)) {
866 throw new \LogicException('invalid json for auth config');
867 }
868 }
869
870 $key = isset($config['installed']) ? 'installed' : 'web';
871 if (isset($config['type']) && $config['type'] == 'service_account') {
872 // application default credentials
873 $this->useApplicationDefaultCredentials();
874
875 // set the information from the config
876 $this->setClientId($config['client_id']);
877 $this->config['client_email'] = $config['client_email'];
878 $this->config['signing_key'] = $config['private_key'];
879 $this->config['signing_algorithm'] = 'HS256';
880 } elseif (isset($config[$key])) {
881 // old-style
882 $this->setClientId($config[$key]['client_id']);
883 $this->setClientSecret($config[$key]['client_secret']);
884 if (isset($config[$key]['redirect_uris'])) {
885 $this->setRedirectUri($config[$key]['redirect_uris'][0]);
886 }
887 } else {
888 // new-style
889 $this->setClientId($config['client_id']);
890 $this->setClientSecret($config['client_secret']);
891 if (isset($config['redirect_uris'])) {
892 $this->setRedirectUri($config['redirect_uris'][0]);
893 }
894 }
895 }
896
897 /**
898 * Use when the service account has been delegated domain wide access.
899 *
900 * @param string $subject an email address account to impersonate
901 */
902 public function setSubject($subject)
903 {
904 $this->config['subject'] = $subject;
905 }
906
907 /**
908 * Declare whether making API calls should make the call immediately, or
909 * return a request which can be called with ->execute();
910 *
911 * @param boolean $defer True if calls should not be executed right away.
912 */
913 public function setDefer($defer)
914 {
915 $this->deferExecution = $defer;
916 }
917
918 /**
919 * Whether or not to return raw requests
920 * @return boolean
921 */
922 public function shouldDefer()
923 {
924 return $this->deferExecution;
925 }
926
927 /**
928 * @return Google\Auth\OAuth2 implementation
929 */
930 public function getOAuth2Service()
931 {
932 if (!isset($this->auth)) {
933 $this->auth = $this->createOAuth2Service();
934 }
935
936 return $this->auth;
937 }
938
939 /**
940 * create a default google auth object
941 */
942 protected function createOAuth2Service()
943 {
944 $auth = new OAuth2(
945 [
946 'clientId' => $this->getClientId(),
947 'clientSecret' => $this->getClientSecret(),
948 'authorizationUri' => self::OAUTH2_AUTH_URL,
949 'tokenCredentialUri' => self::OAUTH2_TOKEN_URI,
950 'redirectUri' => $this->getRedirectUri(),
951 'issuer' => $this->config['client_id'],
952 'signingKey' => $this->config['signing_key'],
953 'signingAlgorithm' => $this->config['signing_algorithm'],
954 ]
955 );
956
957 return $auth;
958 }
959
960 /**
961 * Set the Cache object
962 * @param Psr\Cache\CacheItemPoolInterface $cache
963 */
964 public function setCache(CacheItemPoolInterface $cache)
965 {
966 $this->cache = $cache;
967 }
968
969 /**
970 * @return Psr\Cache\CacheItemPoolInterface Cache implementation
971 */
972 public function getCache()
973 {
974 if (!$this->cache) {
975 $this->cache = $this->createDefaultCache();
976 }
977
978 return $this->cache;
979 }
980
981 /**
982 * @param array $cacheConfig
983 */
984 public function setCacheConfig(array $cacheConfig)
985 {
986 $this->config['cache_config'] = $cacheConfig;
987 }
988
989 /**
990 * Set the Logger object
991 * @param Psr\Log\LoggerInterface $logger
992 */
993 public function setLogger(LoggerInterface $logger)
994 {
995 $this->logger = $logger;
996 }
997
998 /**
999 * @return Psr\Log\LoggerInterface implementation
1000 */
1001 public function getLogger()
1002 {
1003 if (!isset($this->logger)) {
1004 $this->logger = $this->createDefaultLogger();
1005 }
1006
1007 return $this->logger;
1008 }
1009
1010 protected function createDefaultLogger()
1011 {
1012 $logger = new Logger('google-api-php-client');
1013 if ($this->isAppEngine()) {
1014 $handler = new MonologSyslogHandler('app', LOG_USER, Logger::NOTICE);
1015 } else {
1016 $handler = new MonologStreamHandler('php://stderr', Logger::NOTICE);
1017 }
1018 $logger->pushHandler($handler);
1019
1020 return $logger;
1021 }
1022
1023 protected function createDefaultCache()
1024 {
1025 return new MemoryCacheItemPool;
1026 }
1027
1028 /**
1029 * Set the Http Client object
1030 * @param GuzzleHttp\ClientInterface $http
1031 */
1032 public function setHttpClient(ClientInterface $http)
1033 {
1034 $this->http = $http;
1035 }
1036
1037 /**
1038 * @return GuzzleHttp\ClientInterface implementation
1039 */
1040 public function getHttpClient()
1041 {
1042 if (null === $this->http) {
1043 $this->http = $this->createDefaultHttpClient();
1044 }
1045
1046 return $this->http;
1047 }
1048
1049 protected function createDefaultHttpClient()
1050 {
1051 $options = ['exceptions' => false];
1052
1053 $version = ClientInterface::VERSION;
1054 if ('5' === $version[0]) {
1055 $options = [
1056 'base_url' => $this->config['base_path'],
1057 'defaults' => $options,
1058 ];
1059 if ($this->isAppEngine()) {
1060 // set StreamHandler on AppEngine by default
1061 $options['handler'] = new StreamHandler();
1062 $options['defaults']['verify'] = '/etc/ca-certificates.crt';
1063 }
1064 } else {
1065 // guzzle 6
1066 $options['base_uri'] = $this->config['base_path'];
1067 }
1068
1069 return new Client($options);
1070 }
1071
1072 private function createApplicationDefaultCredentials()
1073 {
1074 $scopes = $this->prepareScopes();
1075 $sub = $this->config['subject'];
1076 $signingKey = $this->config['signing_key'];
1077
1078 // create credentials using values supplied in setAuthConfig
1079 if ($signingKey) {
1080 $serviceAccountCredentials = array(
1081 'client_id' => $this->config['client_id'],
1082 'client_email' => $this->config['client_email'],
1083 'private_key' => $signingKey,
1084 'type' => 'service_account',
1085 );
1086 $credentials = CredentialsLoader::makeCredentials($scopes, $serviceAccountCredentials);
1087 } else {
1088 $credentials = ApplicationDefaultCredentials::getCredentials($scopes);
1089 }
1090
1091 // for service account domain-wide authority (impersonating a user)
1092 // @see https://developers.google.com/identity/protocols/OAuth2ServiceAccount
1093 if ($sub) {
1094 if (!$credentials instanceof ServiceAccountCredentials) {
1095 throw new \DomainException('domain-wide authority requires service account credentials');
1096 }
1097
1098 $credentials->setSub($sub);
1099 }
1100
1101 return $credentials;
1102 }
1103
1104 protected function getAuthHandler()
1105 {
1106 // Be very careful using the cache, as the underlying auth library's cache
1107 // implementation is naive, and the cache keys do not account for user
1108 // sessions.
1109 //
1110 // @see https://github.com/google/google-api-php-client/issues/821
1111 return Google_AuthHandler_AuthHandlerFactory::build(
1112 $this->getCache(),
1113 $this->config['cache_config']
1114 );
1115 }
1116
1117 private function createUserRefreshCredentials($scope, $refreshToken)
1118 {
1119 $creds = array_filter(
1120 array(
1121 'client_id' => $this->getClientId(),
1122 'client_secret' => $this->getClientSecret(),
1123 'refresh_token' => $refreshToken,
1124 )
1125 );
1126
1127 return new UserRefreshCredentials($scope, $creds);
1128 }
1129 }
1130