PluginProbe
WP Database Backup – Unlimited Database & Files Backup by Backup for WP / 7.13
WP Database Backup – Unlimited Database & Files Backup by Backup for WP v7.13
7.13 7.12 trunk 1.1 2.1.1 5.9 6.0 6.1 6.10 6.11 6.12 6.12.1 6.2 6.3 6.4 6.5 6.5.1 6.6 6.7 6.8 6.9 7.0 7.0.1 7.1 7.10 All 34 releases
wp-database-backup / includes / admin / Destination / Google / google-api-php-client / src / Google_Client.php

Google_Client.php in WP Database Backup – Unlimited Database & Files Backup by Backup for WP 7.13, at includes/admin/Destination/Google/google-api-php-client/src/Google_Client.php

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