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:
<?php
namespace LeanCloud\Engine;
use LeanCloud\Client;
use LeanCloud\User;
use LeanCloud\CloudException;
class LeanEngine {
private static $allowedHeaders = array(
'X-LC-Id', 'X-LC-Key', 'X-LC-Session', 'X-LC-Sign', 'X-LC-Prod',
'X-LC-UA',
'X-Uluru-Application-Key',
'X-Uluru-Application-Id',
'X-Uluru-Application-Production',
'X-Uluru-Client-Version',
'X-Uluru-Session-Token',
'X-AVOSCloud-Application-Key',
'X-AVOSCloud-Application-Id',
'X-AVOSCloud-Application-Production',
'X-AVOSCloud-Client-Version',
'X-AVOSCloud-Super-Key',
'X-AVOSCloud-Session-Token',
'X-AVOSCloud-Request-sign',
'X-Requested-With',
'Content-Type'
);
protected static $useHttpsRedirect = false;
protected $env = array();
protected function getHeaderLine($key) {
if (isset($_SERVER[$key])) {
return $_SERVER[$key];
}
return null;
}
protected function withHeader($key, $val) {
header("{$key}: {$val}");
return $this;
}
protected function send($body, $status) {
http_response_code($status);
echo $body;
exit;
}
protected function redirect($url) {
http_response_code(302);
header("Location: {$url}");
exit;
}
protected function getBody() {
$body = file_get_contents("php://input");
return $body;
}
private function renderJSON($data=null, $status=200) {
$out = is_null($data) ? "" : json_encode($data);
$this->withHeader("Content-Type",
"application/json; charset=utf-8;")
->send($out, $status);
}
private function renderError($message, $code=1, $status=400) {
$data = json_encode(array(
"code" => $code,
"error" => $message
));
$this->withHeader("Content-Type", "application; charset=utf-8;")
->send($data, $status);
}
private function retrieveHeader($keys) {
$val = null;
forEach($keys as $k) {
$val = $this->getHeaderLine($k);
if (!empty($val)) {
return $val;
}
}
return $val;
}
private function parseHeaders() {
$this->env["ORIGIN"] = $this->retrieveHeader(array(
"ORIGIN",
"HTTP_ORIGIN"
));
$this->env["CONTENT_TYPE"] = $this->retrieveHeader(array(
"CONTENT_TYPE",
"HTTP_CONTENT_TYPE"
));
$this->env["REMOTE_ADDR"] = $this->retrieveHeader(array(
"X_REAL_IP",
"HTTP_X_REAL_IP",
"X_FORWARDED_FOR",
"HTTP_X_FORWARDED_FOR",
"REMOTE_ADDR"
));
$this->env["LC_ID"] = $this->retrieveHeader(array(
"X_LC_ID",
"HTTP_X_LC_ID",
"X_AVOSCLOUD_APPLICATION_ID",
"HTTP_X_AVOSCLOUD_APPLICATION_ID",
"X_ULURU_APPLICATION_ID",
"HTTP_X_ULURU_APPLICATION_ID"
));
$this->env["LC_KEY"] = $this->retrieveHeader(array(
"X_LC_KEY",
"HTTP_X_LC_KEY",
"X_AVOSCLOUD_APPLICATION_KEY",
"HTTP_X_AVOSCLOUD_APPLICATION_KEY",
"X_ULURU_APPLICATION_KEY",
"HTTP_X_ULURU_APPLICATION_KEY"
));
$this->env["LC_MASTER_KEY"] = $this->retrieveHeader(array(
"X_AVOSCLOUD_MASTER_KEY",
"HTTP_X_AVOSCLOUD_MASTER_KEY",
"X_ULURU_MASTER_KEY",
"HTTP_X_ULURU_MASTER_KEY"
));
$this->env["LC_SESSION"] = $this->retrieveHeader(array(
"X_LC_SESSION",
"HTTP_X_LC_SESSION",
"X_AVOSCLOUD_SESSION_TOKEN",
"HTTP_X_AVOSCLOUD_SESSION_TOKEN",
"X_ULURU_SESSION_TOKEN",
"HTTP_X_ULURU_SESSION_TOKEN"
));
$this->env["LC_SIGN"] = $this->retrieveHeader(array(
"X_LC_SIGN",
"HTTP_X_LC_SIGN",
"X_AVOSCLOUD_REQUEST_SIGN",
"HTTP_X_AVOSCLOUD_REQUEST_SIGN"
));
$prod = $this->retrieveHeader(array(
"X_LC_PROD",
"HTTP_X_LC_PROD",
"X_AVOSCLOUD_APPLICATION_PRODUCTION",
"HTTP_X_AVOSCLOUD_APPLICATION_PRODUCTION",
"X_ULURU_APPLICATION_PRODUCTION",
"HTTP_X_ULURU_APPLICATION_PRODUCTION"
));
$this->env["useProd"] = true;
if ($prod === 0 || $prod === false) {
$this->env["useProd"] = false;
}
$this->env["useMaster"] = false;
}
private function parsePlainBody($body) {
$data = json_decode($body, true);
if (!empty($data)) {
$this->env["LC_ID"] = isset($data["_ApplicationId"]) ?
$data["_ApplicationId"] : null;
$this->env["LC_KEY"] = isset($data["_ApplicationKey"]) ?
$data["_ApplicationKey"] : null;
$this->env["LC_MASTER_KEY"] = isset($data["_MasterKey"]) ?
$data["_MasterKey"] : null;
$this->env["LC_SESSION"] = isset($data["_SessionToken"]) ?
$data["_SessionToken"] : null;
$this->env["LC_SIGN"] = null;
$this->env["useProd"] = isset($data["_ApplicationProduction"]) ?
(true && $data["_ApplicationProduction"]) :
true;
$this->env["useMaster"] = false;
forEach($data as $key) {
if ($key[0] === "_" && $key[1] !== "_") {
unset($data[$key]);
}
}
}
return $data;
}
private function authRequest() {
$appId = $this->env["LC_ID"];
$sign = $this->env["LC_SIGN"];
if ($sign && Client::verifySign($appId, $sign)) {
if (strpos($sign, "master") !== false) {
$this->env["useMaster"] = true;
}
return true;
}
$appKey = $this->env["LC_KEY"];
if ($appKey && Client::verifyKey($appId, $appKey)) {
if (strpos($appKey, "master") !== false) {
$this->env["useMaster"] = true;
}
return true;
}
$masterKey = $this->env["LC_MASTER_KEY"];
$key = "{$masterKey}, master";
if ($masterKey && Client::verifyKey($appId, $key)) {
$this->env["useMaster"] = true;
return true;
}
$this->renderError("Unauthorized", 401, 401);
}
private function verifyHookSign($hookName, $sign){
if (Client::verifyHookSign($hookName, $sign)) return true;
error_log("Invalid hook sign for {$hookName}");
$this->renderError("Unauthorized", 142, 401);
}
private function processSession() {
$token = $this->env["LC_SESSION"];
if ($token) {
User::become($token);
}
}
private function __dispatch($method, $url) {
if (static::$useHttpsRedirect) {
$this->httpsRedirect();
}
$path = parse_url($url, PHP_URL_PATH);
$path = rtrim($path, "/");
if (strpos($path, "/__engine/1/ping") === 0) {
$this->renderJSON(array(
"runtime" => "php-" . phpversion(),
"version" => Client::VERSION
));
}
$this->parseHeaders();
$pathParts = array();
if (preg_match("/^\/(1|1\.1)\/(functions|call)(.*)/",
$path,
$pathParts) === 1) {
$pathParts["version"] = $pathParts[1];
$pathParts["endpoint"] = $pathParts[2];
$pathParts["extra"] = $pathParts[3];
$origin = $this->env["ORIGIN"];
$this->withHeader("Access-Control-Allow-Origin",
$origin ? $origin : "*");
if ($method == "OPTIONS") {
$this->withHeader("Access-Control-Max-Age", 86400)
->withHeader("Access-Control-Allow-Methods",
"PUT, GET, POST, DELETE, OPTIONS")
->withHeader("Access-Control-Allow-Headers",
implode(", ", self::$allowedHeaders))
->withHeader("Content-Length", 0)
->renderJSON();
}
$body = $this->getBody();
if (preg_match("/text\/plain/", $this->env["CONTENT_TYPE"])) {
$json = $this->parsePlainBody($body);
} else {
$json = json_decode($body, true);
}
$this->authRequest();
$this->processSession();
if (strpos($pathParts["extra"], "/_ops/metadatas") === 0) {
if ($this->env["useMaster"]) {
$this->renderJSON(array("result" => Cloud::getKeys()));
} else {
$this->renderError("Unauthorized.", 401, 401);
}
}
$funcParams = explode("/", ltrim($pathParts["extra"], "/"));
if (count($funcParams) == 1) {
$this->dispatchFunc($funcParams[0], $json,
$pathParts["endpoint"] === "call");
} else {
if ($funcParams[0] == "onVerified") {
$this->dispatchOnVerified($funcParams[1], $json);
} else if ($funcParams[0] == "_User" &&
$funcParams[1] == "onLogin") {
$this->dispatchOnLogin($json);
} else if ($funcParams[0] == "BigQuery" ||
$funcParams[0] == "Insight") {
$this->dispatchOnInsight($json);
} else if (count($funcParams) == 2) {
$this->dispatchHook($funcParams[0], $funcParams[1], $json);
}
}
}
}
private function dispatchFunc($funcName, $body, $decodeObj=false) {
if (in_array($funcName, array(
'_messageReceived', '_receiversOffline', '_messageSent', '_messageUpdate',
'_conversationStart', '_conversationStarted',
'_conversationAdd', '_conversationAdded', '_conversationRemove', '_conversationRemoved', '_conversationUpdate',
'_clientOnline', '_clientOffline', '_rtmClientSign'
))) {
static::verifyHookSign($funcName, $body["__sign"]);
}
$params = $body;
if ($decodeObj) {
$params = Client::decode($body, null);
}
$meta["remoteAddress"] = $this->env["REMOTE_ADDR"];
$result = Cloud::run($funcName,
$params,
User::getCurrentUser(),
$meta);
if ($decodeObj) {
$out = Client::encode($result, "toFullJSON");
} else {
$out = Client::encode($result, "toJSON");
}
$this->renderJSON(array("result" => $out));
}
private function dispatchHook($className, $hookName, $body) {
$verified = false;
if (strpos($hookName, "before") === 0) {
$this->verifyHookSign("__before_for_{$className}",
$body["object"]["__before"]);
} else {
$this->verifyHookSign("__after_for_{$className}",
$body["object"]["__after"]);
}
$json = $body["object"];
$json["__type"] = "Object";
$json["className"] = $className;
$obj = Client::decode($json, null);
if (strpos($hookName, "before") === 0) {
if (isset($json["__before"])) {
$obj->set("__before", $json["__before"]);
} else {
$obj->disableBeforeHook();
}
} else {
if (isset($json["__after"])) {
$obj->set("__after", $json["__after"]);
} else {
$obj->disableAfterHook();
}
}
if (isset($json["_updatedKeys"])) {
$obj->updatedKeys = $json["_updatedKeys"];
}
$meta["remoteAddress"] = $this->env["REMOTE_ADDR"];
$result = Cloud::runHook($className,
$hookName,
$obj,
User::getCurrentUser(),
$meta);
if ($hookName == "beforeDelete") {
$this->renderJSON(array());
} else if (strpos($hookName, "after") === 0) {
$this->renderJSON(array("result" => "ok"));
} else {
$this->renderJSON($obj->toJSON());
}
}
private function dispatchOnVerified($type, $body) {
$this->verifyHookSign("__on_verified_{$type}",
$body["object"]["__sign"]);
$userObj = Client::decode($body["object"], null);
User::saveCurrentUser($userObj);
$meta["remoteAddress"] = $this->env["REMOTE_ADDR"];
Cloud::runOnVerified($type, $userObj, $meta);
$this->renderJSON(array("result" => "ok"));
}
private function dispatchOnLogin($body) {
$this->verifyHookSign("__on_login__User",
$body["object"]["__sign"]);
$userObj = Client::decode($body["object"], null);
$meta["remoteAddress"] = $this->env["REMOTE_ADDR"];
Cloud::runOnLogin($userObj, $meta);
$this->renderJSON(array("result" => "ok"));
}
private function dispatchOnInsight($body) {
$this->verifyHookSign("__on_complete_bigquery_job",
$body["__sign"]);
$meta["remoteAddress"] = $this->env["REMOTE_ADDR"];
Cloud::runOnInsight($body, $meta);
$this->renderJSON(array("result" => "ok"));
}
protected function dispatch($method, $url) {
try {
$this->__dispatch($method, $url);
} catch (FunctionError $ex) {
$status = (int) $ex->status;
if ( $status >= 500) {
error_log($ex);
error_log($ex->getTraceAsString());
}
$this->renderError("{$ex->getMessage()}", $ex->getCode(), $ex->status);
} catch (CloudException $ex) {
error_log($ex);
error_log($ex->getTraceAsString());
$this->renderError("{$ex->getMessage()}", $ex->getCode(), $ex->status);
} catch (\Exception $ex) {
error_log($ex);
error_log($ex->getTraceAsString());
$this->renderError($ex->getMessage(),
$ex->getCode() ? $ex->getCode() : 1,
500);
}
}
public function start() {
$this->dispatch($_SERVER["REQUEST_METHOD"],
$_SERVER["REQUEST_URI"]);
}
private function httpsRedirect() {
$reqProto = $this->getHeaderLine("HTTP_X_FORWARDED_PROTO");
if ($reqProto === "http" &&
in_array(getenv("LEANCLOUD_APP_ENV"), array("production", "stage"))) {
$url = "https://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$this->redirect($url);
}
}
public static function enableHttpsRedirect() {
static::$useHttpsRedirect = true;
}
}