PluginProbe
Analytify – Google Analytics Dashboard For WordPress (GA4 analytics tracking) / 1.2.5
Analytify – Google Analytics Dashboard For WordPress (GA4 analytics tracking) v1.2.5
9.1.2 9.1.1 9.1.0 9.0.2 9.0.1 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7 1.1.0 1.1.1 1.2.0 1.2.1 1.2.2 1.2.3 1.2.4 1.2.5 1.3.0 1.3.1 1.3.2 All 153 releases
wp-analytify / lib / Google / Client.php

Client.php in Analytify – Google Analytics Dashboard For WordPress (GA4 analytics tracking) 1.2.5, at lib/Google/Client.php

618 lines 17.6 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 ANALYTIFY_LIB_PATH . 'Google/Auth/AssertionCredentials.php';
19 require_once ANALYTIFY_LIB_PATH . 'Google/Cache/File.php';
20 require_once ANALYTIFY_LIB_PATH . 'Google/Cache/Memcache.php';
21 require_once ANALYTIFY_LIB_PATH . 'Google/Config.php';
22 require_once ANALYTIFY_LIB_PATH . 'Google/Collection.php';
23 require_once ANALYTIFY_LIB_PATH . 'Google/Exception.php';
24 require_once ANALYTIFY_LIB_PATH . 'Google/IO/Curl.php';
25 require_once ANALYTIFY_LIB_PATH . 'Google/IO/Stream.php';
26 require_once ANALYTIFY_LIB_PATH . 'Google/Model.php';
27 require_once ANALYTIFY_LIB_PATH . 'Google/Service.php';
28 require_once ANALYTIFY_LIB_PATH . '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 Analytify_Google_Client
38 {
39 const LIBVER = "1.0.5-beta";
40 const USER_AGENT_SUFFIX = "google-api-php-client/";
41 /**
42 * @var Analytify_Google_Auth_Abstract $auth
43 */
44 private $auth;
45
46 /**
47 * @var Analytify_Google_IO_Abstract $io
48 */
49 private $io;
50
51 /**
52 * @var Analytify_Google_Cache_Abstract $cache
53 */
54 private $cache;
55
56 /**
57 * @var Analytify_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 Analytify_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 Analytify_Google_Config($config);
90 } else if ( !($config instanceof Analytify_Google_Config)) {
91 $config = new Analytify_Google_Config();
92
93 if ($this->isAppEngine()) {
94 // Automatically use Memcache if we're in AppEngine.
95 $config->setCacheClass('Analytify_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('Analytify_Google_Http_Request', 'disable_gzip', true);
101 }
102 }
103
104 if ($config->getIoClass() == Analytify_Google_Config::USE_AUTO_IO_SELECTION) {
105 if (function_exists('curl_version') && function_exists('curl_exec')) {
106 $config->setIoClass("Analytify_Google_IO_Curl");
107 } else {
108 $config->setIoClass("Analytify_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 Analytify_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 Analytify_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 Analytify_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 Analytify_Google_Auth_Abstract $auth
204 */
205 public function setAuth(Analytify_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 Analytify_Google_Io_Abstract $auth
214 */
215 public function setIo(Analytify_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 Analytify_Google_Cache_Abstract $auth
224 */
225 public function setCache(Analytify_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 || '[]' == $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 login hint, email address or sub id.
297 * @param string $loginHint
298 */
299 public function setLoginHint($loginHint)
300 {
301 $this->config->setLoginHint($loginHint);
302 }
303
304 /**
305 * Set the application name, this is included in the User-Agent HTTP header.
306 * @param string $applicationName
307 */
308 public function setApplicationName($applicationName)
309 {
310 $this->config->setApplicationName($applicationName);
311 }
312
313 /**
314 * Set the OAuth 2.0 Client ID.
315 * @param string $clientId
316 */
317 public function setClientId($clientId)
318 {
319 $this->config->setClientId($clientId);
320 }
321
322 /**
323 * Set the OAuth 2.0 Client Secret.
324 * @param string $clientSecret
325 */
326 public function setClientSecret($clientSecret)
327 {
328 $this->config->setClientSecret($clientSecret);
329 }
330
331 /**
332 * Set the OAuth 2.0 Redirect URI.
333 * @param string $redirectUri
334 */
335 public function setRedirectUri($redirectUri)
336 {
337 $this->config->setRedirectUri($redirectUri);
338 }
339
340 /**
341 * If 'plus.login' is included in the list of requested scopes, you can use
342 * this method to define types of app activities that your app will write.
343 * You can find a list of available types here:
344 * @link https://developers.google.com/+/api/moment-types
345 *
346 * @param array $requestVisibleActions Array of app activity types
347 */
348 public function setRequestVisibleActions($requestVisibleActions)
349 {
350 if (is_array($requestVisibleActions)) {
351 $requestVisibleActions = join(" ", $requestVisibleActions);
352 }
353 $this->config->setRequestVisibleActions($requestVisibleActions);
354 }
355
356 /**
357 * Set the developer key to use, these are obtained through the API Console.
358 * @see http://code.google.com/apis/console-help/#generatingdevkeys
359 * @param string $developerKey
360 */
361 public function setDeveloperKey($developerKey)
362 {
363 $this->config->setDeveloperKey($developerKey);
364 }
365
366 /**
367 * Fetches a fresh OAuth 2.0 access token with the given refresh token.
368 * @param string $refreshToken
369 * @return void
370 */
371 public function refreshToken($refreshToken)
372 {
373 return $this->getAuth()->refreshToken($refreshToken);
374 }
375
376 /**
377 * Revoke an OAuth2 access token or refresh token. This method will revoke the current access
378 * token, if a token isn't provided.
379 * @throws Analytify_Google_Auth_Exception
380 * @param string|null $token The token (access token or a refresh token) that should be revoked.
381 * @return boolean Returns True if the revocation was successful, otherwise False.
382 */
383 public function revokeToken($token = null)
384 {
385 return $this->getAuth()->revokeToken($token);
386 }
387
388 /**
389 * Verify an id_token. This method will verify the current id_token, if one
390 * isn't provided.
391 * @throws Analytify_Google_Auth_Exception
392 * @param string|null $token The token (id_token) that should be verified.
393 * @return Analytify_Google_Auth_LoginTicket Returns an apiLoginTicket if the verification was
394 * successful.
395 */
396 public function verifyIdToken($token = null)
397 {
398 return $this->getAuth()->verifyIdToken($token);
399 }
400
401 /**
402 * Verify a JWT that was signed with your own certificates.
403 *
404 * @param $jwt the token
405 * @param $certs array of certificates
406 * @param $required_audience the expected consumer of the token
407 * @param [$issuer] the expected issues, defaults to Google
408 * @param [$max_expiry] the max lifetime of a token, defaults to MAX_TOKEN_LIFETIME_SECS
409 * @return token information if valid, false if not
410 */
411 public function verifySignedJwt($id_token, $cert_location, $audience, $issuer, $max_expiry = null)
412 {
413 $auth = new Analytify_Google_Auth_OAuth2($this);
414 $certs = $auth->retrieveCertsFromLocation($cert_location);
415 return $auth->verifySignedJwtWithCerts($id_token, $certs, $audience, $issuer, $max_expiry);
416 }
417
418 /**
419 * @param Analytify_Google_Auth_AssertionCredentials $creds
420 * @return void
421 */
422 public function setAssertionCredentials(Analytify_Google_Auth_AssertionCredentials $creds)
423 {
424 $this->getAuth()->setAssertionCredentials($creds);
425 }
426
427 /**
428 * Set the scopes to be requested. Must be called before createAuthUrl().
429 * Will remove any previously configured scopes.
430 * @param array $scopes, ie: array('https://www.googleapis.com/auth/plus.login',
431 * 'https://www.googleapis.com/auth/moderator')
432 */
433 public function setScopes($scopes)
434 {
435 $this->requestedScopes = array();
436 $this->addScope($scopes);
437 }
438
439 /**
440 * This functions adds a scope to be requested as part of the OAuth2.0 flow.
441 * Will append any scopes not previously requested to the scope parameter.
442 * A single string will be treated as a scope to request. An array of strings
443 * will each be appended.
444 * @param $scope_or_scopes string|array e.g. "profile"
445 */
446 public function addScope($scope_or_scopes)
447 {
448 if (is_string($scope_or_scopes) && !in_array($scope_or_scopes, $this->requestedScopes)) {
449 $this->requestedScopes[] = $scope_or_scopes;
450 } else if (is_array($scope_or_scopes)) {
451 foreach ($scope_or_scopes as $scope) {
452 $this->addScope($scope);
453 }
454 }
455 }
456
457 /**
458 * Returns the list of scopes requested by the client
459 * @return array the list of scopes
460 *
461 */
462 public function getScopes()
463 {
464 return $this->requestedScopes;
465 }
466
467 /**
468 * Declare whether batch calls should be used. This may increase throughput
469 * by making multiple requests in one connection.
470 *
471 * @param boolean $useBatch True if the batch support should
472 * be enabled. Defaults to False.
473 */
474 public function setUseBatch($useBatch)
475 {
476 // This is actually an alias for setDefer.
477 $this->setDefer($useBatch);
478 }
479
480 /**
481 * Declare whether making API calls should make the call immediately, or
482 * return a request which can be called with ->execute();
483 *
484 * @param boolean $defer True if calls should not be executed right away.
485 */
486 public function setDefer($defer)
487 {
488 $this->deferExecution = $defer;
489 }
490
491 /**
492 * Helper method to execute deferred HTTP requests.
493 *
494 * @returns object of the type of the expected class or array.
495 */
496 public function execute($request)
497 {
498 if ($request instanceof Analytify_Google_Http_Request) {
499 $request->setUserAgent(
500 $this->getApplicationName()
501 . " " . self::USER_AGENT_SUFFIX
502 . $this->getLibraryVersion()
503 );
504 if (!$this->getClassConfig("Analytify_Google_Http_Request", "disable_gzip")) {
505 $request->enableGzip();
506 }
507 $request->maybeMoveParametersToBody();
508 return Analytify_Google_Http_REST::execute($this, $request);
509 } else if ($request instanceof Analytify_Google_Http_Batch) {
510 return $request->execute();
511 } else {
512 throw new Analytify_Google_Exception("Do not know how to execute this type of object.");
513 }
514 }
515
516 /**
517 * Whether or not to return raw requests
518 * @return boolean
519 */
520 public function shouldDefer()
521 {
522 return $this->deferExecution;
523 }
524
525 /**
526 * @return Analytify_Google_Auth_Abstract Authentication implementation
527 */
528 public function getAuth()
529 {
530 if (!isset($this->auth)) {
531 $class = $this->config->getAuthClass();
532 $this->auth = new $class($this);
533 }
534 return $this->auth;
535 }
536
537 /**
538 * @return Analytify_Google_IO_Abstract IO implementation
539 */
540 public function getIo()
541 {
542 if (!isset($this->io)) {
543 $class = $this->config->getIoClass();
544 $this->io = new $class($this);
545 }
546 return $this->io;
547 }
548
549 /**
550 * @return Analytify_Google_Cache_Abstract Cache implementation
551 */
552 public function getCache()
553 {
554 if (!isset($this->cache)) {
555 $class = $this->config->getCacheClass();
556 $this->cache = new $class($this);
557 }
558 return $this->cache;
559 }
560
561 /**
562 * Retrieve custom configuration for a specific class.
563 * @param $class string|object - class or instance of class to retrieve
564 * @param $key string optional - key to retrieve
565 */
566 public function getClassConfig($class, $key = null)
567 {
568 if (!is_string($class)) {
569 $class = get_class($class);
570 }
571 return $this->config->getClassConfig($class, $key);
572 }
573
574 /**
575 * Set configuration specific to a given class.
576 * $config->setClassConfig('Analytify_Google_Cache_File',
577 * array('directory' => '/tmp/cache'));
578 * @param $class The class name for the configuration
579 * @param $config string key or an array of configuration values
580 * @param $value optional - if $config is a key, the value
581 *
582 */
583 public function setClassConfig($class, $config, $value = null)
584 {
585 if (!is_string($class)) {
586 $class = get_class($class);
587 }
588 return $this->config->setClassConfig($class, $config, $value);
589
590 }
591
592 /**
593 * @return string the base URL to use for calls to the APIs
594 */
595 public function getBasePath()
596 {
597 return $this->config->getBasePath();
598 }
599
600 /**
601 * @return string the name of the application
602 */
603 public function getApplicationName()
604 {
605 return $this->config->getApplicationName();
606 }
607
608 /**
609 * Are we running in Google AppEngine?
610 * return bool
611 */
612 public function isAppEngine()
613 {
614 return (isset($_SERVER['SERVER_SOFTWARE']) &&
615 strpos($_SERVER['SERVER_SOFTWARE'], 'Google App Engine') !== false);
616 }
617 }
618