| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528 |
- <?php
- namespace app\common\controller;
- use app\common\library\Auth;
- use think\Config;
- use think\exception\HttpResponseException;
- use think\exception\ValidateException;
- use think\Hook;
- use think\Lang;
- use think\Loader;
- use think\Request;
- use think\Response;
- use think\Validate;
- /**
- * API控制器基类
- */
- class Api
- {
- /**
- * @var Request Request 实例
- */
- protected $request;
- /**
- * @var bool 验证失败是否抛出异常
- */
- protected $failException = false;
- /**
- * @var bool 是否批量验证
- */
- protected $batchValidate = false;
- /**
- * @var array 前置操作方法列表
- */
- protected $beforeActionList = [];
- /**
- * 无需登录的方法,同时也就不需要鉴权了
- * @var array
- */
- protected $noNeedLogin = [];
- /**
- * 无需鉴权的方法,但需要登录
- * @var array
- */
- protected $noNeedRight = ['*'];
- /**
- * 权限Auth
- * @var Auth
- */
- protected $auth = null;
- /**
- * 默认响应输出类型,支持json/xml
- * @var string
- */
- protected $responseType = 'json';
- /**
- * 快速搜索时执行查找的字段
- */
- protected $searchFields = 'id';
- /**
- * 是否是关联查询
- */
- protected $relationSearch = false;
-
- /**
- * 构造方法
- * @access public
- * @param Request $request Request 对象
- */
- public function __construct(Request $request = null)
- {
- $this->request = is_null($request) ? Request::instance() : $request;
- // 控制器初始化
- $this->_initialize();
- // 前置操作方法
- if ($this->beforeActionList) {
- foreach ($this->beforeActionList as $method => $options) {
- is_numeric($method) ?
- $this->beforeAction($options) :
- $this->beforeAction($method, $options);
- }
- }
- }
- /**
- * 初始化操作
- * @access protected
- */
- protected function _initialize()
- {
- //跨域请求检测
- check_cors_request();
- // 检测IP是否允许
- check_ip_allowed();
- //移除HTML标签
- $this->request->filter('trim,strip_tags,htmlspecialchars');
- $this->auth = Auth::instance();
- $modulename = $this->request->module();
- $controllername = Loader::parseName($this->request->controller());
- $actionname = strtolower($this->request->action());
- //$token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
- $token = $this->request->server('HTTP_TOKEN', $this->request->header('session-token'));
- $path = str_replace('.', '/', $controllername) . '/' . $actionname;
- // 设置当前请求的URI
- $this->auth->setRequestUri($path);
- // 检测是否需要验证登录
- if (!$this->auth->match($this->noNeedLogin)) {
- //初始化
- $this->auth->init($token);
- //检测是否登录
- if (!$this->auth->isLogin()) {
- $this->error(__('Please login first'), null, 401);
- }
- // 判断是否需要验证权限
- if (!$this->auth->match($this->noNeedRight)) {
- // 判断控制器和方法判断是否有对应权限
- if (!$this->auth->check($path)) {
- $this->error(__('You have no permission'), null, 403);
- }
- }
- } else {
- // 如果有传递token才验证是否登录状态
- if ($token) {
- $this->auth->init($token);
- }
- }
- $upload = \app\common\model\Config::upload();
- // 上传信息配置后
- Hook::listen("upload_config_init", $upload);
- Config::set('upload', array_merge(Config::get('upload'), $upload));
- // 加载当前控制器语言包
- $this->loadlang($controllername);
- }
- /**
- * 加载语言文件
- * @param string $name
- */
- protected function loadlang($name)
- {
- $name = Loader::parseName($name);
- $name = preg_match("/^([a-zA-Z0-9_\.\/]+)\$/i", $name) ? $name : 'index';
- $lang = $this->request->langset();
- $lang = preg_match("/^([a-zA-Z\-_]{2,10})\$/i", $lang) ? $lang : 'zh-cn';
- Lang::load(APP_PATH . $this->request->module() . '/lang/' . $lang . '/' . str_replace('.', '/', $name) . '.php');
- }
- /**
- * 操作成功返回的数据
- * @param null $data
- * @param string $msg
- * @param int $code
- * @param null $type
- * @param array $header
- */
- protected function success($data = null, $msg = '成功', $code = 1, $type = null, array $header = [])
- {
- $this->result($msg, $data, $code, $type, $header);
- }
- /**
- * 操作失败返回的数据
- * @param string $msg 提示信息
- * @param mixed $data 要返回的数据
- * @param int $code 错误码,默认为0
- * @param string $type 输出类型
- * @param array $header 发送的 Header 信息
- */
- protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
- {
- $this->result($msg, $data, $code, $type, $header);
- }
- /**
- * 返回封装后的 API 数据到客户端
- * @access protected
- * @param mixed $msg 提示信息
- * @param mixed $data 要返回的数据
- * @param int $code 错误码,默认为0
- * @param string $type 输出类型,支持json/xml/jsonp
- * @param array $header 发送的 Header 信息
- * @return void
- * @throws HttpResponseException
- */
- protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
- {
- $result = [
- 'code' => $code,
- 'msg' => $msg,
- 'time' => Request::instance()->server('REQUEST_TIME'),
- 'data' => $data,
- ];
- // 如果未设置类型则自动判断
- $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
- if (isset($header['statuscode'])) {
- $code = $header['statuscode'];
- unset($header['statuscode']);
- } else {
- //未设置状态码,根据code值判断
- $code = $code >= 1000 || $code < 200 ? 200 : $code;
- }
- $response = Response::create($result, $type, $code)->header($header);
- throw new HttpResponseException($response);
- }
- /**
- * 前置操作
- * @access protected
- * @param string $method 前置操作方法名
- * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
- * @return void
- */
- protected function beforeAction($method, $options = [])
- {
- if (isset($options['only'])) {
- if (is_string($options['only'])) {
- $options['only'] = explode(',', $options['only']);
- }
- if (!in_array($this->request->action(), $options['only'])) {
- return;
- }
- } elseif (isset($options['except'])) {
- if (is_string($options['except'])) {
- $options['except'] = explode(',', $options['except']);
- }
- if (in_array($this->request->action(), $options['except'])) {
- return;
- }
- }
- call_user_func([$this, $method]);
- }
- /**
- * 设置验证失败后是否抛出异常
- * @access protected
- * @param bool $fail 是否抛出异常
- * @return $this
- */
- protected function validateFailException($fail = true)
- {
- $this->failException = $fail;
- return $this;
- }
- /**
- * 验证数据
- * @access protected
- * @param array $data 数据
- * @param string|array $validate 验证器名或者验证规则数组
- * @param array $message 提示信息
- * @param bool $batch 是否批量验证
- * @param mixed $callback 回调方法(闭包)
- * @return array|string|true
- * @throws ValidateException
- */
- protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
- {
- if (is_array($validate)) {
- $v = Loader::validate();
- $v->rule($validate);
- } else {
- // 支持场景
- if (strpos($validate, '.')) {
- list($validate, $scene) = explode('.', $validate);
- }
- $v = Loader::validate($validate);
- !empty($scene) && $v->scene($scene);
- }
- // 批量验证
- if ($batch || $this->batchValidate) {
- $v->batch(true);
- }
- // 设置错误信息
- if (is_array($message)) {
- $v->message($message);
- }
- // 使用回调验证
- if ($callback && is_callable($callback)) {
- call_user_func_array($callback, [$v, &$data]);
- }
- if (!$v->check($data)) {
- if ($this->failException) {
- throw new ValidateException($v->getError());
- }
- return $v->getError();
- }
- return true;
- }
- /**
- * 刷新Token
- */
- protected function token()
- {
- $token = $this->request->param('__token__');
- //验证Token
- if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
- $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
- }
- //刷新Token
- $this->request->token();
- }
- /**
- * 生成查询所需要的条件,排序方式
- * @param mixed $searchfields 快速查询的字段
- * @param boolean $relationSearch 是否关联查询
- * @return array
- */
- protected function buildparams($searchfields = null, $relationSearch = null)
- {
- $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
- $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
- $search = $this->request->get("search", '');
- $filter = $this->request->get("filter", '','trim');
- $op = $this->request->get("op", '', 'trim');
- $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
- $order = $this->request->get("order", "DESC");
- $offset = $this->request->get("offset/d", 0);
- $limit = $this->request->get("limit/d", 999999);
- //新增自动计算页码
- $page = $limit ? intval($offset / $limit) + 1 : 1;
- if ($this->request->has("page")) {
- $page = $this->request->get("page/d", 1);
- }
- $this->request->get([config('paginate.var_page') => $page]);
- // p($filter);
- // p($op);
- $filter = (array)json_decode($filter, true);
- $op = (array)json_decode($op, true);
- // p($filter);
- // p($op);
- $filter = $filter ? $filter : [];
- $where = [];
- $alias = [];
- $bind = [];
- $name = '';
- $aliasName = '';
- if (!empty($this->model) && $this->relationSearch) {
- $name = $this->model->getTable();
- $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
- $aliasName = $alias[$name] . '.';
- }
- $sortArr = explode(',', $sort);
- foreach ($sortArr as $index => & $item) {
- $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
- }
- unset($item);
- $sort = implode(',', $sortArr);
- // $adminIds = $this->getDataLimitAdminIds();
- // if (is_array($adminIds)) {
- // $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
- // }
-
- if ($search) {
- $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
- foreach ($searcharr as $k => &$v) {
- $v = stripos($v, ".") === false ? $aliasName . $v : $v;
- }
- unset($v);
- $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
- }
- $index = 0;
-
- foreach ($filter as $k => $v) {
- if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
- continue;
- }
- $sym = isset($op[$k]) ? $op[$k] : '=';
- if (stripos($k, ".") === false) {
- $k = $aliasName . $k;
- }
- $v = !is_array($v) ? trim($v) : $v;
- $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
- //null和空字符串特殊处理
- if (!is_array($v)) {
- if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
- $sym = strtoupper($v);
- }
- if (in_array($v, ['""', "''"])) {
- $v = '';
- $sym = '=';
- }
- }
- // p($sym);
- switch ($sym) {
- case '=':
- case '<>':
- $where[] = [$k, $sym, (string)$v];
- break;
- case 'LIKE':
- case 'NOT LIKE':
- case 'LIKE %...%':
- case 'NOT LIKE %...%':
- $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
- break;
- case '>':
- case '>=':
- case '<':
- case '<=':
- $where[] = [$k, $sym, intval($v)];
- break;
- case 'FINDIN':
- case 'FINDINSET':
- case 'FIND_IN_SET':
- $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
- $findArr = array_values($v);
- foreach ($findArr as $idx => $item) {
- $bindName = "item_" . $index . "_" . $idx;
- $bind[$bindName] = $item;
- $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
- }
- break;
- case 'IN':
- case 'IN(...)':
- case 'NOT IN':
- case 'NOT IN(...)':
- $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
- break;
- case 'BETWEEN':
- case 'NOT BETWEEN':
- $arr = array_slice(explode(',', $v), 0, 2);
- if (stripos($v, ',') === false || !array_filter($arr, function ($v) {
- return $v != '' && $v !== false && $v !== null;
- })) {
- continue 2;
- }
- //当出现一边为空时改变操作符
- if ($arr[0] === '') {
- $sym = $sym == 'BETWEEN' ? '<=' : '>';
- $arr = $arr[1];
- } elseif ($arr[1] === '') {
- $sym = $sym == 'BETWEEN' ? '>=' : '<';
- $arr = $arr[0];
- }
- $where[] = [$k, $sym, $arr];
- break;
- case 'RANGE':
- case 'NOT RANGE':
- $v = str_replace(' - ', ',', $v);
- $arr = array_slice(explode(',', $v), 0, 2);
- if (stripos($v, ',') === false || !array_filter($arr)) {
- continue 2;
- }
- //当出现一边为空时改变操作符
- if ($arr[0] === '') {
- $sym = $sym == 'RANGE' ? '<=' : '>';
- $arr = $arr[1];
- } elseif ($arr[1] === '') {
- $sym = $sym == 'RANGE' ? '>=' : '<';
- $arr = $arr[0];
- }
- $tableArr = explode('.', $k);
- if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
- //修复关联模型下时间无法搜索的BUG
- $relation = Loader::parseName($tableArr[0], 1, false);
- $alias[$this->model->$relation()->getTable()] = $tableArr[0];
- }
- $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
- break;
- case 'NULL':
- case 'IS NULL':
- case 'NOT NULL':
- case 'IS NOT NULL':
- $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
- break;
- default:
- break;
- }
- $index++;
- }
- if (!empty($this->model)) {
- $this->model->alias($alias);
- }
- $model = $this->model;
- // p($where);
- $where = function ($query) use ($where, $alias, $bind, &$model) {
- if (!empty($model)) {
- $model->alias($alias);
- $model->bind($bind);
- }
- foreach ($where as $k => $v) {
- if (is_array($v)) {
- call_user_func_array([$query, 'where'], $v);
- } else {
- $query->where($v);
- }
- }
- };
- return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
- }
- }
|