Backend.php 15 KB

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