Backend.php 29 KB

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