Backend.php 29 KB

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