Backend.php 22 KB

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