Backend.php 16 KB

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