-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathClient.php
More file actions
738 lines (676 loc) · 22.7 KB
/
Copy pathClient.php
File metadata and controls
738 lines (676 loc) · 22.7 KB
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
<?php
namespace LeanCloud;
use LeanCloud\Bytes;
use LeanCloud\LeanObject;
use LeanCloud\ACL;
use LeanCloud\File;
use LeanCloud\User;
use LeanCloud\Operation\IOperation;
use LeanCloud\Storage\IStorage;
use LeanCloud\Storage\SessionStorage;
use LeanCloud\AppRouter;
/**
* Client interfacing with LeanCloud REST API
*
* The client is responsible for sending request to API, and parsing
* the response into objects in PHP. There are also utility functions
* such as `::randomFloat` to generate a random float number.
*
*/
class Client {
/**
* Client version
*/
const VERSION = '0.14.1';
/**
* API Version string
*
* @var string
*/
private static $apiVersion = "1.1";
/**
* API Timeout
*
* Default to 15 seconds
*
* @var int
*/
private static $apiTimeout = 15;
/**
* Application ID
*
* @var string
*/
private static $appId;
/**
* Application Key
*
* @var string
*/
private static $appKey;
/**
* Application master key
*
* @var string
*/
private static $appMasterKey;
/**
* Server url
*
* @var string
*/
private static $serverUrl;
/**
* Use master key or not
*
* @var bool
*/
private static $useMasterKey = false;
/**
* Is in production or not
*
* @var bool
*/
public static $isProduction = false;
/**
* Is in debug mode or not
*
* @var bool
*/
private static $debugMode = false;
/**
* Default request headers
*
* @var array
*/
private static $defaultHeaders;
/**
* Persistent key-value storage
*
* @var IStorage
*/
private static $storage;
/**
* Initialize application key and settings
*
* @param string $appId Application ID
* @param string $appKey Application key
* @param string $appMasterKey Application master key
*/
public static function initialize($appId, $appKey, $appMasterKey) {
self::$appId = $appId;
self::$appKey = $appKey;
self::$appMasterKey = $appMasterKey;
self::$defaultHeaders = array(
'X-LC-Id' => self::$appId,
'Content-Type' => 'application/json;charset=utf-8',
'Accept-Encoding' => 'gzip, deflate',
'User-Agent' => self::getVersionString()
);
// Use session storage by default
if (!self::$storage) {
self::$storage = new SessionStorage();
}
self::useProduction(getenv("LEANCLOUD_APP_ENV") == "production");
User::registerClass();
Role::registerClass();
}
/**
* Set a deadline for requests to complete.
*
* Note that file upload requests are not affected.
*
* @param integer $seconds
*/
public static function setApiTimeout($seconds) {
static::$apiTimeout = intval($seconds);
}
/**
* Assert client is correctly initialized
*
* @throws RuntimeException
*/
private static function assertInitialized() {
if (!isset(self::$appId) &&
!isset(self::$appKey) &&
!isset(self::$appMasterKey)) {
throw new \RuntimeException("Client is not initialized, " .
"please specify application key " .
"with Client::initialize.");
}
}
/**
* Get version string used as user agent
*
* @return string
*/
public static function getVersionString() {
return "LeanCloud PHP SDK " . self::VERSION;
}
/**
* Set API region
*
* See `LeanCloud\Region` for available regions.
*
* @param mixed $region
*/
public static function useRegion($region) {
self::assertInitialized();
AppRouter::getInstance(self::$appId)->setRegion($region);
}
/**
* Use production or not
*
* @param bool $flag Default false
*/
public static function useProduction($flag) {
self::$isProduction = $flag ? true : false;
}
/**
* Set debug mode
*
* Enable debug mode to log request params and response.
*
* @param bool $flag Default false
*/
public static function setDebug($flag) {
self::$debugMode = $flag ? true : false;
}
/**
* Use master key or not
*
* @param bool $flag
*/
public static function useMasterKey($flag) {
self::$useMasterKey = $flag ? true : false;
}
/**
* Set server url
*
* Explicitly set server url with which this client will communicate.
* Url shall be in the form of: `https://api.leancloud.cn` .
*
* @param string $url
*/
public static function setServerUrl($url) {
self::$serverUrl = rtrim($url, "/");
}
/**
* Get API Endpoint
*
* The returned endpoint will include version string.
* For example: https://api.leancloud.cn/1.1 .
*
* @return string
*/
public static function getAPIEndPoint() {
if ($url = self::$serverUrl) {
return $url . "/" . self::$apiVersion;
} else if ($url = getenv("LEANCLOUD_API_SERVER")) {
return $url . "/" . self::$apiVersion;
} else {
$region = getenv("LEANCLOUD_REGION");
$appIdPrefix = strtolower(substr(self::$appId, 0, 8));
if ($region == "US") {
return "https://{$appIdPrefix}.lncldglobal.com" . self::$apiVersion;
} else if (str_ends_with(self::$appId, "-MdYXbMMI")) {
return "https://{$appIdPrefix}.lncldglobal.com" . self::$apiVersion;
} else if (str_ends_with(self::$appId, "-9Nh9j0Va")) {
return "https://{$appIdPrefix}.lc-cn-e1-shared.com" . self::$apiVersion;
} else {
return "https://{$appIdPrefix}.lc-cn-n1-shared.com" . self::$apiVersion;
}
}
}
/**
* Build authentication headers
*
* @param string $sessionToken Session token of a User
* @param bool $useMasterKey
* @return array
*/
public static function buildHeaders($sessionToken, $useMasterKey) {
if (is_null($useMasterKey)) {
$useMasterKey = self::$useMasterKey;
}
$h = self::$defaultHeaders;
$h['X-LC-Prod'] = self::$isProduction ? 1 : 0;
$timestamp = time();
$key = $useMasterKey ? self::$appMasterKey : self::$appKey;
$sign = md5($timestamp . $key);
$h['X-LC-Sign'] = $sign . "," . $timestamp;
if ($useMasterKey) {
$h['X-LC-Sign'] .= ",master";
}
if (!$sessionToken) {
$sessionToken = User::getCurrentSessionToken();
}
if ($sessionToken) {
$h['X-LC-Session'] = $sessionToken;
}
return $h;
}
/**
* Verify app ID and sign
*
* The sign must be in the format of "{md5sum},{timestamp}[,master]",
* which follows the format as in header "X-LC-Sign".
*
* @param string $appId App Id
* @param string $sign Request sign
* @return bool
*/
public static function verifySign($appId, $sign) {
if (!$appId || ($appId != self::$appId)) {
return false;
}
$parts = explode(",", $sign);
$key = self::$appKey;
if (isset($parts[2]) && "master" === trim($parts[2])) {
$key = self::$appMasterKey;
}
return $parts[0] === md5(trim($parts[1]) . $key);
}
/**
* Verify app ID and key
*
* The key shall be in format of "{key}[,master]", it will be verified
* as master key if master suffix present.
*
* @param string $appId App Id
* @param string $key App key or master key
* @return bool
*/
public static function verifyKey($appId, $key) {
if (!$appId || ($appId != self::$appId)) {
return false;
}
$parts = explode(",", $key);
if (isset($parts[1]) && "master" === trim($parts[1])) {
return self::$appMasterKey === $parts[0];
}
return self::$appKey === $parts[0];
}
/**
* Generate a sign used to auth hook invocation on LeanEngine
*
* @param string $hookName E.g. "__before_for_Object"
* @param integer $msec Timestamap in microseconds
* @return string
*/
public static function signHook($hookName, $msec) {
$hash = hash_hmac("sha1", "{$hookName}:{$msec}", self::$appMasterKey);
return "{$msec},{$hash}";
}
/**
* Verify a signed hook
*
* @param string $hookName
* @param string $sign
* @return bool
*/
public static function verifyHookSign($hookName, $sign) {
if ($sign) {
$parts = explode(",", $sign);
$msec = $parts[0];
return self::signHook($hookName, $msec) === $sign;
}
return false;
}
/**
* Issue request to LeanCloud
*
* The data is passing in as an associative array, which will be encoded
* into JSON if the content-type header is "application/json", or
* be appended to url as query string if it's GET request.
*
* The optional headers do have higher precedence, if provided it
* will overwrite the items in default headers.
*
* @param string $method GET, POST, PUT, DELETE
* @param string $path Request path (without version string)
* @param array $data Payload data
* @param string $sessionToken Session token of a User
* @param array $headers Optional headers
* @param bool $useMasterkey Use master key or not
* @return array JSON decoded associative array
* @throws RuntimeException, CloudException
*/
public static function request($method, $path, $data,
$sessionToken=null,
$headers=array(),
$useMasterKey=null) {
self::assertInitialized();
$url = self::getAPIEndPoint();
$url .= $path;
$defaultHeaders = self::buildHeaders($sessionToken, $useMasterKey);
if (empty($headers)) {
$headers = $defaultHeaders;
} else {
$headers = array_merge($defaultHeaders, $headers);
}
if (strpos($headers["Content-Type"], "/json") !== false) {
$json = json_encode($data);
}
// Build headers list in HTTP format
$headersList = array_map(function($key, $val) { return "$key: $val";},
array_keys($headers),
$headers);
$req = curl_init($url);
curl_setopt($req, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($req, CURLOPT_HTTPHEADER, $headersList);
curl_setopt($req, CURLOPT_RETURNTRANSFER, true);
curl_setopt($req, CURLOPT_TIMEOUT, self::$apiTimeout);
// curl_setopt($req, CURLINFO_HEADER_OUT, true);
// curl_setopt($req, CURLOPT_HEADER, true);
curl_setopt($req, CURLOPT_ENCODING, '');
switch($method) {
case "GET":
if ($data) {
// append GET data as query string
$url .= "?" . http_build_query($data);
curl_setopt($req, CURLOPT_URL, $url);
}
break;
case "POST":
curl_setopt($req, CURLOPT_POST, 1);
curl_setopt($req, CURLOPT_POSTFIELDS, $json);
break;
case "PUT":
curl_setopt($req, CURLOPT_POSTFIELDS, $json);
curl_setopt($req, CURLOPT_CUSTOMREQUEST, $method);
case "DELETE":
curl_setopt($req, CURLOPT_CUSTOMREQUEST, $method);
break;
default:
break;
}
$reqId = rand(100,999);
if (self::$debugMode) {
error_log("[DEBUG] HEADERS {$reqId}:" . json_encode($headersList));
error_log("[DEBUG] REQUEST {$reqId}: {$method} {$url} {$json}");
}
// list($headers, $resp) = explode("\r\n\r\n", curl_exec($req), 2);
$resp = curl_exec($req);
$respCode = curl_getinfo($req, CURLINFO_HTTP_CODE);
$respType = curl_getinfo($req, CURLINFO_CONTENT_TYPE);
$error = curl_error($req);
$errno = curl_errno($req);
curl_close($req);
if (self::$debugMode) {
error_log("[DEBUG] RESPONSE {$reqId}: {$resp}");
}
/** type of error:
* - curl connection error
* - http status error 4xx, 5xx
* - rest api error
*/
if ($errno > 0) {
throw new \RuntimeException("CURL connection ($url) error: " .
"$errno $error",
$errno);
}
if (strpos($respType, "text/html") !== false) {
throw new CloudException("Bad response type text/html", -1, $respCode,
$method, $url);
}
$data = json_decode($resp, true);
if (isset($data["error"])) {
$code = isset($data["code"]) ? $data["code"] : -1;
throw new CloudException("{$data['error']}", $code, $respCode,
$method, $url);
}
return $data;
}
/**
* Issue GET request to LeanCloud
*
* @param string $path Request path (without version string)
* @param array $data Payload data
* @param string $sessionToken Session token of a User
* @param array $headers Optional headers
* @param bool $useMasterkey Use master key or not
* @return array JSON decoded associated array
* @see self::request()
*/
public static function get($path, $data=null, $sessionToken=null,
$headers=array(), $useMasterKey=null) {
return self::request("GET", $path, $data, $sessionToken,
$headers, $useMasterKey);
}
/**
* Issue POST request to LeanCloud
*
* @param string $path Request path (without version string)
* @param array $data Payload data
* @param string $sessionToken Session token of a User
* @param array $headers Optional headers
* @param bool $useMasterkey Use master key or not, optional
* @return array JSON decoded associated array
* @see self::request()
*/
public static function post($path, $data, $sessionToken=null,
$headers=array(), $useMasterKey=null) {
return self::request("POST", $path, $data, $sessionToken,
$headers, $useMasterKey);
}
/**
* Issue PUT request to LeanCloud
*
* @param string $path Request path (without version string)
* @param array $data Payload data
* @param string $sessionToken Session token of a User
* @param array $headers Optional headers
* @param bool $useMasterkey Use master key or not, optional
* @return array JSON decoded associated array
* @see self::request()
*/
public static function put($path, $data, $sessionToken=null,
$headers=array(), $useMasterKey=null) {
return self::request("PUT", $path, $data, $sessionToken,
$headers, $useMasterKey);
}
/**
* Issue DELETE request to LeanCloud
*
* @param string $path Request path (without version string)
* @param string $sessionToken Session token of a User
* @param array $headers Optional headers
* @param bool $useMasterkey Use master key or not, optional
* @return array JSON decoded associated array
* @see self::request()
*/
public static function delete($path, $sessionToken=null,
$headers=array(), $useMasterKey=null) {
return self::request("DELETE", $path, null, $sessionToken,
$headers, $useMasterKey);
}
/**
* Issue a batch request
*
* @param array $requests Array of requests in batch op
* @param string $sessionToken Session token of a User
* @param array $headers Optional headers
* @param bool $useMasterkey Use master key or not, optional
* @return array JSON decoded associated array
* @see self::request()
*/
public static function batch($requests, $sessionToken=null,
$headers=array(), $useMasterKey=null) {
$response = Client::post("/batch",
array("requests" => $requests),
$sessionToken,
$headers,
$useMasterKey);
$batchRequestError = new BatchRequestError();
forEach($requests as $i => $req) {
if (isset($response[$i]["error"])) {
$batchRequestError->add($req, $response[$i]["error"]);
}
}
if (!$batchRequestError->isEmpty()) {
throw $batchRequestError;
}
return $response;
}
/**
* Recursively encode value as JSON representation
*
* By default LeanObject will be encoded as pointer, though
* `$encoder` could be provided to encode to customized type, such
* as full `__type` annotated json object. The $encoder must be
* name of instance method of object.
*
* To avoid infinite loop in the case of circular object
* references, previously seen objects (`$seen`) are encoded
* in pointer, even a customized encoder was provided.
*
* ```php
* $obj = new TestObject();
* $obj->set("owner", $user);
*
* // encode object to full JSON, with `__type` and `className`
* Client::encode($obj, "toFullJSON");
*
* // encode object to literal JSON, without `__type` and `className`
* Client::encode($obj, "toJSON");
* ```
*
* @param mixed $value
* @param string $encoder Object encoder name, e.g.: getPointer, toJSON
* @param array $seen Array of Object that has been traversed
* @return mixed
*/
public static function encode($value,
$encoder=null,
$seen=array()) {
if (is_null($value) || is_scalar($value)) {
return $value;
} else if (($value instanceof \DateTime) ||
($value instanceof \DateTimeImmutable)) {
return array("__type" => "Date",
"iso" => self::formatDate($value));
} else if ($value instanceof LeanObject) {
if ($encoder && $value->hasData() && !in_array($value, $seen)) {
$seen[] = $value;
return call_user_func(array($value, $encoder), $seen);
} else {
return $value->getPointer();
}
} else if ($value instanceof IOperation ||
$value instanceof GeoPoint ||
$value instanceof Bytes ||
$value instanceof ACL ||
$value instanceof Relation ||
$value instanceof File) {
return $value->encode();
} else if (is_array($value)) {
$res = array();
forEach($value as $key => $val) {
$res[$key] = self::encode($val, $encoder, $seen);
}
return $res;
} else {
throw new \RuntimeException("Dont know how to encode " .
gettype($value));
}
}
/**
* Format date according to LeanCloud spec.
*
* @param DateTime $date
* @return string
*/
public static function formatDate($date) {
$utc = clone $date;
$utc->setTimezone(new \DateTimezone("UTC"));
$iso = $utc->format("Y-m-d\TH:i:s.u");
// Milliseconds precision is required for server to correctly parse time,
// thus we have to chop off last 3 microseconds to milliseconds.
$iso = substr($iso, 0, 23) . "Z";
return $iso;
}
/**
* Decode value from LeanCloud response.
*
* @param mixed $value Value to decode
* @param string $key Field key for the value
* @return mixed
*/
public static function decode($value, $key) {
if (!is_array($value)) {
return $value;
}
if ($key === 'ACL') {
return new ACL($value);
}
if (!isset($value["__type"])) {
$out = array();
forEach($value as $k => $v) {
$out[$k] = self::decode($v, $k);
}
return $out;
}
// Parse different data type from server.
$type = $value["__type"];
if ($type === "Date") {
// return time in default time zone
$date = new \DateTime($value["iso"]);
$date->setTimezone(new \DateTimeZone(date_default_timezone_get()));
return $date;
}
if ($type === "Bytes") {
return Bytes::createFromBase64Data($value["base64"]);
}
if ($type === "GeoPoint") {
return new GeoPoint($value["latitude"], $value["longitude"]);
}
if ($type === "File") {
$file = new File($value["name"]);
$file->mergeAfterFetch($value);
return $file;
}
if ($type === "Pointer" || $type === "Object") {
$id = isset($value["objectId"]) ? $value["objectId"] : null;
$obj = LeanObject::create($value["className"], $id);
unset($value["__type"]);
unset($value["className"]);
if (!empty($value)) {
$obj->mergeAfterFetch($value);
}
return $obj;
}
if ($type === "Relation") {
return new Relation(null, $key, $value["className"]);
}
}
/**
* Get storage
*
* @return IStorage
*/
public static function getStorage() {
return self::$storage;
}
/**
* Set storage
*
* It unset the storage if $storage is null.
*
* @param IStorage $storage
*/
public static function setStorage($storage) {
self::$storage = $storage;
}
/**
* Generate a random float between [$min, $max)
*
* @param float $min
* @param float $max
* @return float
*/
public static function randomFloat($min=0, $max=1) {
$M = mt_getrandmax();
return $min + (mt_rand(0, $M - 1) / $M) * ($max - $min);
}
}