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:
<?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;
class Client {
const VERSION = '0.14.0';
private static $apiVersion = "1.1";
private static $apiTimeout = 15;
private static $appId;
private static $appKey;
private static $appMasterKey;
private static $serverUrl;
private static $useMasterKey = false;
public static $isProduction = false;
private static $debugMode = false;
private static $defaultHeaders;
private static $storage;
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()
);
if (!self::$storage) {
self::$storage = new SessionStorage();
}
self::useProduction(getenv("LEANCLOUD_APP_ENV") == "production");
User::registerClass();
Role::registerClass();
}
public static function setApiTimeout($seconds) {
static::$apiTimeout = intval($seconds);
}
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.");
}
}
public static function getVersionString() {
return "LeanCloud PHP SDK " . self::VERSION;
}
public static function useRegion($region) {
self::assertInitialized();
AppRouter::getInstance(self::$appId)->setRegion($region);
}
public static function useProduction($flag) {
self::$isProduction = $flag ? true : false;
}
public static function setDebug($flag) {
self::$debugMode = $flag ? true : false;
}
public static function useMasterKey($flag) {
self::$useMasterKey = $flag ? true : false;
}
public static function setServerUrl($url) {
self::$serverUrl = rtrim($url, "/");
}
public static function getAPIEndPoint() {
if ($url = self::$serverUrl) {
return $url . "/" . self::$apiVersion;
} else if ($url = getenv("LEANCLOUD_API_SERVER")) {
return $url . "/" . self::$apiVersion;
} else {
$host = AppRouter::getInstance(self::$appId)->getRoute(AppRouter::API_SERVER_KEY);
return "https://{$host}/" . self::$apiVersion;
}
}
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;
}
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);
}
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];
}
public static function signHook($hookName, $msec) {
$hash = hash_hmac("sha1", "{$hookName}:{$msec}", self::$appMasterKey);
return "{$msec},{$hash}";
}
public static function verifyHookSign($hookName, $sign) {
if ($sign) {
$parts = explode(",", $sign);
$msec = $parts[0];
return self::signHook($hookName, $msec) === $sign;
}
return false;
}
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);
}
$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, CURLOPT_ENCODING, '');
switch($method) {
case "GET":
if ($data) {
$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}");
}
$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}");
}
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;
}
public static function get($path, $data=null, $sessionToken=null,
$headers=array(), $useMasterKey=null) {
return self::request("GET", $path, $data, $sessionToken,
$headers, $useMasterKey);
}
public static function post($path, $data, $sessionToken=null,
$headers=array(), $useMasterKey=null) {
return self::request("POST", $path, $data, $sessionToken,
$headers, $useMasterKey);
}
public static function put($path, $data, $sessionToken=null,
$headers=array(), $useMasterKey=null) {
return self::request("PUT", $path, $data, $sessionToken,
$headers, $useMasterKey);
}
public static function delete($path, $sessionToken=null,
$headers=array(), $useMasterKey=null) {
return self::request("DELETE", $path, null, $sessionToken,
$headers, $useMasterKey);
}
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;
}
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));
}
}
public static function formatDate($date) {
$utc = clone $date;
$utc->setTimezone(new \DateTimezone("UTC"));
$iso = $utc->format("Y-m-d\TH:i:s.u");
$iso = substr($iso, 0, 23) . "Z";
return $iso;
}
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;
}
$type = $value["__type"];
if ($type === "Date") {
$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"]);
}
}
public static function getStorage() {
return self::$storage;
}
public static function setStorage($storage) {
self::$storage = $storage;
}
public static function randomFloat($min=0, $max=1) {
$M = mt_getrandmax();
return $min + (mt_rand(0, $M - 1) / $M) * ($max - $min);
}
}