PluginProbe
Gianism / 1.0
Gianism v1.0
4.3.0 4.3.1 4.3.2 4.3.3 4.3.4 4.4.0 5.0.0 5.0.1 5.0.2 5.1.0 5.2.1 5.2.2 5.3.0 6.0.0 6.0.1 trunk 1.0 1.1 1.1.1 1.1.2 1.1.3 1.1.4 1.1.5 1.1.6 1.1.7 All 65 releases
gianism / sdks / google / apiClient.php

apiClient.php in Gianism 1.0, at sdks/google/apiClient.php

319 lines 10.4 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 // Check for the required json and curl extensions, the Google API PHP Client won't function without
19 if (! function_exists('curl_init')) {
20 throw new Exception('The Google PHP API Client requires the CURL PHP extension');
21 }
22
23 if (! function_exists('json_decode')) {
24 throw new Exception('The Google PHP API Client requires the JSON PHP extension');
25 }
26
27 // hack around with the include paths a bit so the library 'just works'
28 $cwd = dirname(__FILE__);
29 set_include_path("$cwd" . PATH_SEPARATOR . get_include_path());
30
31 require_once "config.php";
32 // If a local configuration file is found, merge it's values with the default configuration
33 if (file_exists($cwd . '/local_config.php')) {
34 $defaultConfig = $apiConfig;
35 require_once ($cwd . '/local_config.php');
36 $apiConfig = array_merge($defaultConfig, $apiConfig);
37 }
38
39 // Include the top level classes, they each include their own dependencies
40 require_once 'auth/apiAuth.php';
41 require_once 'cache/apiCache.php';
42 require_once 'io/apiIO.php';
43 require_once 'service/apiService.php';
44
45 /**
46 * The Google API Client
47 * http://code.google.com/p/google-api-php-client/
48 *
49 * @author Chris Chabot <chabotc@google.com>
50 * @author Chirag Shah <chirags@google.com>
51 */
52 class apiClient {
53 // the version of the discovery mechanism this class is meant to work with
54 const discoveryVersion = 'v0.3';
55
56 /**
57 *
58 * @static
59 * @var apiAuth $auth
60 */
61 static $auth;
62
63 /** @var apiIo $io */
64 static $io;
65
66 /** @var apiCache $cache */
67 static $cache;
68
69 /** @var array $scopes */
70 protected $scopes = array();
71
72 /** @var bool $useObjects */
73 protected $useObjects = false;
74
75 // definitions of services that are discovered.
76 protected $services = array();
77
78 // Used to track authenticated state, can't discover services after doing authenticate()
79 private $authenticated = false;
80
81 private $defaultService = array(
82 'authorization_token_url' => 'https://www.google.com/accounts/OAuthAuthorizeToken',
83 'request_token_url' => 'https://www.google.com/accounts/OAuthGetRequestToken',
84 'access_token_url' => 'https://www.google.com/accounts/OAuthGetAccessToken');
85
86 public function __construct($config = array()) {
87 global $apiConfig;
88 $apiConfig = array_merge($apiConfig, $config);
89 self::$cache = new $apiConfig['cacheClass']();
90 self::$auth = new $apiConfig['authClass']();
91 self::$io = new $apiConfig['ioClass']();
92 }
93
94 public function discover($service, $version = 'v1') {
95 $this->addService($service, $version);
96 $this->$service = $this->discoverService($service, $this->services[$service]['discoveryURI']);
97 return $this->$service;
98 }
99
100 /**
101 * Add a service
102 */
103 public function addService($service, $version) {
104 global $apiConfig;
105 if ($this->authenticated) {
106 // Adding services after being authenticated, since the oauth scope is already set (so you wouldn't have access to that data)
107 throw new apiException('Cant add services after having authenticated');
108 }
109 $this->services[$service] = $this->defaultService;
110 if (isset($apiConfig['services'][$service])) {
111 // Merge the service descriptor with the default values
112 $this->services[$service] = array_merge($this->services[$service], $apiConfig['services'][$service]);
113 }
114 $this->services[$service]['discoveryURI'] = $apiConfig['basePath'] . '/discovery/' . self::discoveryVersion . '/describe/' . urlencode($service) . '/' . urlencode($version);
115 }
116
117 /**
118 * Set the type of Auth class the client should use.
119 * @param string $authClassName
120 */
121 public function setAuthClass($authClassName) {
122 self::$auth = new $authClassName();
123 }
124
125 public function authenticate() {
126 $service = $this->prepareService();
127 $this->authenticated = true;
128 return self::$auth->authenticate($service);
129 }
130
131 /**
132 * Construct the OAuth 2.0 authorization request URI.
133 * @return string
134 */
135 public function createAuthUrl() {
136 $service = $this->prepareService();
137 return self::$auth->createAuthUrl($service['scope']);
138 }
139
140 private function prepareService() {
141 $service = $this->defaultService;
142 $scopes = array();
143 if ($this->scopes) {
144 $scopes = $this->scopes;
145 } else {
146 foreach ($this->services as $key => $val) {
147 if (isset($val['scope'])) {
148 if (is_array($val['scope'])) {
149 $scopes = array_merge($val['scope'], $scopes);
150 } else {
151 $scopes[] = $val['scope'];
152 }
153 } else {
154 $scopes[] = 'https://www.googleapis.com/auth/' . $key;
155 }
156 unset($val['discoveryURI']);
157 unset($val['scope']);
158 $service = array_merge($service, $val);
159 }
160 }
161 $service['scope'] = implode(' ', $scopes);
162 return $service;
163 }
164
165 /**
166 * Set the OAuth 2.0 access token using the string that resulted from calling authenticate()
167 * or apiClient#getAccessToken().
168 * @param string $accessToken JSON encoded string containing in the following format:
169 * {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
170 * "expires_in":3600, "id_token":"TOKEN", "created":1320790426}
171 */
172 public function setAccessToken($accessToken) {
173 if ($accessToken == null || 'null' == $accessToken) {
174 $accessToken = null;
175 }
176 self::$auth->setAccessToken($accessToken);
177 }
178
179 /**
180 * Get the OAuth 2.0 access token.
181 * @return string $accessToken JSON encoded string in the following format:
182 * {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
183 * "expires_in":3600,"id_token":"TOKEN", "created":1320790426}
184 */
185 public function getAccessToken() {
186 $token = self::$auth->getAccessToken();
187 return (null == $token || 'null' == $token) ? null : $token;
188 }
189
190 /**
191 * Set the developer key to use, these are obtained through the API Console.
192 * @see http://code.google.com/apis/console-help/#generatingdevkeys
193 * @param string $developerKey
194 */
195 public function setDeveloperKey($developerKey) {
196 self::$auth->setDeveloperKey($developerKey);
197 }
198
199 /**
200 * Set OAuth 2.0 "state" parameter to achieve per-request customization.
201 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-3.1.2.2
202 * @param string $state
203 */
204 public function setState($state) {
205 self::$auth->setState($state);
206 }
207
208 /**
209 * @param string $accessType Possible values for access_type include:
210 * {@code "offline"} to request offline access from the user. (This is the default value)
211 * {@code "online"} to request online access from the user.
212 */
213 public function setAccessType($accessType) {
214 self::$auth->setAccessType($accessType);
215 }
216
217 /**
218 * @param string $approvalPrompt Possible values for approval_prompt include:
219 * {@code "force"} to force the approval UI to appear. (This is the default value)
220 * {@code "auto"} to request auto-approval when possible.
221 */
222 public function setApprovalPrompt($approvalPrompt) {
223 self::$auth->setApprovalPrompt($approvalPrompt);
224 }
225
226 /**
227 * Set the application name, this is included in the User-Agent HTTP header.
228 * @param string $applicationName
229 */
230 public function setApplicationName($applicationName) {
231 global $apiConfig;
232 $apiConfig['application_name'] = $applicationName;
233 }
234
235 /**
236 * Set the OAuth 2.0 Client ID.
237 * @param string $clientId
238 */
239 public function setClientId($clientId) {
240 global $apiConfig;
241 $apiConfig['oauth2_client_id'] = $clientId;
242 self::$auth->clientId = $clientId;
243 }
244
245 /**
246 * Set the OAuth 2.0 Client Secret.
247 * @param string $clientSecret
248 */
249 public function setClientSecret($clientSecret) {
250 global $apiConfig;
251 $apiConfig['oauth2_client_secret'] = $clientSecret;
252 self::$auth->clientSecret = $clientSecret;
253 }
254
255 /**
256 * Set the OAuth 2.0 Redirect URI.
257 * @param string $redirectUri
258 */
259 public function setRedirectUri($redirectUri) {
260 global $apiConfig;
261 $apiConfig['oauth2_redirect_uri'] = $redirectUri;
262 self::$auth->redirectUri = $redirectUri;
263 }
264
265 /**
266 * This function allows you to overrule the automatically generated scopes,
267 * so that you can ask for more or less permission in the auth flow
268 * Set this before you call authenticate() though!
269 * @param array $scopes, ie: array('https://www.googleapis.com/auth/plus', 'https://www.googleapis.com/auth/moderator')
270 */
271 public function setScopes($scopes) {
272 $this->scopes = is_string($scopes) ? explode(" ", $scopes) : $scopes;
273 }
274
275 /**
276 * Declare if objects should be returned by the api service classes.
277 *
278 * @param boolean $useObjects True if objects should be returned by the service classes.
279 * False if associative arrays should be returned (default behavior).
280 */
281 public function setUseObjects($useObjects) {
282 global $apiConfig;
283 $apiConfig['use_objects'] = $useObjects;
284 }
285
286 private function discoverService($serviceName, $serviceURI) {
287 $request = self::$io->makeRequest(new apiHttpRequest($serviceURI));
288 if ($request->getResponseHttpCode() != 200) {
289 throw new apiException("Could not fetch discovery document for $serviceName, http code: " . $request->getResponseHttpCode() . ", response body: " . $request->getResponseBody());
290 }
291 $discoveryResponse = $request->getResponseBody();
292 $discoveryDocument = json_decode($discoveryResponse, true);
293 if ($discoveryDocument == NULL) {
294 throw new apiException("Invalid json returned for $serviceName");
295 }
296 return new apiService($serviceName, $discoveryDocument, apiClient::getIo());
297 }
298
299 /*
300 * @return apiIo the implementation of apiIo.
301 */
302 public static function getIo() {
303 return apiClient::$io;
304 }
305
306 /*
307 * @return apiCache the implementation of apiCache.
308 */
309 public function getCache() {
310 return apiClient::$cache;
311 }
312 }
313
314 // Exceptions that the Google PHP API Library can throw
315 class apiException extends Exception {}
316 class apiAuthException extends apiException {}
317 class apiCacheException extends apiException {}
318 class apiIOException extends apiException {}
319 class apiServiceException extends apiException {}