-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUser.php
398 lines (341 loc) · 14 KB
/
User.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
<?php
namespace ElockyAPI;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* Implement the Elocky API.
* The User class is either an anonymous user or an authenticated user depending on the credential parameters
* at object creation.
* @see https://elocky.com/fr/doc-api-test Elocky API
* @author domotruc
*
*/
class User {
const ACCESS_TOKEN_ID = 'access_token';
const REFRESH_TOKEN_ID = 'refresh_token';
const EXPIRY_DATE_ID = 'expiry_date';
// Client id and secret
private $client_id;
private $client_secret;
/**
* @var string authenticated user name
*/
private $username;
/**
* @var string authenticated user password
*/
private $password;
/**
* PSR-3 compliant logger
* @var LoggerInterface
*/
private $logger;
/**
* @var string access token
*/
private $access_token;
/**
* @var string token to request token refresh
*/
private $refresh_token;
/**
* @var \DateTime Token expiry date
*/
private $expiry_date;
/**
* @var callable $token_update_func user callback called when token is updated (if set)
*/
private $update_token_func;
# CONSTRUCTORS
##############
function __construct() {
// Default logger that does nothing
$this->logger = new NullLogger();
$a = func_get_args();
$i = func_num_args();
if (method_exists($this,$f='__construct'.$i)) {
call_user_func_array(array($this,$f),$a);
}
}
protected function __construct2($_client_id, $_client_secret) {
$this->client_id = $_client_id;
$this->client_secret = $_client_secret;
$this->logger->debug($this->buildMsg('anonymous user creation'));
}
protected function __construct3($_client_id, $_client_secret, LoggerInterface $_logger) {
$this->logger = $_logger;
$this->__construct2($_client_id, $_client_secret);
}
protected function __construct4($_client_id, $_client_secret, $_username, $_password) {
$this->client_id = $_client_id;
$this->client_secret = $_client_secret;
$this->username = $_username;
$this->password = $_password;
$this->logger->debug($this->buildMsg('authenticated user creation'));
}
protected function __construct5($_client_id, $_client_secret, $_username, $_password, LoggerInterface $_logger) {
$this->logger = $_logger;
$this->__construct4($_client_id, $_client_secret, $_username, $_password);
}
# Callback setters
##################
/**
* Set the user callback to be called when token is updated
* @param callable $callback user callback
*/
public function setUpdateTokenFunc($callback) {
$this->update_token_func = $callback;
}
# API functionalities management
################################
public static function printJson($s) {
print(json_encode(json_decode($s), JSON_PRETTY_PRINT));
}
# User management
#################
/**
* Return the user profile
* @see https://elocky.com/fr/doc-api-test#get-user Elocky API
* @return array user profile as an associative array
*/
public function requestUserProfile() {
$this->manageToken();
return $this->curlExec("https://www.elocky.com/webservice/user/.json", 'access_token=' . $this->access_token);
}
/**
* Download and save the user photo
* @param string $_filename filename of the photo to retrieve
* @param string $_save_dir local directory to save the photo
*/
public function requestUserPhoto($_filename, $_save_dir) {
$this->manageToken();
$photo = $this->curlExec("https://www.elocky.com/webservice/user/photo/" . $_filename . "/download.json", 'access_token=' . $this->access_token, false);
return file_put_contents($_save_dir . '/' . $_filename, $photo);
}
# Places management
###################
/**
* Return the list of countries and time zone
* @see https://elocky.com/fr/doc-api-test#liste-pays Elocky API
* @return array list of countries and time zone
*/
public function requestCountries() {
$this->manageToken();
return $this->curlExec("https://www.elocky.com/webservice/address/country.json", 'access_token=' . $this->access_token);
}
/**
* Return the places associated to this user
* @see https://elocky.com/fr/doc-api-test#liste-lieu Elocky API
* @return array list of places as an associative array
* @throws \Exception in case of communication error with the Elocky server
*/
public function requestPlaces() {
$this->manageToken();
return $this->curlExec("https://www.elocky.com/webservice/address/list.json", 'access_token=' . $this->access_token);
}
/**
* Download and save the place photo
* @param string $_filename filename of the photo to retrieve
* @param string $_save_dir local directory to save the photo
*/
public function requestPlacePhoto($_filename, $_save_dir) {
$this->manageToken();
$photo = $this->curlExec("https://www.elocky.com/webservice/address/photo/" . $_filename . "/download.json", 'access_token=' . $this->access_token, false);
return file_put_contents($_save_dir . '/' . $_filename, $photo);
}
public function requestHistory($_place_id, $_start_nb) {
$this->manageToken();
return $this->curlExec("https://www.elocky.com/webservice/address/log/" . $_place_id . "/" . $_start_nb . ".json", 'access_token=' . $this->access_token);
}
# Access management
###################
public function requestAccesses() {
$this->manageToken();
return $this->curlExec("https://www.elocky.com/webservice/access/list/user.json", 'access_token=' . $this->access_token);
}
public function requestGuests() {
$this->manageToken();
return $this->curlExec("https://www.elocky.com/webservice/access/list/invite.json", 'access_token=' . $this->access_token);
}
# Object management
###################
public function requestObjects($_refAdmin, $_idPlace) {
$this->manageToken();
return $this->curlExec("https://www.elocky.com/webservice/address/object/" . $_refAdmin . "/" . $_idPlace . ".json", 'access_token=' . $this->access_token);
}
// FIXME: tentative, pas encore supporté par l'API
public function requestOpening($_idBoard) {
$this->manageToken();
return $this->curlExec("https://www.elocky.com/webservice/object/open/" . $_idBoard . ".json", 'access_token=' . $this->access_token);
}
###################################
/**
* Return token data related to this User.
* @return array associative array which keys are ACCESS_TOKEN_ID, REFRESH_TOKEN_ID and EXPIRY_DATE_ID
* (EXPIRY_DATE_ID is a timestamp format)
*/
public function getAuthenticationData() {
$this->manageToken();
return array(
self::ACCESS_TOKEN_ID => $this->access_token,
self::REFRESH_TOKEN_ID => $this->refresh_token,
self::EXPIRY_DATE_ID => $this->expiry_date->getTimestamp()
);
}
/**
* Set token data previously retrieved with getAuthenticationData.
* @param array associative array which keys are ACCESS_TOKEN_ID, REFRESH_TOKEN_ID and EXPIRY_DATE_ID
* (EXPIRY_DATE_ID is a timestamp format)
*/
public function setAuthenticationData(array $_authData) {
$this->access_token = $_authData[self::ACCESS_TOKEN_ID];
$this->refresh_token = $_authData[self::REFRESH_TOKEN_ID];
$this->expiry_date = (new \DateTime())->setTimestamp($_authData[self::EXPIRY_DATE_ID]);
$this->logger->debug($this->buildMsg('authentication data set'));
}
/**
* Return the token expiry date
* @return \DateTime Token expiry date
*/
public function getTokenExpiryDate() {
return $this->expiry_date;
}
/**
* Refresh the access token
* Request a new token if needed
*/
public function refreshToken() {
if (isset($this->refresh_token)) {
$this->logger->info($this->buildMsg('refresh the current token'));
$this->processToken($this->requestUserTokenRefresh());
if (isset($this->update_token_func))
call_user_func($this->update_token_func);
}
else {
$this->initToken();
}
}
/**
* Manage the token validity. This method shall be called before each request to the Elocky server
* to insure that the token is defined and valid.
*/
protected function manageToken() {
if (isset($this->access_token)) {
if ($this->isTokenValid()) {
$this->logger->debug($this->buildMsg('current token is still valid'));
}
else {
$this->logger->info($this->buildMsg('current token has expired, refresh it'));
try {
$this->refreshToken();
}
catch (\Exception $e) {
$msg = json_decode($e->getMessage(), TRUE);
if ($msg['error'] == 'invalid_grant') {
$this->logger->info($this->buildMsg('refresh token has expired, get a new one'));
$this->initToken();
}
else
throw $e;
}
}
}
else {
$this->logger->info($this->buildMsg('token initialization'));
$this->initToken();
}
}
protected function requestAnonymousToken() {
return $this->curlExec("https://www.elocky.com/oauth/v2/token", $this->getSecretIdFields() ."&grant_type=client_credentials");
}
protected function requestUserToken() {
return $this->curlExec("https://www.elocky.com/oauth/v2/token",
$this->getSecretIdFields() . "&grant_type=password&username=" . $this->username . "&password=" . $this->password);
}
protected function requestUserTokenRefresh() {
return $this->curlExec("https://www.elocky.com/oauth/v2/token",
$this->getSecretIdFields() . "&grant_type=refresh_token&refresh_token=" . $this->refresh_token);
}
/**
* Initialize an access token for this User.
* If username/password are set an authenticated access is requested. An anonymous one otherwise.
* @see User::$username
* @see User::$password
*/
protected function initToken() {
if (isset($this->username)) {
$this->logger->info($this->buildMsg('request an authenticated user access'));
$this->processToken($this->requestUserToken());
if (isset($this->update_token_func))
call_user_func($this->update_token_func);
}
else {
$this->logger->info($this->buildMsg('request an anonymous access'));
$this->processToken($this->requestAnonymousToken());
if (isset($this->update_token_func))
call_user_func($this->update_token_func);
}
}
/**
* Returns whether or not the token is valid.
* @return bool TRUE if token is still valid, FALSE if not
*/
protected function isTokenValid() {
return ($this->expiry_date > (new \DateTime())->add(new \DateInterval('PT60S')));
}
/**
* Execute a request to the Elocky server
* @param string $url request url to contact
* @param string $param request parameters
* @param bool $is_json set to true if the server response is supposed to be JSON formatted
* @throws \Exception if the Elocky servers returns a non JSON string; or if the Elocky server returned an error
* @return array JSON array
*/
protected function curlExec($url, $param, $is_json = true) {
$ch = curl_init($url . '?' . $param);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
if ($data === FALSE) {
throw new \Exception(json_encode(
array("error" => "connexion_error",
"error_description" => "cannot connect to the distant server")));
}
if (strlen($data) == 0) {
throw new \Exception(json_encode(array("error" => "data_error", "error_description" => "no data retrieved from the distant server")));
}
if ($is_json) {
$this->logger->debug($this->buildMsg('reception of ' . strval($data)));
$ret_data = json_decode($data, TRUE);
if (json_last_error() != JSON_ERROR_NONE) {
throw new \Exception(json_encode(array("error" => "json_error", "error_description" => json_last_error_msg())));
}
if (array_key_exists('error', $ret_data)) {
throw new \Exception($data);
}
}
else {
$this->logger->debug($this->buildMsg('reception of ' . strlen($data) . ' bytes'));
$ret_data = $data;
}
return $ret_data;
}
protected function getSecretIdFields() {
return "client_id=" . $this->client_id . "&client_secret=" . $this->client_secret;
}
private function processToken($_jsonArray) {
$this->access_token = $_jsonArray['access_token'];
if (array_key_exists('refresh_token', $_jsonArray))
$this->refresh_token = $_jsonArray['refresh_token'];
$this->expiry_date = (new \DateTime())->add(new \DateInterval('PT'.$_jsonArray['expires_in'].'S'));
}
/**
* Append the username (or anonymous if applicable)
* @param string $msg
* @return string
*/
private function buildMsg($msg) {
$name = isset($this->username) ? $this->username : 'anonymous';
return '[' . $name . '] ' . $msg;
}
}