Backend.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  1. <?php
  2. namespace app\common\controller;
  3. use app\admin\library\Auth;
  4. use app\admin\model\Area;
  5. use app\api\model\massager\Collect;
  6. use think\Config;
  7. use think\Controller;
  8. use think\Hook;
  9. use think\Lang;
  10. use think\Loader;
  11. use think\Model;
  12. use think\Session;
  13. use fast\Tree;
  14. use think\Validate;
  15. /**
  16. * 后台控制器基类
  17. */
  18. class Backend extends Controller
  19. {
  20. /**
  21. * 无需登录的方法,同时也就不需要鉴权了
  22. * @var array
  23. */
  24. protected $noNeedLogin = [];
  25. /**
  26. * 无需鉴权的方法,但需要登录
  27. * @var array
  28. */
  29. protected $noNeedRight = ["selectpage"];
  30. /**
  31. * 布局模板
  32. * @var string
  33. */
  34. protected $layout = 'default';
  35. /**
  36. * 权限控制类
  37. * @var Auth
  38. */
  39. protected $auth = null;
  40. /**
  41. * 模型对象
  42. * @var \think\Model
  43. */
  44. protected $model = null;
  45. /**
  46. * 快速搜索时执行查找的字段
  47. */
  48. protected $searchFields = 'id';
  49. /**
  50. * 是否是关联查询
  51. */
  52. protected $relationSearch = false;
  53. /**
  54. * 是否开启数据限制
  55. * 支持auth/personal
  56. * 表示按权限判断/仅限个人
  57. * 默认为禁用,若启用请务必保证表中存在admin_id字段
  58. */
  59. protected $dataLimit = false;
  60. /**
  61. * 数据限制字段
  62. */
  63. protected $dataLimitField = 'admin_id';
  64. /**
  65. * 数据限制开启时自动填充限制字段值
  66. */
  67. protected $dataLimitFieldAutoFill = true;
  68. /**
  69. * 是否开启Validate验证
  70. */
  71. protected $modelValidate = false;
  72. /**
  73. * 是否开启模型场景验证
  74. */
  75. protected $modelSceneValidate = false;
  76. /**
  77. * Multi方法可批量修改的字段
  78. */
  79. protected $multiFields = 'status';
  80. /**
  81. * Selectpage可显示的字段
  82. */
  83. protected $selectpageFields = '*';
  84. /**
  85. * 前台提交过来,需要排除的字段数据
  86. */
  87. protected $excludeFields = "";
  88. /**
  89. * 导入文件首行类型
  90. * 支持comment/name
  91. * 表示注释或字段名
  92. */
  93. protected $importHeadType = 'comment';
  94. /**
  95. * 引入后台控制器的traits
  96. */
  97. use \app\admin\library\traits\Backend;
  98. public function _initialize()
  99. {
  100. $modulename = $this->request->module();
  101. $controllername = Loader::parseName($this->request->controller());
  102. $actionname = strtolower($this->request->action());
  103. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  104. // 定义是否Addtabs请求
  105. !defined('IS_ADDTABS') && define('IS_ADDTABS', input("addtabs") ? true : false);
  106. // 定义是否Dialog请求
  107. !defined('IS_DIALOG') && define('IS_DIALOG', input("dialog") ? true : false);
  108. // 定义是否AJAX请求
  109. !defined('IS_AJAX') && define('IS_AJAX', $this->request->isAjax());
  110. // 检测IP是否允许
  111. check_ip_allowed();
  112. $this->auth = Auth::instance();
  113. // 设置当前请求的URI
  114. $this->auth->setRequestUri($path);
  115. // 检测是否需要验证登录
  116. if (!$this->auth->match($this->noNeedLogin)) {
  117. //检测是否登录
  118. if (!$this->auth->isLogin()) {
  119. Hook::listen('admin_nologin', $this);
  120. $url = Session::get('referer');
  121. $url = $url ? $url : $this->request->url();
  122. if (in_array($this->request->pathinfo(), ['/', 'index/index'])) {
  123. $this->redirect('index/login', [], 302, ['referer' => $url]);
  124. exit;
  125. }
  126. $this->error(__('Please login first'), url('index/login', ['url' => $url]));
  127. }
  128. // 判断是否需要验证权限
  129. if (!$this->auth->match($this->noNeedRight)) {
  130. // 判断控制器和方法是否有对应权限
  131. if (!$this->auth->check($path)) {
  132. Hook::listen('admin_nopermission', $this);
  133. $this->error(__('You have no permission'), '');
  134. }
  135. }
  136. }
  137. // 非选项卡时重定向
  138. if (!$this->request->isPost() && !IS_AJAX && !IS_ADDTABS && !IS_DIALOG && input("ref") == 'addtabs') {
  139. $url = preg_replace_callback("/([\?|&]+)ref=addtabs(&?)/i", function ($matches) {
  140. return $matches[2] == '&' ? $matches[1] : '';
  141. }, $this->request->url());
  142. if (Config::get('url_domain_deploy')) {
  143. if (stripos($url, $this->request->server('SCRIPT_NAME')) === 0) {
  144. $url = substr($url, strlen($this->request->server('SCRIPT_NAME')));
  145. }
  146. $url = url($url, '', false);
  147. }
  148. $this->redirect('index/index', [], 302, ['referer' => $url]);
  149. exit;
  150. }
  151. // 设置面包屑导航数据
  152. $breadcrumb = [];
  153. if (!IS_DIALOG && !config('fastadmin.multiplenav') && config('fastadmin.breadcrumb')) {
  154. $breadcrumb = $this->auth->getBreadCrumb($path);
  155. array_pop($breadcrumb);
  156. }
  157. $this->view->breadcrumb = $breadcrumb;
  158. // 如果有使用模板布局
  159. if ($this->layout) {
  160. $this->view->engine->layout('layout/' . $this->layout);
  161. }
  162. // 语言检测
  163. $lang = $this->request->langset();
  164. $lang = preg_match("/^([a-zA-Z\-_]{2,10})\$/i", $lang) ? $lang : 'zh-cn';
  165. $site = Config::get("site");
  166. $upload = \app\common\model\Config::upload();
  167. // 上传信息配置后
  168. Hook::listen("upload_config_init", $upload);
  169. // 配置信息
  170. $config = [
  171. 'site' => array_intersect_key($site, array_flip(['name', 'indexurl', 'cdnurl', 'version', 'timezone', 'languages'])),
  172. 'upload' => $upload,
  173. 'modulename' => $modulename,
  174. 'controllername' => $controllername,
  175. 'actionname' => $actionname,
  176. 'jsname' => 'backend/' . str_replace('.', '/', $controllername),
  177. 'moduleurl' => rtrim(url("/{$modulename}", '', false), '/'),
  178. 'language' => $lang,
  179. 'referer' => Session::get("referer")
  180. ];
  181. $config = array_merge($config, Config::get("view_replace_str"));
  182. Config::set('upload', array_merge(Config::get('upload'), $upload));
  183. // 配置信息后
  184. Hook::listen("config_init", $config);
  185. //加载当前控制器语言包
  186. $this->loadlang($controllername);
  187. //渲染站点配置
  188. $this->assign('site', $site);
  189. //渲染配置信息
  190. $this->assign('config', $config);
  191. //渲染权限对象
  192. $this->assign('auth', $this->auth);
  193. //渲染管理员对象
  194. $this->assign('admin', Session::get('admin'));
  195. $this->assign("boolList", [0 => '否', 1 => '是']);
  196. $this->assign("negationBoolList", [1 => '否', 0 => '是']);
  197. $admin = $this->auth->getUserInfo();
  198. if ($admin) {
  199. $allow_areas = (new Area())->findAreaByAdmin($admin);
  200. $allow_areas_fmt = array_reduce($allow_areas, function ($p,$cur) {
  201. $p[$cur['area_code']] = $cur['name'];
  202. return $p;
  203. }, []);
  204. $this->assignconfig("allow_areas", $allow_areas_fmt);
  205. }
  206. }
  207. /**
  208. * 加载语言文件
  209. * @param string $name
  210. */
  211. protected function loadlang($name)
  212. {
  213. $name = Loader::parseName($name);
  214. $name = preg_match("/^([a-zA-Z0-9_\.\/]+)\$/i", $name) ? $name : 'index';
  215. $lang = $this->request->langset();
  216. $lang = preg_match("/^([a-zA-Z\-_]{2,10})\$/i", $lang) ? $lang : 'zh-cn';
  217. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $lang . '/' . str_replace('.', '/', $name) . '.php');
  218. }
  219. /**
  220. * 渲染配置信息
  221. * @param mixed $name 键名或数组
  222. * @param mixed $value 值
  223. */
  224. protected function assignconfig($name, $value = '')
  225. {
  226. $this->view->config = array_merge($this->view->config ? $this->view->config : [], is_array($name) ? $name : [$name => $value]);
  227. }
  228. /**
  229. * 生成查询所需要的条件,排序方式
  230. * @param mixed $searchfields 快速查询的字段
  231. * @param boolean $relationSearch 是否关联查询
  232. * @return array
  233. */
  234. protected function buildparams($searchfields = null, $relationSearch = null)
  235. {
  236. $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
  237. $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
  238. $search = $this->request->get("search", '');
  239. $filter = $this->request->get("filter", '');
  240. $op = $this->request->get("op", '', 'trim');
  241. $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
  242. $order = $this->request->get("order", "DESC");
  243. $offset = $this->request->get("offset/d", 0);
  244. $limit = $this->request->get("limit/d", 999999);
  245. //新增自动计算页码
  246. $page = $limit ? intval($offset / $limit) + 1 : 1;
  247. if ($this->request->has("page")) {
  248. $page = $this->request->get("page/d", 1);
  249. }
  250. $this->request->get([config('paginate.var_page') => $page]);
  251. $filter = (array)json_decode($filter, true);
  252. $op = (array)json_decode($op, true);
  253. $filter = $filter ? $filter : [];
  254. $where = [];
  255. $alias = [];
  256. $bind = [];
  257. $name = '';
  258. $aliasName = '';
  259. if (!empty($this->model) && $this->relationSearch) {
  260. $name = $this->model->getTable();
  261. $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
  262. $aliasName = $alias[$name] . '.';
  263. }
  264. $sortArr = explode(',', $sort);
  265. foreach ($sortArr as $index => & $item) {
  266. $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
  267. }
  268. unset($item);
  269. $sort = implode(',', $sortArr);
  270. $adminIds = $this->getDataLimitAdminIds();
  271. if (is_array($adminIds)) {
  272. $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
  273. }
  274. if ($search) {
  275. $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
  276. foreach ($searcharr as $k => &$v) {
  277. $v = stripos($v, ".") === false ? $aliasName . $v : $v;
  278. }
  279. unset($v);
  280. $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
  281. }
  282. $index = 0;
  283. foreach ($filter as $k => $v) {
  284. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
  285. continue;
  286. }
  287. $sym = isset($op[$k]) ? $op[$k] : '=';
  288. if (stripos($k, ".") === false) {
  289. $k = $aliasName . $k;
  290. }
  291. $v = !is_array($v) ? trim($v) : $v;
  292. $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
  293. //null和空字符串特殊处理
  294. if (!is_array($v)) {
  295. if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
  296. $sym = strtoupper($v);
  297. }
  298. if (in_array($v, ['""', "''"])) {
  299. $v = '';
  300. $sym = '=';
  301. }
  302. }
  303. switch ($sym) {
  304. case '=':
  305. case '<>':
  306. $where[] = [$k, $sym, (string)$v];
  307. break;
  308. case 'LIKE':
  309. case 'NOT LIKE':
  310. case 'LIKE %...%':
  311. case 'NOT LIKE %...%':
  312. $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
  313. break;
  314. case '>':
  315. case '>=':
  316. case '<':
  317. case '<=':
  318. $where[] = [$k, $sym, intval($v)];
  319. break;
  320. case 'FINDIN':
  321. case 'FINDINSET':
  322. case 'FIND_IN_SET':
  323. $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
  324. $findArr = array_values($v);
  325. foreach ($findArr as $idx => $item) {
  326. $bindName = "item_" . $index . "_" . $idx;
  327. $bind[$bindName] = $item;
  328. $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
  329. }
  330. break;
  331. case 'IN':
  332. case 'IN(...)':
  333. case 'NOT IN':
  334. case 'NOT IN(...)':
  335. $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
  336. break;
  337. case 'BETWEEN':
  338. case 'NOT BETWEEN':
  339. $arr = array_slice(explode(',', $v), 0, 2);
  340. if (stripos($v, ',') === false || !array_filter($arr, function ($v) {
  341. return $v != '' && $v !== false && $v !== null;
  342. })) {
  343. continue 2;
  344. }
  345. //当出现一边为空时改变操作符
  346. if ($arr[0] === '') {
  347. $sym = $sym == 'BETWEEN' ? '<=' : '>';
  348. $arr = $arr[1];
  349. } elseif ($arr[1] === '') {
  350. $sym = $sym == 'BETWEEN' ? '>=' : '<';
  351. $arr = $arr[0];
  352. }
  353. $where[] = [$k, $sym, $arr];
  354. break;
  355. case 'RANGE':
  356. case 'NOT RANGE':
  357. $v = str_replace(' - ', ',', $v);
  358. $arr = array_slice(explode(',', $v), 0, 2);
  359. if (stripos($v, ',') === false || !array_filter($arr)) {
  360. continue 2;
  361. }
  362. //当出现一边为空时改变操作符
  363. if ($arr[0] === '') {
  364. $sym = $sym == 'RANGE' ? '<=' : '>';
  365. $arr = $arr[1];
  366. } elseif ($arr[1] === '') {
  367. $sym = $sym == 'RANGE' ? '>=' : '<';
  368. $arr = $arr[0];
  369. }
  370. $tableArr = explode('.', $k);
  371. if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
  372. //修复关联模型下时间无法搜索的BUG
  373. $relation = Loader::parseName($tableArr[0], 1, false);
  374. $alias[$this->model->$relation()->getTable()] = $tableArr[0];
  375. }
  376. $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
  377. break;
  378. case 'NULL':
  379. case 'IS NULL':
  380. case 'NOT NULL':
  381. case 'IS NOT NULL':
  382. $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
  383. break;
  384. default:
  385. break;
  386. }
  387. $index++;
  388. }
  389. if (!empty($this->model)) {
  390. $this->model->alias($alias);
  391. }
  392. $model = $this->model;
  393. $where = function ($query) use ($where, $alias, $bind, &$model) {
  394. if (!empty($model)) {
  395. $model->alias($alias);
  396. $model->bind($bind);
  397. }
  398. foreach ($where as $k => $v) {
  399. if (is_array($v)) {
  400. call_user_func_array([$query, 'where'], $v);
  401. } else {
  402. $query->where($v);
  403. }
  404. }
  405. };
  406. return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
  407. }
  408. /**
  409. * 获取数据限制的管理员ID
  410. * 禁用数据限制时返回的是null
  411. * @return mixed
  412. */
  413. protected function getDataLimitAdminIds()
  414. {
  415. if (!$this->dataLimit) {
  416. return null;
  417. }
  418. if ($this->auth->isSuperAdmin()) {
  419. return null;
  420. }
  421. $adminIds = [];
  422. if (in_array($this->dataLimit, ['auth', 'personal'])) {
  423. $adminIds = $this->dataLimit == 'auth' ? $this->auth->getChildrenAdminIds(true) : [$this->auth->id];
  424. }
  425. return $adminIds;
  426. }
  427. /**
  428. * Selectpage的实现方法
  429. *
  430. * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
  431. * 这里示例了所有的参数,所以比较复杂,实现上自己实现只需简单的几行即可
  432. *
  433. */
  434. protected function selectpage()
  435. {
  436. //设置过滤方法
  437. $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);
  438. //搜索关键词,客户端输入以空格分开,这里接收为数组
  439. $word = (array)$this->request->request("q_word/a");
  440. //当前页
  441. $page = $this->request->request("pageNumber");
  442. //分页大小
  443. $pagesize = $this->request->request("pageSize");
  444. //搜索条件
  445. $andor = $this->request->request("andOr", "and", "strtoupper");
  446. //排序方式
  447. $orderby = (array)$this->request->request("orderBy/a");
  448. //显示的字段
  449. $field = $this->request->request("showField");
  450. //主键
  451. $primarykey = $this->request->request("keyField");
  452. //主键值
  453. $primaryvalue = $this->request->request("keyValue");
  454. //搜索字段
  455. $searchfield = (array)$this->request->request("searchField/a");
  456. //自定义搜索条件
  457. $custom = (array)$this->request->request("custom/a");
  458. //是否返回树形结构
  459. $istree = $this->request->request("isTree", 0);
  460. $ishtml = $this->request->request("isHtml", 0);
  461. if ($istree) {
  462. $word = [];
  463. $pagesize = 999999;
  464. }
  465. $order = [];
  466. foreach ($orderby as $k => $v) {
  467. $order[$v[0]] = $v[1];
  468. }
  469. $field = $field ? $field : 'name';
  470. //如果有primaryvalue,说明当前是初始化传值
  471. if ($primaryvalue !== null) {
  472. $where = [$primarykey => ['in', $primaryvalue]];
  473. $pagesize = 999999;
  474. } else {
  475. $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
  476. $logic = $andor == 'AND' ? '&' : '|';
  477. $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
  478. $searchfield = str_replace(',', $logic, $searchfield);
  479. $word = array_filter(array_unique($word));
  480. if (count($word) == 1) {
  481. $query->where($searchfield, "like", "%" . reset($word) . "%");
  482. } else {
  483. $query->where(function ($query) use ($word, $searchfield) {
  484. foreach ($word as $index => $item) {
  485. $query->whereOr(function ($query) use ($item, $searchfield) {
  486. $query->where($searchfield, "like", "%{$item}%");
  487. });
  488. }
  489. });
  490. }
  491. if ($custom && is_array($custom)) {
  492. foreach ($custom as $k => $v) {
  493. if (is_array($v) && 2 == count($v)) {
  494. $query->where($k, trim($v[0]), $v[1]);
  495. } else {
  496. $query->where($k, '=', $v);
  497. }
  498. }
  499. }
  500. };
  501. }
  502. $adminIds = $this->getDataLimitAdminIds();
  503. if (is_array($adminIds)) {
  504. $this->model->where($this->dataLimitField, 'in', $adminIds);
  505. }
  506. $list = [];
  507. $total = $this->model->where($where)->count();
  508. if ($total > 0) {
  509. if (is_array($adminIds)) {
  510. $this->model->where($this->dataLimitField, 'in', $adminIds);
  511. }
  512. $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);
  513. //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
  514. if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
  515. $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
  516. //修复自定义data-primary-key为字符串内容时,给排序字段添加上引号
  517. $primaryvalue = array_map(function ($value) {
  518. return '\'' . $value . '\'';
  519. }, $primaryvalue);
  520. $primaryvalue = implode(',', $primaryvalue);
  521. $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
  522. } else {
  523. $this->model->order($order);
  524. }
  525. $datalist = $this->model->where($where)
  526. ->page($page, $pagesize)
  527. ->select();
  528. foreach ($datalist as $index => $item) {
  529. unset($item['password'], $item['salt']);
  530. if ($this->selectpageFields == '*') {
  531. $result = [
  532. $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
  533. $field => isset($item[$field]) ? $item[$field] : '',
  534. ];
  535. } else {
  536. $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
  537. }
  538. $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
  539. $list[] = $result;
  540. }
  541. if ($istree && !$primaryvalue) {
  542. $tree = Tree::instance();
  543. $tree->init(collection($list)->toArray(), 'pid');
  544. $list = $tree->getTreeList($tree->getTreeArray(0), $field);
  545. if (!$ishtml) {
  546. foreach ($list as &$item) {
  547. $item = str_replace('&nbsp;', ' ', $item);
  548. }
  549. unset($item);
  550. }
  551. }
  552. }
  553. //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
  554. return json(['list' => $list, 'total' => $total]);
  555. }
  556. protected function c_selectpage($custom_where = [])
  557. {
  558. //设置过滤方法
  559. $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);
  560. //搜索关键词,客户端输入以空格分开,这里接收为数组
  561. $word = (array)$this->request->request("q_word/a");
  562. //当前页
  563. $page = $this->request->request("pageNumber");
  564. //分页大小
  565. $pagesize = $this->request->request("pageSize");
  566. //搜索条件
  567. $andor = $this->request->request("andOr", "and", "strtoupper");
  568. //排序方式
  569. $orderby = (array)$this->request->request("orderBy/a");
  570. //显示的字段
  571. $field = $this->request->request("showField");
  572. //主键
  573. $primarykey = $this->request->request("keyField");
  574. //主键值
  575. $primaryvalue = $this->request->request("keyValue");
  576. //搜索字段
  577. $searchfield = (array)$this->request->request("searchField/a");
  578. //自定义搜索条件
  579. $custom = (array)$this->request->request("custom/a");
  580. foreach ($custom as $key => $value) {
  581. if (!$value)
  582. unset($custom[$key]);
  583. }
  584. //是否返回树形结构
  585. $istree = $this->request->request("isTree", 0);
  586. $ishtml = $this->request->request("isHtml", 0);
  587. if ($istree) {
  588. $word = [];
  589. $pagesize = 999999;
  590. }
  591. $order = [];
  592. foreach ($orderby as $k => $v) {
  593. $order[$v[0]] = $v[1];
  594. }
  595. $field = $field ? $field : 'name';
  596. //如果有primaryvalue,说明当前是初始化传值
  597. if ($primaryvalue !== null) {
  598. $where = [$primarykey => ['in', $primaryvalue]];
  599. $pagesize = 999999;
  600. } else {
  601. $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
  602. $logic = $andor == 'AND' ? '&' : '|';
  603. $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
  604. $searchfield = str_replace(',', $logic, $searchfield);
  605. $word = array_filter(array_unique($word));
  606. if (count($word) == 1) {
  607. $query->where($searchfield, "like", "%" . reset($word) . "%");
  608. } else {
  609. $query->where(function ($query) use ($word, $searchfield) {
  610. foreach ($word as $index => $item) {
  611. $query->whereOr(function ($query) use ($item, $searchfield) {
  612. $query->where($searchfield, "like", "%{$item}%");
  613. });
  614. }
  615. });
  616. }
  617. if ($custom && is_array($custom)) {
  618. foreach ($custom as $k => $v) {
  619. if (is_array($v) && 2 == count($v)) {
  620. $query->where($k, trim($v[0]), $v[1]);
  621. } else {
  622. $query->where($k, '=', $v);
  623. }
  624. }
  625. }
  626. };
  627. }
  628. $adminIds = $this->getDataLimitAdminIds();
  629. if (is_array($adminIds)) {
  630. $this->model->where($this->dataLimitField, 'in', $adminIds);
  631. }
  632. $list = [];
  633. $query = $this->model
  634. ->where($where);
  635. foreach ($custom_where as $item) {
  636. $query->where($item[0], $item[1], $item[2]);
  637. }
  638. $total = $query->count();
  639. if ($total > 0) {
  640. if (is_array($adminIds)) {
  641. $this->model->where($this->dataLimitField, 'in', $adminIds);
  642. }
  643. $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);
  644. //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
  645. if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
  646. $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
  647. //修复自定义data-primary-key为字符串内容时,给排序字段添加上引号
  648. $primaryvalue = array_map(function ($value) {
  649. return '\'' . $value . '\'';
  650. }, $primaryvalue);
  651. $primaryvalue = implode(',', $primaryvalue);
  652. $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
  653. } else {
  654. $this->model->order($order);
  655. }
  656. $query = $this->model
  657. ->where($where);
  658. foreach ($custom_where as $item) {
  659. $query->where($item[0], $item[1], $item[2]);
  660. }
  661. $datalist = $query
  662. ->page($page, $pagesize)
  663. ->select();
  664. foreach ($datalist as $index => $item) {
  665. unset($item['password'], $item['salt']);
  666. if ($this->selectpageFields == '*') {
  667. $result = [
  668. $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
  669. $field => isset($item[$field]) ? $item[$field] : '',
  670. ];
  671. } else {
  672. $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
  673. }
  674. $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
  675. $list[] = $result;
  676. }
  677. if ($istree && !$primaryvalue) {
  678. $tree = Tree::instance();
  679. $tree->init(collection($list)->toArray(), 'pid');
  680. $list = $tree->getTreeList($tree->getTreeArray(0), $field);
  681. if (!$ishtml) {
  682. foreach ($list as &$item) {
  683. $item = str_replace('&nbsp;', ' ', $item);
  684. }
  685. unset($item);
  686. }
  687. }
  688. }
  689. //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
  690. return json(['list' => $list, 'total' => $total]);
  691. }
  692. /**
  693. * 刷新Token
  694. */
  695. protected function token()
  696. {
  697. $token = $this->request->param('__token__');
  698. //验证Token
  699. if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
  700. $this->error(__('Token verification error'), '', ['__token__' => $this->request->token()]);
  701. }
  702. //刷新Token
  703. $this->request->token();
  704. }
  705. }