You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

528 lines
18 KiB

  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\Session;
  10. use fast\Tree;
  11. use think\Validate;
  12. /**
  13. * 后台控制器基类
  14. */
  15. class Backend extends Controller
  16. {
  17. /**
  18. * 无需登录的方法,同时也就不需要鉴权了
  19. * @var array
  20. */
  21. protected $noNeedLogin = [];
  22. /**
  23. * 无需鉴权的方法,但需要登录
  24. * @var array
  25. */
  26. protected $noNeedRight = [];
  27. /**
  28. * 布局模板
  29. * @var string
  30. */
  31. protected $layout = 'default';
  32. /**
  33. * 权限控制类
  34. * @var Auth
  35. */
  36. protected $auth = null;
  37. /**
  38. * 模型对象
  39. * @var \think\Model
  40. */
  41. protected $model = null;
  42. /**
  43. * 快速搜索时执行查找的字段
  44. */
  45. protected $searchFields = 'id';
  46. /**
  47. * 是否是关联查询
  48. */
  49. protected $relationSearch = false;
  50. /**
  51. * 是否开启数据限制
  52. * 支持auth/personal
  53. * 表示按权限判断/仅限个人
  54. * 默认为禁用,若启用请务必保证表中存在admin_id字段
  55. */
  56. protected $dataLimit = false;
  57. /**
  58. * 数据限制字段
  59. */
  60. protected $dataLimitField = 'admin_id';
  61. /**
  62. * 数据限制开启时自动填充限制字段值
  63. */
  64. protected $dataLimitFieldAutoFill = true;
  65. /**
  66. * 是否开启Validate验证
  67. */
  68. protected $modelValidate = false;
  69. /**
  70. * 是否开启模型场景验证
  71. */
  72. protected $modelSceneValidate = false;
  73. /**
  74. * Multi方法可批量修改的字段
  75. */
  76. protected $multiFields = 'status';
  77. /**
  78. * Selectpage可显示的字段
  79. */
  80. protected $selectpageFields = '*';
  81. /**
  82. * 前台提交过来,需要排除的字段数据
  83. */
  84. protected $excludeFields = "";
  85. /**
  86. * 导入文件首行类型
  87. * 支持comment/name
  88. * 表示注释或字段名
  89. */
  90. protected $importHeadType = 'comment';
  91. /**
  92. * 引入后台控制器的traits
  93. */
  94. use \app\admin\library\traits\Backend;
  95. public function _initialize()
  96. {
  97. $modulename = $this->request->module();
  98. $controllername = Loader::parseName($this->request->controller());
  99. $actionname = strtolower($this->request->action());
  100. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  101. // 定义是否Addtabs请求
  102. !defined('IS_ADDTABS') && define('IS_ADDTABS', input("addtabs") ? true : false);
  103. // 定义是否Dialog请求
  104. !defined('IS_DIALOG') && define('IS_DIALOG', input("dialog") ? true : false);
  105. // 定义是否AJAX请求
  106. !defined('IS_AJAX') && define('IS_AJAX', $this->request->isAjax());
  107. $this->auth = Auth::instance();
  108. // 设置当前请求的URI
  109. $this->auth->setRequestUri($path);
  110. // 检测是否需要验证登录
  111. if (!$this->auth->match($this->noNeedLogin)) {
  112. //检测是否登录
  113. if (!$this->auth->isLogin()) {
  114. Hook::listen('admin_nologin', $this);
  115. $url = Session::get('referer');
  116. $url = $url ? $url : $this->request->url();
  117. if ($url == '/') {
  118. $this->redirect('index/login', [], 302, ['referer' => $url]);
  119. exit;
  120. }
  121. $this->error(__('Please login first'), url('index/login', ['url' => $url]));
  122. }
  123. // 判断是否需要验证权限
  124. if (!$this->auth->match($this->noNeedRight)) {
  125. // 判断控制器和方法判断是否有对应权限
  126. if (!$this->auth->check($path)) {
  127. Hook::listen('admin_nopermission', $this);
  128. $this->error(__('You have no permission'), '');
  129. }
  130. }
  131. }
  132. // 非选项卡时重定向
  133. if (!$this->request->isPost() && !IS_AJAX && !IS_ADDTABS && !IS_DIALOG && input("ref") == 'addtabs') {
  134. $url = preg_replace_callback("/([\?|&]+)ref=addtabs(&?)/i", function ($matches) {
  135. return $matches[2] == '&' ? $matches[1] : '';
  136. }, $this->request->url());
  137. if (Config::get('url_domain_deploy')) {
  138. if (stripos($url, $this->request->server('SCRIPT_NAME')) === 0) {
  139. $url = substr($url, strlen($this->request->server('SCRIPT_NAME')));
  140. }
  141. $url = url($url, '', false);
  142. }
  143. $this->redirect('index/index', [], 302, ['referer' => $url]);
  144. exit;
  145. }
  146. // 设置面包屑导航数据
  147. $breadcrumb = $this->auth->getBreadCrumb($path);
  148. array_pop($breadcrumb);
  149. $this->view->breadcrumb = $breadcrumb;
  150. // 如果有使用模板布局
  151. if ($this->layout) {
  152. $this->view->engine->layout('layout/' . $this->layout);
  153. }
  154. // 语言检测
  155. $lang = strip_tags($this->request->langset());
  156. $site = Config::get("site");
  157. $upload = \app\common\model\Config::upload();
  158. // 上传信息配置后
  159. Hook::listen("upload_config_init", $upload);
  160. // 配置信息
  161. $config = [
  162. 'site' => array_intersect_key($site, array_flip(['name', 'indexurl', 'cdnurl', 'version', 'timezone', 'languages'])),
  163. 'upload' => $upload,
  164. 'modulename' => $modulename,
  165. 'controllername' => $controllername,
  166. 'actionname' => $actionname,
  167. 'jsname' => 'backend/' . str_replace('.', '/', $controllername),
  168. 'moduleurl' => rtrim(url("/{$modulename}", '', false), '/'),
  169. 'language' => $lang,
  170. 'referer' => Session::get("referer")
  171. ];
  172. $config = array_merge($config, Config::get("view_replace_str"));
  173. Config::set('upload', array_merge(Config::get('upload'), $upload));
  174. // 配置信息后
  175. Hook::listen("config_init", $config);
  176. //加载当前控制器语言包
  177. $this->loadlang($controllername);
  178. //渲染站点配置
  179. $this->assign('site', $site);
  180. //渲染配置信息
  181. $this->assign('config', $config);
  182. //渲染权限对象
  183. $this->assign('auth', $this->auth);
  184. //渲染管理员对象
  185. $this->assign('admin', Session::get('admin'));
  186. }
  187. /**
  188. * 加载语言文件
  189. * @param string $name
  190. */
  191. protected function loadlang($name)
  192. {
  193. $name = Loader::parseName($name);
  194. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
  195. }
  196. /**
  197. * 渲染配置信息
  198. * @param mixed $name 键名或数组
  199. * @param mixed $value 值
  200. */
  201. protected function assignconfig($name, $value = '')
  202. {
  203. $this->view->config = array_merge($this->view->config ? $this->view->config : [], is_array($name) ? $name : [$name => $value]);
  204. }
  205. /**
  206. * 生成查询所需要的条件,排序方式
  207. * @param mixed $searchfields 快速查询的字段
  208. * @param boolean $relationSearch 是否关联查询
  209. * @return array
  210. */
  211. protected function buildparams($searchfields = null, $relationSearch = null)
  212. {
  213. $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
  214. $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
  215. $search = $this->request->get("search", '');
  216. $filter = $this->request->get("filter", '');
  217. $op = $this->request->get("op", '', 'trim');
  218. $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
  219. $order = $this->request->get("order", "DESC");
  220. $offset = $this->request->get("offset", 0);
  221. $limit = $this->request->get("limit", 0);
  222. $filter = (array)json_decode($filter, true);
  223. $op = (array)json_decode($op, true);
  224. $filter = $filter ? $filter : [];
  225. $where = [];
  226. $tableName = '';
  227. if ($relationSearch) {
  228. if (!empty($this->model)) {
  229. $name = \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
  230. $name = $this->model->getTable();
  231. $tableName = $name . '.';
  232. }
  233. $sortArr = explode(',', $sort);
  234. foreach ($sortArr as $index => & $item) {
  235. $item = stripos($item, ".") === false ? $tableName . trim($item) : $item;
  236. }
  237. unset($item);
  238. $sort = implode(',', $sortArr);
  239. }
  240. $adminIds = $this->getDataLimitAdminIds();
  241. if (is_array($adminIds)) {
  242. $where[] = [$tableName . $this->dataLimitField, 'in', $adminIds];
  243. }
  244. if ($search) {
  245. $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
  246. foreach ($searcharr as $k => &$v) {
  247. $v = stripos($v, ".") === false ? $tableName . $v : $v;
  248. }
  249. unset($v);
  250. $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
  251. }
  252. foreach ($filter as $k => $v) {
  253. $sym = isset($op[$k]) ? $op[$k] : '=';
  254. if (stripos($k, ".") === false) {
  255. $k = $tableName . $k;
  256. }
  257. $v = !is_array($v) ? trim($v) : $v;
  258. $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
  259. switch ($sym) {
  260. case '=':
  261. case '<>':
  262. $where[] = [$k, $sym, (string)$v];
  263. break;
  264. case 'LIKE':
  265. case 'NOT LIKE':
  266. case 'LIKE %...%':
  267. case 'NOT LIKE %...%':
  268. $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
  269. break;
  270. case '>':
  271. case '>=':
  272. case '<':
  273. case '<=':
  274. $where[] = [$k, $sym, intval($v)];
  275. break;
  276. case 'FINDIN':
  277. case 'FINDINSET':
  278. case 'FIND_IN_SET':
  279. $where[] = "FIND_IN_SET('{$v}', " . ($relationSearch ? $k : '`' . str_replace('.', '`.`', $k) . '`') . ")";
  280. break;
  281. case 'IN':
  282. case 'IN(...)':
  283. case 'NOT IN':
  284. case 'NOT IN(...)':
  285. $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
  286. break;
  287. case 'BETWEEN':
  288. case 'NOT BETWEEN':
  289. $arr = array_slice(explode(',', $v), 0, 2);
  290. if (stripos($v, ',') === false || !array_filter($arr)) {
  291. continue 2;
  292. }
  293. //当出现一边为空时改变操作符
  294. if ($arr[0] === '') {
  295. $sym = $sym == 'BETWEEN' ? '<=' : '>';
  296. $arr = $arr[1];
  297. } elseif ($arr[1] === '') {
  298. $sym = $sym == 'BETWEEN' ? '>=' : '<';
  299. $arr = $arr[0];
  300. }
  301. $where[] = [$k, $sym, $arr];
  302. break;
  303. case 'RANGE':
  304. case 'NOT RANGE':
  305. $v = str_replace(' - ', ',', $v);
  306. $arr = array_slice(explode(',', $v), 0, 2);
  307. if (stripos($v, ',') === false || !array_filter($arr)) {
  308. continue 2;
  309. }
  310. //当出现一边为空时改变操作符
  311. if ($arr[0] === '') {
  312. $sym = $sym == 'RANGE' ? '<=' : '>';
  313. $arr = $arr[1];
  314. } elseif ($arr[1] === '') {
  315. $sym = $sym == 'RANGE' ? '>=' : '<';
  316. $arr = $arr[0];
  317. }
  318. $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
  319. break;
  320. case 'LIKE':
  321. case 'LIKE %...%':
  322. $where[] = [$k, 'LIKE', "%{$v}%"];
  323. break;
  324. case 'NULL':
  325. case 'IS NULL':
  326. case 'NOT NULL':
  327. case 'IS NOT NULL':
  328. $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
  329. break;
  330. default:
  331. break;
  332. }
  333. }
  334. $where = function ($query) use ($where) {
  335. foreach ($where as $k => $v) {
  336. if (is_array($v)) {
  337. call_user_func_array([$query, 'where'], $v);
  338. } else {
  339. $query->where($v);
  340. }
  341. }
  342. };
  343. return [$where, $sort, $order, $offset, $limit];
  344. }
  345. /**
  346. * 获取数据限制的管理员ID
  347. * 禁用数据限制时返回的是null
  348. * @return mixed
  349. */
  350. protected function getDataLimitAdminIds()
  351. {
  352. if (!$this->dataLimit) {
  353. return null;
  354. }
  355. if ($this->auth->isSuperAdmin()) {
  356. return null;
  357. }
  358. $adminIds = [];
  359. if (in_array($this->dataLimit, ['auth', 'personal'])) {
  360. $adminIds = $this->dataLimit == 'auth' ? $this->auth->getChildrenAdminIds(true) : [$this->auth->id];
  361. }
  362. return $adminIds;
  363. }
  364. /**
  365. * Selectpage的实现方法
  366. *
  367. * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
  368. * 这里示例了所有的参数,所以比较复杂,实现上自己实现只需简单的几行即可
  369. *
  370. */
  371. protected function selectpage()
  372. {
  373. //设置过滤方法
  374. $this->request->filter(['strip_tags', 'htmlspecialchars']);
  375. //搜索关键词,客户端输入以空格分开,这里接收为数组
  376. $word = (array)$this->request->request("q_word/a");
  377. //当前页
  378. $page = $this->request->request("pageNumber");
  379. //分页大小
  380. $pagesize = $this->request->request("pageSize");
  381. //搜索条件
  382. $andor = $this->request->request("andOr", "and", "strtoupper");
  383. //排序方式
  384. $orderby = (array)$this->request->request("orderBy/a");
  385. //显示的字段
  386. $field = $this->request->request("showField");
  387. //主键
  388. $primarykey = $this->request->request("keyField");
  389. //主键值
  390. $primaryvalue = $this->request->request("keyValue");
  391. //搜索字段
  392. $searchfield = (array)$this->request->request("searchField/a");
  393. //自定义搜索条件
  394. $custom = (array)$this->request->request("custom/a");
  395. //是否返回树形结构
  396. $istree = $this->request->request("isTree", 0);
  397. $ishtml = $this->request->request("isHtml", 0);
  398. if ($istree) {
  399. $word = [];
  400. $pagesize = 99999;
  401. }
  402. $order = [];
  403. foreach ($orderby as $k => $v) {
  404. $order[$v[0]] = $v[1];
  405. }
  406. $field = $field ? $field : 'name';
  407. //如果有primaryvalue,说明当前是初始化传值
  408. if ($primaryvalue !== null) {
  409. $where = [$primarykey => ['in', $primaryvalue]];
  410. $pagesize = 99999;
  411. } else {
  412. $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
  413. $logic = $andor == 'AND' ? '&' : '|';
  414. $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
  415. foreach ($word as $k => $v) {
  416. $query->where(str_replace(',', $logic, $searchfield), "like", "%{$v}%");
  417. }
  418. if ($custom && is_array($custom)) {
  419. foreach ($custom as $k => $v) {
  420. if (is_array($v) && 2 == count($v)) {
  421. $query->where($k, trim($v[0]), $v[1]);
  422. } else {
  423. $query->where($k, '=', $v);
  424. }
  425. }
  426. }
  427. };
  428. }
  429. $adminIds = $this->getDataLimitAdminIds();
  430. if (is_array($adminIds)) {
  431. $this->model->where($this->dataLimitField, 'in', $adminIds);
  432. }
  433. $list = [];
  434. $total = $this->model->where($where)->count();
  435. if ($total > 0) {
  436. if (is_array($adminIds)) {
  437. $this->model->where($this->dataLimitField, 'in', $adminIds);
  438. }
  439. $datalist = $this->model->where($where)
  440. ->order($order)
  441. ->page($page, $pagesize)
  442. ->field($this->selectpageFields)
  443. ->select();
  444. foreach ($datalist as $index => $item) {
  445. unset($item['password'], $item['salt']);
  446. $list[] = [
  447. $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
  448. $field => isset($item[$field]) ? $item[$field] : '',
  449. 'pid' => isset($item['pid']) ? $item['pid'] : 0
  450. ];
  451. }
  452. if ($istree && !$primaryvalue) {
  453. $tree = Tree::instance();
  454. $tree->init(collection($list)->toArray(), 'pid');
  455. $list = $tree->getTreeList($tree->getTreeArray(0), $field);
  456. if (!$ishtml) {
  457. foreach ($list as &$item) {
  458. $item = str_replace('&nbsp;', ' ', $item);
  459. }
  460. unset($item);
  461. }
  462. }
  463. }
  464. //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
  465. return json(['list' => $list, 'total' => $total]);
  466. }
  467. /**
  468. * 刷新Token
  469. */
  470. protected function token()
  471. {
  472. $token = $this->request->post('__token__');
  473. //验证Token
  474. if (!Validate::is($token, "token", ['__token__' => $token])) {
  475. $this->error(__('Token verification error'), '', ['__token__' => $this->request->token()]);
  476. }
  477. //刷新Token
  478. $this->request->token();
  479. }
  480. }