Api.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. <?php
  2. namespace app\common\controller;
  3. use app\common\library\Auth;
  4. use think\Config;
  5. use think\exception\HttpResponseException;
  6. use think\exception\ValidateException;
  7. use think\Hook;
  8. use think\Lang;
  9. use think\Loader;
  10. use think\Request;
  11. use think\Response;
  12. use think\Validate;
  13. /**
  14. * API控制器基类
  15. */
  16. class Api
  17. {
  18. /**
  19. * @var Request Request 实例
  20. */
  21. protected $request;
  22. /**
  23. * @var bool 验证失败是否抛出异常
  24. */
  25. protected $failException = false;
  26. /**
  27. * @var bool 是否批量验证
  28. */
  29. protected $batchValidate = false;
  30. /**
  31. * @var array 前置操作方法列表
  32. */
  33. protected $beforeActionList = [];
  34. /**
  35. * 无需登录的方法,同时也就不需要鉴权了
  36. * @var array
  37. */
  38. protected $noNeedLogin = [];
  39. /**
  40. * 无需鉴权的方法,但需要登录
  41. * @var array
  42. */
  43. protected $noNeedRight = ['*'];
  44. /**
  45. * 权限Auth
  46. * @var Auth
  47. */
  48. protected $auth = null;
  49. /**
  50. * 默认响应输出类型,支持json/xml
  51. * @var string
  52. */
  53. protected $responseType = 'json';
  54. /**
  55. * 快速搜索时执行查找的字段
  56. */
  57. protected $searchFields = 'id';
  58. /**
  59. * 是否是关联查询
  60. */
  61. protected $relationSearch = false;
  62. /**
  63. * 构造方法
  64. * @access public
  65. * @param Request $request Request 对象
  66. */
  67. public function __construct(Request $request = null)
  68. {
  69. $this->request = is_null($request) ? Request::instance() : $request;
  70. // 控制器初始化
  71. $this->_initialize();
  72. // 前置操作方法
  73. if ($this->beforeActionList) {
  74. foreach ($this->beforeActionList as $method => $options) {
  75. is_numeric($method) ?
  76. $this->beforeAction($options) :
  77. $this->beforeAction($method, $options);
  78. }
  79. }
  80. }
  81. /**
  82. * 初始化操作
  83. * @access protected
  84. */
  85. protected function _initialize()
  86. {
  87. //跨域请求检测
  88. check_cors_request();
  89. // 检测IP是否允许
  90. check_ip_allowed();
  91. //移除HTML标签
  92. $this->request->filter('trim,strip_tags,htmlspecialchars');
  93. $this->auth = Auth::instance();
  94. $modulename = $this->request->module();
  95. $controllername = Loader::parseName($this->request->controller());
  96. $actionname = strtolower($this->request->action());
  97. //$token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
  98. $token = $this->request->server('HTTP_TOKEN', $this->request->header('session-token'));
  99. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  100. // 设置当前请求的URI
  101. $this->auth->setRequestUri($path);
  102. // 检测是否需要验证登录
  103. if (!$this->auth->match($this->noNeedLogin)) {
  104. //初始化
  105. $this->auth->init($token);
  106. //检测是否登录
  107. if (!$this->auth->isLogin()) {
  108. $this->error(__('Please login first'), null, 401);
  109. }
  110. // 判断是否需要验证权限
  111. if (!$this->auth->match($this->noNeedRight)) {
  112. // 判断控制器和方法判断是否有对应权限
  113. if (!$this->auth->check($path)) {
  114. $this->error(__('You have no permission'), null, 403);
  115. }
  116. }
  117. } else {
  118. // 如果有传递token才验证是否登录状态
  119. if ($token) {
  120. $this->auth->init($token);
  121. }
  122. }
  123. $upload = \app\common\model\Config::upload();
  124. // 上传信息配置后
  125. Hook::listen("upload_config_init", $upload);
  126. Config::set('upload', array_merge(Config::get('upload'), $upload));
  127. // 加载当前控制器语言包
  128. $this->loadlang($controllername);
  129. }
  130. /**
  131. * 加载语言文件
  132. * @param string $name
  133. */
  134. protected function loadlang($name)
  135. {
  136. $name = Loader::parseName($name);
  137. $name = preg_match("/^([a-zA-Z0-9_\.\/]+)\$/i", $name) ? $name : 'index';
  138. $lang = $this->request->langset();
  139. $lang = preg_match("/^([a-zA-Z\-_]{2,10})\$/i", $lang) ? $lang : 'zh-cn';
  140. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $lang . '/' . str_replace('.', '/', $name) . '.php');
  141. }
  142. /**
  143. * 操作成功返回的数据
  144. * @param null $data
  145. * @param string $msg
  146. * @param int $code
  147. * @param null $type
  148. * @param array $header
  149. */
  150. protected function success($data = null, $msg = '成功', $code = 1, $type = null, array $header = [])
  151. {
  152. $this->result($msg, $data, $code, $type, $header);
  153. }
  154. /**
  155. * 操作失败返回的数据
  156. * @param string $msg 提示信息
  157. * @param mixed $data 要返回的数据
  158. * @param int $code 错误码,默认为0
  159. * @param string $type 输出类型
  160. * @param array $header 发送的 Header 信息
  161. */
  162. protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
  163. {
  164. $this->result($msg, $data, $code, $type, $header);
  165. }
  166. /**
  167. * 返回封装后的 API 数据到客户端
  168. * @access protected
  169. * @param mixed $msg 提示信息
  170. * @param mixed $data 要返回的数据
  171. * @param int $code 错误码,默认为0
  172. * @param string $type 输出类型,支持json/xml/jsonp
  173. * @param array $header 发送的 Header 信息
  174. * @return void
  175. * @throws HttpResponseException
  176. */
  177. protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
  178. {
  179. $result = [
  180. 'code' => $code,
  181. 'msg' => $msg,
  182. 'time' => Request::instance()->server('REQUEST_TIME'),
  183. 'data' => $data,
  184. ];
  185. // 如果未设置类型则自动判断
  186. $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
  187. if (isset($header['statuscode'])) {
  188. $code = $header['statuscode'];
  189. unset($header['statuscode']);
  190. } else {
  191. //未设置状态码,根据code值判断
  192. $code = $code >= 1000 || $code < 200 ? 200 : $code;
  193. }
  194. $response = Response::create($result, $type, $code)->header($header);
  195. throw new HttpResponseException($response);
  196. }
  197. /**
  198. * 前置操作
  199. * @access protected
  200. * @param string $method 前置操作方法名
  201. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  202. * @return void
  203. */
  204. protected function beforeAction($method, $options = [])
  205. {
  206. if (isset($options['only'])) {
  207. if (is_string($options['only'])) {
  208. $options['only'] = explode(',', $options['only']);
  209. }
  210. if (!in_array($this->request->action(), $options['only'])) {
  211. return;
  212. }
  213. } elseif (isset($options['except'])) {
  214. if (is_string($options['except'])) {
  215. $options['except'] = explode(',', $options['except']);
  216. }
  217. if (in_array($this->request->action(), $options['except'])) {
  218. return;
  219. }
  220. }
  221. call_user_func([$this, $method]);
  222. }
  223. /**
  224. * 设置验证失败后是否抛出异常
  225. * @access protected
  226. * @param bool $fail 是否抛出异常
  227. * @return $this
  228. */
  229. protected function validateFailException($fail = true)
  230. {
  231. $this->failException = $fail;
  232. return $this;
  233. }
  234. /**
  235. * 验证数据
  236. * @access protected
  237. * @param array $data 数据
  238. * @param string|array $validate 验证器名或者验证规则数组
  239. * @param array $message 提示信息
  240. * @param bool $batch 是否批量验证
  241. * @param mixed $callback 回调方法(闭包)
  242. * @return array|string|true
  243. * @throws ValidateException
  244. */
  245. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  246. {
  247. if (is_array($validate)) {
  248. $v = Loader::validate();
  249. $v->rule($validate);
  250. } else {
  251. // 支持场景
  252. if (strpos($validate, '.')) {
  253. list($validate, $scene) = explode('.', $validate);
  254. }
  255. $v = Loader::validate($validate);
  256. !empty($scene) && $v->scene($scene);
  257. }
  258. // 批量验证
  259. if ($batch || $this->batchValidate) {
  260. $v->batch(true);
  261. }
  262. // 设置错误信息
  263. if (is_array($message)) {
  264. $v->message($message);
  265. }
  266. // 使用回调验证
  267. if ($callback && is_callable($callback)) {
  268. call_user_func_array($callback, [$v, &$data]);
  269. }
  270. if (!$v->check($data)) {
  271. if ($this->failException) {
  272. throw new ValidateException($v->getError());
  273. }
  274. return $v->getError();
  275. }
  276. return true;
  277. }
  278. /**
  279. * 刷新Token
  280. */
  281. protected function token()
  282. {
  283. $token = $this->request->param('__token__');
  284. //验证Token
  285. if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
  286. $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
  287. }
  288. //刷新Token
  289. $this->request->token();
  290. }
  291. /**
  292. * 生成查询所需要的条件,排序方式
  293. * @param mixed $searchfields 快速查询的字段
  294. * @param boolean $relationSearch 是否关联查询
  295. * @return array
  296. */
  297. protected function buildparams($searchfields = null, $relationSearch = null)
  298. {
  299. $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
  300. $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
  301. $search = $this->request->get("search", '');
  302. $filter = $this->request->get("filter", '','trim');
  303. $op = $this->request->get("op", '', 'trim');
  304. $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
  305. $order = $this->request->get("order", "DESC");
  306. $offset = $this->request->get("offset/d", 0);
  307. $limit = $this->request->get("limit/d", 999999);
  308. //新增自动计算页码
  309. $page = $limit ? intval($offset / $limit) + 1 : 1;
  310. if ($this->request->has("page")) {
  311. $page = $this->request->get("page/d", 1);
  312. }
  313. $this->request->get([config('paginate.var_page') => $page]);
  314. // p($filter);
  315. // p($op);
  316. $filter = (array)json_decode($filter, true);
  317. $op = (array)json_decode($op, true);
  318. // p($filter);
  319. // p($op);
  320. $filter = $filter ? $filter : [];
  321. $where = [];
  322. $alias = [];
  323. $bind = [];
  324. $name = '';
  325. $aliasName = '';
  326. if (!empty($this->model) && $this->relationSearch) {
  327. $name = $this->model->getTable();
  328. $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
  329. $aliasName = $alias[$name] . '.';
  330. }
  331. $sortArr = explode(',', $sort);
  332. foreach ($sortArr as $index => & $item) {
  333. $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
  334. }
  335. unset($item);
  336. $sort = implode(',', $sortArr);
  337. // $adminIds = $this->getDataLimitAdminIds();
  338. // if (is_array($adminIds)) {
  339. // $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
  340. // }
  341. if ($search) {
  342. $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
  343. foreach ($searcharr as $k => &$v) {
  344. $v = stripos($v, ".") === false ? $aliasName . $v : $v;
  345. }
  346. unset($v);
  347. $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
  348. }
  349. $index = 0;
  350. foreach ($filter as $k => $v) {
  351. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
  352. continue;
  353. }
  354. $sym = isset($op[$k]) ? $op[$k] : '=';
  355. if (stripos($k, ".") === false) {
  356. $k = $aliasName . $k;
  357. }
  358. $v = !is_array($v) ? trim($v) : $v;
  359. $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
  360. //null和空字符串特殊处理
  361. if (!is_array($v)) {
  362. if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
  363. $sym = strtoupper($v);
  364. }
  365. if (in_array($v, ['""', "''"])) {
  366. $v = '';
  367. $sym = '=';
  368. }
  369. }
  370. // p($sym);
  371. switch ($sym) {
  372. case '=':
  373. case '<>':
  374. $where[] = [$k, $sym, (string)$v];
  375. break;
  376. case 'LIKE':
  377. case 'NOT LIKE':
  378. case 'LIKE %...%':
  379. case 'NOT LIKE %...%':
  380. $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
  381. break;
  382. case '>':
  383. case '>=':
  384. case '<':
  385. case '<=':
  386. $where[] = [$k, $sym, intval($v)];
  387. break;
  388. case 'FINDIN':
  389. case 'FINDINSET':
  390. case 'FIND_IN_SET':
  391. $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
  392. $findArr = array_values($v);
  393. foreach ($findArr as $idx => $item) {
  394. $bindName = "item_" . $index . "_" . $idx;
  395. $bind[$bindName] = $item;
  396. $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
  397. }
  398. break;
  399. case 'IN':
  400. case 'IN(...)':
  401. case 'NOT IN':
  402. case 'NOT IN(...)':
  403. $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
  404. break;
  405. case 'BETWEEN':
  406. case 'NOT BETWEEN':
  407. $arr = array_slice(explode(',', $v), 0, 2);
  408. if (stripos($v, ',') === false || !array_filter($arr, function ($v) {
  409. return $v != '' && $v !== false && $v !== null;
  410. })) {
  411. continue 2;
  412. }
  413. //当出现一边为空时改变操作符
  414. if ($arr[0] === '') {
  415. $sym = $sym == 'BETWEEN' ? '<=' : '>';
  416. $arr = $arr[1];
  417. } elseif ($arr[1] === '') {
  418. $sym = $sym == 'BETWEEN' ? '>=' : '<';
  419. $arr = $arr[0];
  420. }
  421. $where[] = [$k, $sym, $arr];
  422. break;
  423. case 'RANGE':
  424. case 'NOT RANGE':
  425. $v = str_replace(' - ', ',', $v);
  426. $arr = array_slice(explode(',', $v), 0, 2);
  427. if (stripos($v, ',') === false || !array_filter($arr)) {
  428. continue 2;
  429. }
  430. //当出现一边为空时改变操作符
  431. if ($arr[0] === '') {
  432. $sym = $sym == 'RANGE' ? '<=' : '>';
  433. $arr = $arr[1];
  434. } elseif ($arr[1] === '') {
  435. $sym = $sym == 'RANGE' ? '>=' : '<';
  436. $arr = $arr[0];
  437. }
  438. $tableArr = explode('.', $k);
  439. if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
  440. //修复关联模型下时间无法搜索的BUG
  441. $relation = Loader::parseName($tableArr[0], 1, false);
  442. $alias[$this->model->$relation()->getTable()] = $tableArr[0];
  443. }
  444. $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
  445. break;
  446. case 'NULL':
  447. case 'IS NULL':
  448. case 'NOT NULL':
  449. case 'IS NOT NULL':
  450. $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
  451. break;
  452. default:
  453. break;
  454. }
  455. $index++;
  456. }
  457. if (!empty($this->model)) {
  458. $this->model->alias($alias);
  459. }
  460. $model = $this->model;
  461. // p($where);
  462. $where = function ($query) use ($where, $alias, $bind, &$model) {
  463. if (!empty($model)) {
  464. $model->alias($alias);
  465. $model->bind($bind);
  466. }
  467. foreach ($where as $k => $v) {
  468. if (is_array($v)) {
  469. call_user_func_array([$query, 'where'], $v);
  470. } else {
  471. $query->where($v);
  472. }
  473. }
  474. };
  475. return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
  476. }
  477. }