Backend.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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. // 检测IP是否允许
  109. check_ip_allowed();
  110. $this->auth = Auth::instance();
  111. // 设置当前请求的URI
  112. $this->auth->setRequestUri($path);
  113. // 检测是否需要验证登录
  114. if (!$this->auth->match($this->noNeedLogin)) {
  115. //检测是否登录
  116. if (!$this->auth->isLogin()) {
  117. Hook::listen('admin_nologin', $this);
  118. $url = Session::get('referer');
  119. $url = $url ? $url : $this->request->url();
  120. if (in_array($this->request->pathinfo(), ['/', 'index/index'])) {
  121. $this->redirect('index/login', [], 302, ['referer' => $url]);
  122. exit;
  123. }
  124. $this->error(__('Please login first'), url('index/login', ['url' => $url]));
  125. }
  126. // 判断是否需要验证权限
  127. if (!$this->auth->match($this->noNeedRight)) {
  128. // 判断控制器和方法是否有对应权限
  129. if (!$this->auth->check($path)) {
  130. Hook::listen('admin_nopermission', $this);
  131. $this->error(__('You have no permission'), '');
  132. }
  133. }
  134. }
  135. // 非选项卡时重定向
  136. if (!$this->request->isPost() && !IS_AJAX && !IS_ADDTABS && !IS_DIALOG && input("ref") == 'addtabs') {
  137. $url = preg_replace_callback("/([\?|&]+)ref=addtabs(&?)/i", function ($matches) {
  138. return $matches[2] == '&' ? $matches[1] : '';
  139. }, $this->request->url());
  140. if (Config::get('url_domain_deploy')) {
  141. if (stripos($url, $this->request->server('SCRIPT_NAME')) === 0) {
  142. $url = substr($url, strlen($this->request->server('SCRIPT_NAME')));
  143. }
  144. $url = url($url, '', false);
  145. }
  146. $this->redirect('index/index', [], 302, ['referer' => $url]);
  147. exit;
  148. }
  149. // 设置面包屑导航数据
  150. $breadcrumb = [];
  151. if (!IS_DIALOG && !config('fastadmin.multiplenav') && config('fastadmin.breadcrumb')) {
  152. $breadcrumb = $this->auth->getBreadCrumb($path);
  153. array_pop($breadcrumb);
  154. }
  155. $this->view->breadcrumb = $breadcrumb;
  156. // 如果有使用模板布局
  157. if ($this->layout) {
  158. $this->view->engine->layout('layout/' . $this->layout);
  159. }
  160. // 语言检测
  161. $lang = strip_tags($this->request->langset());
  162. $site = Config::get("site");
  163. $upload = \app\common\model\Config::upload();
  164. // 上传信息配置后
  165. Hook::listen("upload_config_init", $upload);
  166. // 配置信息
  167. $config = [
  168. 'site' => array_intersect_key($site, array_flip(['name', 'indexurl', 'cdnurl', 'version', 'timezone', 'languages'])),
  169. 'upload' => $upload,
  170. 'modulename' => $modulename,
  171. 'controllername' => $controllername,
  172. 'actionname' => $actionname,
  173. 'jsname' => 'backend/' . str_replace('.', '/', $controllername),
  174. 'moduleurl' => rtrim(url("/{$modulename}", '', false), '/'),
  175. 'language' => $lang,
  176. 'referer' => Session::get("referer")
  177. ];
  178. $config = array_merge($config, Config::get("view_replace_str"));
  179. Config::set('upload', array_merge(Config::get('upload'), $upload));
  180. // 配置信息后
  181. Hook::listen("config_init", $config);
  182. //加载当前控制器语言包
  183. $this->loadlang($controllername);
  184. //渲染站点配置
  185. $this->assign('site', $site);
  186. //渲染配置信息
  187. $this->assign('config', $config);
  188. //渲染权限对象
  189. $this->assign('auth', $this->auth);
  190. //渲染管理员对象
  191. $this->assign('admin', Session::get('admin'));
  192. }
  193. /**
  194. * 加载语言文件
  195. * @param string $name
  196. */
  197. protected function loadlang($name)
  198. {
  199. $name = Loader::parseName($name);
  200. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
  201. }
  202. /**
  203. * 渲染配置信息
  204. * @param mixed $name 键名或数组
  205. * @param mixed $value 值
  206. */
  207. protected function assignconfig($name, $value = '')
  208. {
  209. $this->view->config = array_merge($this->view->config ? $this->view->config : [], is_array($name) ? $name : [$name => $value]);
  210. }
  211. /**
  212. * 生成查询所需要的条件,排序方式
  213. * @param mixed $searchfields 快速查询的字段
  214. * @param boolean $relationSearch 是否关联查询
  215. * @return array
  216. */
  217. protected function buildparams($searchfields = null, $relationSearch = null)
  218. {
  219. $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
  220. $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
  221. $search = $this->request->get("search", '');
  222. $filter = $this->request->get("filter", '');
  223. $op = $this->request->get("op", '', 'trim');
  224. $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
  225. $order = $this->request->get("order", "DESC");
  226. $offset = $this->request->get("offset/d", 0);
  227. $limit = $this->request->get("limit/d", 999999);
  228. //新增自动计算页码
  229. $page = $limit ? intval($offset / $limit) + 1 : 1;
  230. if ($this->request->has("page")) {
  231. $page = $this->request->get("page/d", 1);
  232. }
  233. $this->request->get([config('paginate.var_page') => $page]);
  234. $filter = (array)json_decode($filter, true);
  235. $op = (array)json_decode($op, true);
  236. $filter = $filter ? $filter : [];
  237. $where = [];
  238. $alias = [];
  239. $bind = [];
  240. $name = '';
  241. $aliasName = '';
  242. if (!empty($this->model) && $this->relationSearch) {
  243. $name = $this->model->getTable();
  244. $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
  245. $aliasName = $alias[$name] . '.';
  246. }
  247. $sortArr = explode(',', $sort);
  248. foreach ($sortArr as $index => & $item) {
  249. $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
  250. }
  251. unset($item);
  252. $sort = implode(',', $sortArr);
  253. $adminIds = $this->getDataLimitAdminIds();
  254. if (is_array($adminIds)) {
  255. $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
  256. }
  257. if ($search) {
  258. $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
  259. foreach ($searcharr as $k => &$v) {
  260. $v = stripos($v, ".") === false ? $aliasName . $v : $v;
  261. }
  262. unset($v);
  263. $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
  264. }
  265. $index = 0;
  266. foreach ($filter as $k => $v) {
  267. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
  268. continue;
  269. }
  270. $sym = isset($op[$k]) ? $op[$k] : '=';
  271. if (stripos($k, ".") === false) {
  272. $k = $aliasName . $k;
  273. }
  274. $v = !is_array($v) ? trim($v) : $v;
  275. $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
  276. //null和空字符串特殊处理
  277. if (!is_array($v)) {
  278. if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
  279. $sym = strtoupper($v);
  280. }
  281. if (in_array($v, ['""', "''"])) {
  282. $v = '';
  283. $sym = '=';
  284. }
  285. }
  286. switch ($sym) {
  287. case '=':
  288. case '<>':
  289. $where[] = [$k, $sym, (string)$v];
  290. break;
  291. case 'LIKE':
  292. case 'NOT LIKE':
  293. case 'LIKE %...%':
  294. case 'NOT LIKE %...%':
  295. $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
  296. break;
  297. case '>':
  298. case '>=':
  299. case '<':
  300. case '<=':
  301. $where[] = [$k, $sym, intval($v)];
  302. break;
  303. case 'FINDIN':
  304. case 'FINDINSET':
  305. case 'FIND_IN_SET':
  306. $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
  307. $findArr = array_values($v);
  308. foreach ($findArr as $idx => $item) {
  309. $bindName = "item_" . $index . "_" . $idx;
  310. $bind[$bindName] = $item;
  311. $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
  312. }
  313. break;
  314. case 'IN':
  315. case 'IN(...)':
  316. case 'NOT IN':
  317. case 'NOT IN(...)':
  318. $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
  319. break;
  320. case 'BETWEEN':
  321. case 'NOT BETWEEN':
  322. $arr = array_slice(explode(',', $v), 0, 2);
  323. if (stripos($v, ',') === false || !array_filter($arr, function($v){
  324. return $v != '' && $v !== false && $v !== null;
  325. })) {
  326. continue 2;
  327. }
  328. //当出现一边为空时改变操作符
  329. if ($arr[0] === '') {
  330. $sym = $sym == 'BETWEEN' ? '<=' : '>';
  331. $arr = $arr[1];
  332. } elseif ($arr[1] === '') {
  333. $sym = $sym == 'BETWEEN' ? '>=' : '<';
  334. $arr = $arr[0];
  335. }
  336. $where[] = [$k, $sym, $arr];
  337. break;
  338. case 'RANGE':
  339. case 'NOT RANGE':
  340. $v = str_replace(' - ', ',', $v);
  341. $arr = array_slice(explode(',', $v), 0, 2);
  342. if (stripos($v, ',') === false || !array_filter($arr)) {
  343. continue 2;
  344. }
  345. //当出现一边为空时改变操作符
  346. if ($arr[0] === '') {
  347. $sym = $sym == 'RANGE' ? '<=' : '>';
  348. $arr = $arr[1];
  349. } elseif ($arr[1] === '') {
  350. $sym = $sym == 'RANGE' ? '>=' : '<';
  351. $arr = $arr[0];
  352. }
  353. $tableArr = explode('.', $k);
  354. if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
  355. //修复关联模型下时间无法搜索的BUG
  356. $relation = Loader::parseName($tableArr[0], 1, false);
  357. $alias[$this->model->$relation()->getTable()] = $tableArr[0];
  358. }
  359. $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
  360. break;
  361. case 'NULL':
  362. case 'IS NULL':
  363. case 'NOT NULL':
  364. case 'IS NOT NULL':
  365. $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
  366. break;
  367. default:
  368. break;
  369. }
  370. $index++;
  371. }
  372. if (!empty($this->model)) {
  373. $this->model->alias($alias);
  374. }
  375. $model = $this->model;
  376. $where = function ($query) use ($where, $alias, $bind, &$model) {
  377. if (!empty($model)) {
  378. $model->alias($alias);
  379. $model->bind($bind);
  380. }
  381. foreach ($where as $k => $v) {
  382. if (is_array($v)) {
  383. call_user_func_array([$query, 'where'], $v);
  384. } else {
  385. $query->where($v);
  386. }
  387. }
  388. };
  389. return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
  390. }
  391. /**
  392. * 获取数据限制的管理员ID
  393. * 禁用数据限制时返回的是null
  394. * @return mixed
  395. */
  396. protected function getDataLimitAdminIds()
  397. {
  398. if (!$this->dataLimit) {
  399. return null;
  400. }
  401. if ($this->auth->isSuperAdmin()) {
  402. return null;
  403. }
  404. $adminIds = [];
  405. if (in_array($this->dataLimit, ['auth', 'personal'])) {
  406. $adminIds = $this->dataLimit == 'auth' ? $this->auth->getChildrenAdminIds(true) : [$this->auth->id];
  407. }
  408. return $adminIds;
  409. }
  410. /**
  411. * Selectpage的实现方法
  412. *
  413. * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
  414. * 这里示例了所有的参数,所以比较复杂,实现上自己实现只需简单的几行即可
  415. *
  416. */
  417. protected function selectpage()
  418. {
  419. //设置过滤方法
  420. $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);
  421. //搜索关键词,客户端输入以空格分开,这里接收为数组
  422. $word = (array)$this->request->request("q_word/a");
  423. //当前页
  424. $page = $this->request->request("pageNumber");
  425. //分页大小
  426. $pagesize = $this->request->request("pageSize");
  427. //搜索条件
  428. $andor = $this->request->request("andOr", "and", "strtoupper");
  429. //排序方式
  430. $orderby = (array)$this->request->request("orderBy/a");
  431. //显示的字段
  432. $field = $this->request->request("showField");
  433. //主键
  434. $primarykey = $this->request->request("keyField");
  435. //主键值
  436. $primaryvalue = $this->request->request("keyValue");
  437. //搜索字段
  438. $searchfield = (array)$this->request->request("searchField/a");
  439. //自定义搜索条件
  440. $custom = (array)$this->request->request("custom/a");
  441. //是否返回树形结构
  442. $istree = $this->request->request("isTree", 0);
  443. $ishtml = $this->request->request("isHtml", 0);
  444. if ($istree) {
  445. $word = [];
  446. $pagesize = 999999;
  447. }
  448. $order = [];
  449. foreach ($orderby as $k => $v) {
  450. $order[$v[0]] = $v[1];
  451. }
  452. $field = $field ? $field : 'name';
  453. //如果有primaryvalue,说明当前是初始化传值
  454. if ($primaryvalue !== null) {
  455. $where = [$primarykey => ['in', $primaryvalue]];
  456. $pagesize = 999999;
  457. } else {
  458. $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
  459. $logic = $andor == 'AND' ? '&' : '|';
  460. $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
  461. $searchfield = str_replace(',', $logic, $searchfield);
  462. $word = array_filter(array_unique($word));
  463. if (count($word) == 1) {
  464. $query->where($searchfield, "like", "%" . reset($word) . "%");
  465. } else {
  466. $query->where(function ($query) use ($word, $searchfield) {
  467. foreach ($word as $index => $item) {
  468. $query->whereOr(function ($query) use ($item, $searchfield) {
  469. $query->where($searchfield, "like", "%{$item}%");
  470. });
  471. }
  472. });
  473. }
  474. if ($custom && is_array($custom)) {
  475. foreach ($custom as $k => $v) {
  476. if (is_array($v) && 2 == count($v)) {
  477. $query->where($k, trim($v[0]), $v[1]);
  478. } else {
  479. $query->where($k, '=', $v);
  480. }
  481. }
  482. }
  483. };
  484. }
  485. $adminIds = $this->getDataLimitAdminIds();
  486. if (is_array($adminIds)) {
  487. $this->model->where($this->dataLimitField, 'in', $adminIds);
  488. }
  489. $list = [];
  490. $total = $this->model->where($where)->count();
  491. if ($total > 0) {
  492. if (is_array($adminIds)) {
  493. $this->model->where($this->dataLimitField, 'in', $adminIds);
  494. }
  495. $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);
  496. //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
  497. if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
  498. $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
  499. //修复自定义data-primary-key为字符串内容时,给排序字段添加上引号
  500. $primaryvalue = array_map(function ($value) {
  501. return '\'' . $value . '\'';
  502. }, $primaryvalue);
  503. $primaryvalue = implode(',', $primaryvalue);
  504. $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
  505. } else {
  506. $this->model->order($order);
  507. }
  508. $datalist = $this->model->where($where)
  509. ->page($page, $pagesize)
  510. ->select();
  511. foreach ($datalist as $index => $item) {
  512. unset($item['password'], $item['salt']);
  513. if ($this->selectpageFields == '*') {
  514. $result = [
  515. $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
  516. $field => isset($item[$field]) ? $item[$field] : '',
  517. ];
  518. } else {
  519. $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
  520. }
  521. $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
  522. $list[] = $result;
  523. }
  524. if ($istree && !$primaryvalue) {
  525. $tree = Tree::instance();
  526. $tree->init(collection($list)->toArray(), 'pid');
  527. $list = $tree->getTreeList($tree->getTreeArray(0), $field);
  528. if (!$ishtml) {
  529. foreach ($list as &$item) {
  530. $item = str_replace('&nbsp;', ' ', $item);
  531. }
  532. unset($item);
  533. }
  534. }
  535. }
  536. //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
  537. return json(['list' => $list, 'total' => $total]);
  538. }
  539. /**
  540. * 刷新Token
  541. */
  542. protected function token()
  543. {
  544. $token = $this->request->param('__token__');
  545. //验证Token
  546. if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
  547. $this->error(__('Token verification error'), '', ['__token__' => $this->request->token()]);
  548. }
  549. //刷新Token
  550. $this->request->token();
  551. }
  552. }