xuanxuan.class.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. <?php
  2. include 'router.class.php';
  3. class xuanxuan extends router
  4. {
  5. /**
  6. * The input params.
  7. *
  8. * @var array
  9. * @access public
  10. */
  11. public $input = array();
  12. /**
  13. * The request params.
  14. *
  15. * @var array
  16. * @access public
  17. */
  18. public $params = array();
  19. /**
  20. * 构造方法, 设置路径,类,超级变量等。注意:
  21. * 1.应该使用createApp()方法实例化router类;
  22. * 2.如果$appRoot为空,框架会根据$appName计算应用路径。
  23. *
  24. * The construct function.
  25. * Prepare all the paths, classes, super objects and so on.
  26. * Notice:
  27. * 1. You should use the createApp() method to get an instance of the router.
  28. * 2. If the $appRoot is empty, the framework will compute the appRoot according the $appName
  29. *
  30. * @param string $appName the name of the app
  31. * @param string $appRoot the root path of the app
  32. * @access public
  33. * @return void
  34. */
  35. public function __construct($appName = 'sys', $appRoot = '')
  36. {
  37. parent::__construct($appName, $appRoot);
  38. $this->setViewType();
  39. $this->setXuanClientLang();
  40. $this->setXuanDebug();
  41. }
  42. /**
  43. * Set view type.
  44. *
  45. * @access public
  46. * @return void
  47. */
  48. public function setViewType()
  49. {
  50. $this->viewType = RUN_MODE == 'xuanxuan' ? 'json' : 'html';
  51. }
  52. /**
  53. * 根据用户浏览器的语言设置和服务器配置,选择显示的语言。
  54. * 优先级:$lang参数 > session > cookie > 浏览器 > 配置文件。
  55. *
  56. * Set the language.
  57. * Using the order of method $lang param, session, cookie, browser and the default lang.
  58. *
  59. * @param string $lang zh-cn|zh-tw|zh-hk|en
  60. * @access public
  61. * @return void
  62. */
  63. public function setXuanClientLang()
  64. {
  65. $row = $this->dbh->query('SELECT `value` FROM ' . TABLE_CONFIG . " WHERE `owner`='system' AND `module`='common' AND `section`='xuanxuan' AND `key`='backendLang'")->fetch();
  66. $lang = empty($row) ? 'zh-cn' : $row->value;
  67. parent::setClientLang($lang);
  68. }
  69. /**
  70. * Set debug.
  71. *
  72. * @access public
  73. * @return void
  74. */
  75. public function setXuanDebug()
  76. {
  77. $row = $this->dbh->query('SELECT `value` FROM ' . TABLE_CONFIG . " WHERE `owner`='system' AND `module`='common' AND `section`='xuanxuan' AND `key`='debug'")->fetch();
  78. $this->debug = empty($row) ? false : ($row->value == 1);
  79. }
  80. /**
  81. * Set input params.
  82. *
  83. * @access public
  84. * @return void
  85. */
  86. public function setInput()
  87. {
  88. if(RUN_MODE == 'xuanxuan')
  89. {
  90. $input = empty($_POST) ? file_get_contents("php://input") : $_POST;
  91. /* Decrypt only if AES is enabled. */
  92. $enableAES = $this->dbh->query('SELECT `value` FROM ' . TABLE_CONFIG . " WHERE `owner`='system' AND `module`='common' AND `section`='xuanxuan' AND `key`='aes'")->fetch();
  93. if(empty($enableAES) || $enableAES->value == 'on') $this->enableAES = true;
  94. if(!empty($enableAES) && $enableAES->value == 'off') $this->enableAES = false;
  95. if($this->enableAES) $this->initAES();
  96. $input = $this->decrypt($input);
  97. $this->input['rid'] = zget($input, 'rid' , '');
  98. $this->input['userID'] = zget($input, 'userID' , '');
  99. $this->input['client'] = zget($input, 'client' , '');
  100. $this->input['module'] = zget($input, 'module' , 'im');
  101. $this->input['method'] = zget($input, 'method' , '');
  102. $this->input['lang'] = zget($input, 'lang' , 'zh-cn');
  103. $this->input['params'] = zget($input, 'params' , array());
  104. $this->input['version'] = zget($input, 'version', '');
  105. $this->input['device'] = zget($input, 'device' , 'desktop');
  106. }
  107. else
  108. {
  109. $this->input['module'] = 'im';
  110. $this->input['method'] = 'debug';
  111. $this->input['params'] = array();
  112. }
  113. }
  114. /**
  115. * Init aes object.
  116. *
  117. * @access public
  118. * @return void
  119. */
  120. public function initAES()
  121. {
  122. $row = $this->dbh->query('SELECT `value` FROM ' . TABLE_CONFIG . " WHERE `owner`='system' AND `module`='common' AND `section`='xuanxuan' AND `key`='key'")->fetch();
  123. $key = $row->value;
  124. $iv = substr($key, 0, 16);
  125. $this->aes = $this->loadClass('phpaes');
  126. $this->aes->init($key, $iv);
  127. if($this->debug)
  128. {
  129. $this->log("engine: " . $this->aes->getEngine());
  130. }
  131. }
  132. /**
  133. * Set params.
  134. *
  135. * @param array $params
  136. * @access public
  137. * @return void
  138. */
  139. public function setParams($params = array())
  140. {
  141. $this->params = $params;
  142. }
  143. /**
  144. * 解析本次请求的入口方法,根据请求的类型(PATH_INFO GET),调用相应的方法。
  145. * The entrance of parseing request. According to the requestType, call related methods.
  146. *
  147. * @access public
  148. * @return void
  149. */
  150. public function parseRequest()
  151. {
  152. $this->setInput();
  153. extract($this->input);
  154. $module = strtolower($module);
  155. $method = strtolower($method);
  156. if(RUN_MODE == 'xuanxuan')
  157. {
  158. if(!isset($this->config->xuanxuan->enabledMethods[$module][$method]))
  159. {
  160. $data = new stdclass();
  161. $data->module = 'im';
  162. $data->method = 'error';
  163. $data->data = 'Illegal Request.';
  164. $this->output($this->encrypt($data));
  165. return false;
  166. }
  167. /* Check for default parameters of the method if params is an object instead of an array. */
  168. $filledWithDefaults = false;
  169. if(is_object($params)) // cannot check ($params !== array_values($params)) for now because the decoder could not tell if data type name is needed and the name is always set.
  170. {
  171. $inputParams = (object)$params;
  172. $defaultParams = $this->getFunctionParams($method, $module);
  173. $filledParams = array();
  174. foreach($defaultParams as $name => $defaultValue)
  175. {
  176. if(in_array($name, array('userID', 'version', 'device'))) continue;
  177. $filledParams[] = isset($inputParams->$name) ? $inputParams->$name : $defaultValue;
  178. }
  179. $filledWithDefaults = true;
  180. $params = $filledParams;
  181. }
  182. /* Unset servername param of handshake methods. */
  183. $handshakeMethods = array('userlogin', 'sysgetserverinfo');
  184. if(!$filledWithDefaults && $module == 'im' && in_array(strtolower($method), $handshakeMethods) && is_array($params)) unset($params[0]);
  185. if(is_array($params))
  186. {
  187. $params[] = $userID;
  188. $params[] = $version;
  189. $params[] = $device;
  190. }
  191. $this->session->set('userID', $userID);
  192. $this->session->set('clientIP', $client);
  193. $this->session->set('clientLang', $lang);
  194. }
  195. elseif($module != 'im' or $method != 'debug')
  196. {
  197. $this->output('Access Denied');
  198. return false;
  199. }
  200. $this->setModuleName($module);
  201. $this->setMethodName($method);
  202. $this->setParams($params);
  203. $this->setControlFile();
  204. return true;
  205. }
  206. /**
  207. * 使用反射机制获取函数参数的默认值。
  208. * Get the default settings of the method to be called using the reflecting.
  209. *
  210. * @param string $methodName
  211. * @param string $moduleName
  212. * @access public
  213. * @return array
  214. */
  215. public function getFunctionParams($methodName, $moduleName = 'im')
  216. {
  217. $control = $this->getExtensionRoot() . "xuan/" . $moduleName . DS . 'control.php';
  218. $moduleExtPaths = $this->getModuleExtPath($moduleName, 'control');
  219. if(!empty($moduleExtPaths))
  220. {
  221. $extActionFile = $moduleExtPaths['common'] . $methodName . '.php';
  222. if(file_exists($extActionFile))
  223. {
  224. $control = $extActionFile;
  225. }
  226. elseif(isset($moduleExtPaths['xuan']))
  227. {
  228. $extActionFile = $moduleExtPaths['xuan'] . $methodName . '.php';
  229. if(file_exists($extActionFile)) $control = $extActionFile;
  230. }
  231. }
  232. helper::cd(dirname($control));
  233. helper::import($control);
  234. helper::cd();
  235. $moduleName = class_exists("my$moduleName") ? "my$moduleName" : $moduleName;
  236. $defaultParams = array();
  237. $methodReflect = new reflectionMethod($moduleName, $methodName);
  238. foreach($methodReflect->getParameters() as $param)
  239. {
  240. $name = $param->getName();
  241. $default = '_NOT_SET';
  242. if($param->isDefaultValueAvailable()) $default = $param->getDefaultValue();
  243. $defaultParams[$name] = $default;
  244. }
  245. return $defaultParams;
  246. }
  247. /**
  248. * 加载一个模块:
  249. * 1. 引入控制器文件或扩展的方法文件;
  250. * 2. 创建control对象;
  251. * 3. 解析url,得到请求的参数;
  252. * 4. 使用call_user_function_array调用相应的方法。
  253. *
  254. * Load a module.
  255. * 1. include the control file or the extension action file.
  256. * 2. create the control object.
  257. * 3. set the params passed in through url.
  258. * 4. call the method by call_user_function_array
  259. *
  260. * @access public
  261. * @return bool|object if the module object of die.
  262. */
  263. public function loadModule()
  264. {
  265. $appName = $this->appName;
  266. $moduleName = $this->moduleName;
  267. $methodName = $this->methodName;
  268. /*
  269. * 引入该模块的control文件。
  270. * Include the control file of the module.
  271. **/
  272. $file2Included = $this->setActionExtFile() ? $this->extActionFile : $this->controlFile;
  273. chdir(dirname($file2Included));
  274. helper::import($file2Included);
  275. /*
  276. * 设置control的类名。
  277. * Set the class name of the control.
  278. **/
  279. $className = class_exists("my$moduleName") ? "my$moduleName" : $moduleName;
  280. if(!class_exists($className))
  281. {
  282. $this->triggerError("the control $className not found", __FILE__, __LINE__);
  283. return false;
  284. }
  285. /*
  286. * 创建control类的实例。
  287. * Create a instance of the control.
  288. **/
  289. $module = new $className();
  290. if(!method_exists($module, $methodName))
  291. {
  292. $this->triggerError("the module $moduleName has no $methodName method", __FILE__, __LINE__);
  293. return false;
  294. }
  295. /* If the db server restarted, must reset dbh. */
  296. $this->control = $module;
  297. /* include default value for module*/
  298. $defaultValueFiles = glob($this->getTmpRoot() . "defaultvalue/*.php");
  299. if($defaultValueFiles) foreach($defaultValueFiles as $file) include $file;
  300. /*
  301. * 使用反射机制获取函数参数的默认值。
  302. * Get the default settings of the method to be called using the reflecting.
  303. *
  304. * */
  305. $defaultParams = array();
  306. $methodReflect = new reflectionMethod($className, $methodName);
  307. foreach($methodReflect->getParameters() as $param)
  308. {
  309. $name = $param->getName();
  310. $default = '_NOT_SET';
  311. if(isset($paramDefaultValue[$appName][$className][$methodName][$name]))
  312. {
  313. $default = $paramDefaultValue[$appName][$className][$methodName][$name];
  314. }
  315. elseif(isset($paramDefaultValue[$className][$methodName][$name]))
  316. {
  317. $default = $paramDefaultValue[$className][$methodName][$name];
  318. }
  319. elseif($param->isDefaultValueAvailable())
  320. {
  321. $default = $param->getDefaultValue();
  322. }
  323. $defaultParams[$name] = $default;
  324. }
  325. /* Merge params. */
  326. $mergedParams = array();
  327. if(isset($this->params))
  328. {
  329. $mergedParams = $this->mergeParams($defaultParams, (array)$this->params);
  330. }
  331. else
  332. {
  333. $this->triggerError("param error: {$this->request->raw}", __FILE__, __LINE__);
  334. return false;
  335. }
  336. /* Call the method. */
  337. $this->response = call_user_func_array(array($module, $methodName), $mergedParams);
  338. return true;
  339. }
  340. /**
  341. * 合并请求的参数和默认参数,这样就可以省略已经有默认值的参数了。
  342. * Merge the params passed in and the default params. Thus the params which have default values needn't pass value, just like a function.
  343. *
  344. * @param array $defaultParams the default params defined by the method.
  345. * @param array $passedParams the params passed in through url.
  346. * @access public
  347. * @return array the merged params.
  348. */
  349. public function mergeParams($defaultParams, $passedParams)
  350. {
  351. /* Remove these two params. */
  352. unset($passedParams['HTTP_X_REQUESTED_WITH']);
  353. /* Check params from URL. */
  354. foreach($passedParams as $param => $value)
  355. {
  356. if(preg_match('/[^a-zA-Z0-9_\.]/', $param))
  357. {
  358. $this->output('Bad Request!');
  359. return array();
  360. }
  361. }
  362. $passedParams = array_values($passedParams);
  363. $i = 0;
  364. foreach($defaultParams as $key => $defaultValue)
  365. {
  366. if(isset($passedParams[$i]))
  367. {
  368. $defaultParams[$key] = $passedParams[$i];
  369. }
  370. else
  371. {
  372. if($defaultValue === '_NOT_SET') $this->triggerError("The param '$key' should pass value. ", __FILE__, __LINE__, $exit = true);
  373. }
  374. $i++;
  375. }
  376. return $defaultParams;
  377. }
  378. /**
  379. * Decrypt an input string.
  380. *
  381. * @param string $input
  382. * @access public
  383. * @return object
  384. */
  385. public function decrypt($input = '')
  386. {
  387. if($this->enableAES) $input = $this->aes->decrypt($input);
  388. if($this->debug) $this->log("decrypt: " . $input);
  389. $input = json_decode($input);
  390. if(!$input) $this->triggerError('Input data is not json.', __FILE__, __LINE__);
  391. if($input && is_object($input)) return $input;
  392. return $this->decodeInput($input);
  393. }
  394. /**
  395. * Encrypt an output object.
  396. *
  397. * @param mixed $output array | object
  398. * @access public
  399. * @return string
  400. */
  401. public function encrypt($output = null)
  402. {
  403. if(is_array($output) or is_object($output)) $output = json_encode($output);
  404. if($this->debug)
  405. {
  406. $this->log("encrypt: " . $output);
  407. }
  408. if($this->enableAES) $output = $this->aes->encrypt($output);
  409. return helper::removeUTF8Bom($output);
  410. }
  411. /**
  412. * Decode input params.
  413. *
  414. * @param array $input
  415. * @access public
  416. * @return array
  417. */
  418. public function decodeInput($inputArray)
  419. {
  420. list($api, $input) = $inputArray;
  421. $maps = zget($this->config->maps, $api, array());
  422. /* Using requestPack as fallback maps */
  423. if(empty($maps)) $maps = zget($this->config->maps, 'requestPack', array());
  424. if($this->debug && empty($maps))
  425. {
  426. $this->log("warning: decode maps is empty for api \"$api\"");
  427. }
  428. $decodedParams = self::decodeArray($maps, $input);
  429. if($this->debug)
  430. {
  431. $this->log("decode input($api): " . json_encode($decodedParams));
  432. }
  433. return $decodedParams;
  434. }
  435. /**
  436. * Decode array to assorted array.
  437. *
  438. * @param array $maps
  439. * @param array $data
  440. * @static
  441. * @access public
  442. * @return array
  443. */
  444. public static function decodeArray($maps, $data)
  445. {
  446. $params = array();
  447. if(empty($maps)) return array();
  448. /* $maps should be a type with dataType set. */
  449. foreach($maps['dataType'] as $key => $prop)
  450. {
  451. /* Skip extra dataTypes that do not exist in the $data array. */
  452. if(!isset($data[$key])) continue;
  453. /* Basic type may contain options that allow using an index to represent a value defined in the scheme. */
  454. if($prop['type'] == 'basic')
  455. {
  456. if(isset($prop['options']))
  457. {
  458. $params[$prop['name']] = zget($prop['options'], $data[$key]);
  459. }
  460. else
  461. {
  462. $params[$prop['name']] = zget($data, $key, '');
  463. }
  464. continue;
  465. }
  466. /* Object type may have a dataType of nested or mixed types. */
  467. if($prop['type'] == 'object')
  468. {
  469. $params[$prop['name']] = self::decodeArray($prop, $data[$key]);
  470. continue;
  471. }
  472. /* List type describes an array of its dataType instances. */
  473. if($prop['type'] == 'list')
  474. {
  475. $params[$prop['name']] = self::decodeArray(array('dataType' => array($prop['dataType'])), $data[$key]);
  476. }
  477. }
  478. return $params;
  479. }
  480. /**
  481. * Output message with echo.
  482. *
  483. * @param string $message
  484. * @access public
  485. * @return void
  486. */
  487. public function output($message)
  488. {
  489. echo $message;
  490. }
  491. /**
  492. * Save a log.
  493. *
  494. * @param string $log
  495. * @param string $file
  496. * @param string $line
  497. * @access public
  498. * @return void
  499. */
  500. public function log($message, $file = '', $line = '')
  501. {
  502. $log = "\n" . date('H:i:s') . " $message";
  503. if($file) $log .= " in <strong>$file</strong>";
  504. if($line) $log .= " on line <strong>$line</strong> ";
  505. $file = $this->getLogRoot() . 'xuanxuan.' . date('Ymd') . '.log.php';
  506. if(!is_file($file)) file_put_contents($file, "<?php\n die();\n?>\n");
  507. $fh = @fopen($file, 'a');
  508. if($fh) fwrite($fh, $log) && fclose($fh);
  509. }
  510. }