Backend.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. // 配置信息后
  144. Hook::listen("config_init", $config);
  145. //加载当前控制器语言包
  146. $this->loadlang($controllername);
  147. //渲染站点配置
  148. $this->assign('site', $site);
  149. //渲染配置信息
  150. $this->assign('config', $config);
  151. //渲染权限对象
  152. $this->assign('auth', $this->auth);
  153. //渲染管理员对象
  154. $this->assign('admin', Session::get('admin'));
  155. }
  156. /**
  157. * 加载语言文件
  158. * @param string $name
  159. */
  160. protected function loadlang($name)
  161. {
  162. Lang::load(APP_PATH . $this->request->module() . '/lang/' . Lang::detect() . '/' . str_replace('.', '/', $name) . '.php');
  163. }
  164. /**
  165. * 渲染配置信息
  166. * @param mixed $name 键名或数组
  167. * @param mixed $value 值
  168. */
  169. protected function assignconfig($name, $value = '')
  170. {
  171. $this->view->config = array_merge($this->view->config ? $this->view->config : [], is_array($name) ? $name : [$name => $value]);
  172. }
  173. /**
  174. * 生成查询所需要的条件,排序方式
  175. * @param mixed $searchfields 快速查询的字段
  176. * @param boolean $relationSearch 是否关联查询
  177. * @return array
  178. */
  179. protected function buildparams($searchfields = null, $relationSearch = null)
  180. {
  181. $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
  182. $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
  183. $search = $this->request->get("search", '');
  184. $filter = $this->request->get("filter", '');
  185. $op = $this->request->get("op", '', 'trim');
  186. $sort = $this->request->get("sort", "id");
  187. $order = $this->request->get("order", "DESC");
  188. $offset = $this->request->get("offset", 0);
  189. $limit = $this->request->get("limit", 0);
  190. $filter = json_decode($filter, TRUE);
  191. $op = json_decode($op, TRUE);
  192. $filter = $filter ? $filter : [];
  193. $where = [];
  194. $tableName = '';
  195. if ($relationSearch)
  196. {
  197. if (!empty($this->model))
  198. {
  199. $class = get_class($this->model);
  200. $name = basename(str_replace('\\', '/', $class));
  201. $tableName = $this->model->getQuery()->getTable($name) . ".";
  202. }
  203. $sort = stripos($sort, ".") === false ? $tableName . $sort : $sort;
  204. }
  205. $adminIds = $this->getDataLimitAdminIds();
  206. if (is_array($adminIds))
  207. {
  208. $where[] = [$this->dataLimitField, 'in', $adminIds];
  209. }
  210. if ($search)
  211. {
  212. $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
  213. foreach ($searcharr as $k => &$v)
  214. {
  215. $v = stripos($v, ".") === false ? $tableName . $v : $v;
  216. }
  217. unset($v);
  218. $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
  219. }
  220. foreach ($filter as $k => $v)
  221. {
  222. $sym = isset($op[$k]) ? $op[$k] : '=';
  223. if (stripos($k, ".") === false)
  224. {
  225. $k = $tableName . $k;
  226. }
  227. $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
  228. switch ($sym)
  229. {
  230. case '=':
  231. case '!=':
  232. $where[] = [$k, $sym, (string) $v];
  233. break;
  234. case 'LIKE':
  235. case 'NOT LIKE':
  236. case 'LIKE %...%':
  237. case 'NOT LIKE %...%':
  238. $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
  239. break;
  240. case '>':
  241. case '>=':
  242. case '<':
  243. case '<=':
  244. $where[] = [$k, $sym, intval($v)];
  245. break;
  246. case 'IN':
  247. case 'IN(...)':
  248. case 'NOT IN':
  249. case 'NOT IN(...)':
  250. $where[] = [$k, str_replace('(...)', '', $sym), explode(',', $v)];
  251. break;
  252. case 'BETWEEN':
  253. case 'NOT BETWEEN':
  254. $arr = array_slice(explode(',', $v), 0, 2);
  255. if (stripos($v, ',') === false || !array_filter($arr))
  256. continue;
  257. //当出现一边为空时改变操作符
  258. if ($arr[0] === '')
  259. {
  260. $sym = $sym == 'BETWEEN' ? '<=' : '>';
  261. $arr = $arr[1];
  262. }
  263. else if ($arr[1] === '')
  264. {
  265. $sym = $sym == 'BETWEEN' ? '>=' : '<';
  266. $arr = $arr[0];
  267. }
  268. $where[] = [$k, $sym, $arr];
  269. break;
  270. case 'RANGE':
  271. case 'NOT RANGE':
  272. $v = str_replace(' - ', ',', $v);
  273. $arr = array_slice(explode(',', $v), 0, 2);
  274. if (stripos($v, ',') === false || !array_filter($arr))
  275. continue;
  276. $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
  277. break;
  278. case 'LIKE':
  279. case 'LIKE %...%':
  280. $where[] = [$k, 'LIKE', "%{$v}%"];
  281. break;
  282. case 'NULL':
  283. case 'IS NULL':
  284. case 'NOT NULL':
  285. case 'IS NOT NULL':
  286. $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
  287. break;
  288. default:
  289. break;
  290. }
  291. }
  292. $where = function($query) use ($where) {
  293. foreach ($where as $k => $v)
  294. {
  295. if (is_array($v))
  296. {
  297. call_user_func_array([$query, 'where'], $v);
  298. }
  299. else
  300. {
  301. $query->where($v);
  302. }
  303. }
  304. };
  305. return [$where, $sort, $order, $offset, $limit];
  306. }
  307. /**
  308. * 获取数据限制的管理员ID
  309. * 禁用数据限制时返回的是null
  310. * @return mixed
  311. */
  312. protected function getDataLimitAdminIds()
  313. {
  314. if (!$this->dataLimit)
  315. {
  316. return null;
  317. }
  318. $adminIds = [];
  319. if (in_array($this->dataLimit, ['auth', 'personal']))
  320. {
  321. $adminIds = $this->dataLimit == 'auth' ? $this->auth->getChildrenAdminIds(true) : [$this->auth->id];
  322. }
  323. return $adminIds;
  324. }
  325. /**
  326. * Selectpage的实现方法
  327. *
  328. * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
  329. * 这里示例了所有的参数,所以比较复杂,实现上自己实现只需简单的几行即可
  330. *
  331. */
  332. protected function selectpage()
  333. {
  334. //设置过滤方法
  335. $this->request->filter(['strip_tags', 'htmlspecialchars']);
  336. //搜索关键词,客户端输入以空格分开,这里接收为数组
  337. $word = (array) $this->request->request("q_word/a");
  338. //当前页
  339. $page = $this->request->request("page");
  340. //分页大小
  341. $pagesize = $this->request->request("per_page");
  342. //搜索条件
  343. $andor = $this->request->request("and_or");
  344. //排序方式
  345. $orderby = (array) $this->request->request("order_by/a");
  346. //显示的字段
  347. $field = $this->request->request("field");
  348. //主键
  349. $primarykey = $this->request->request("pkey_name");
  350. //主键值
  351. $primaryvalue = $this->request->request("pkey_value");
  352. //搜索字段
  353. $searchfield = (array) $this->request->request("search_field/a");
  354. //自定义搜索条件
  355. $custom = (array) $this->request->request("custom/a");
  356. $order = [];
  357. foreach ($orderby as $k => $v)
  358. {
  359. $order[$v[0]] = $v[1];
  360. }
  361. $field = $field ? $field : 'name';
  362. //如果有primaryvalue,说明当前是初始化传值
  363. if ($primaryvalue !== null)
  364. {
  365. $where = [$primarykey => ['in', $primaryvalue]];
  366. }
  367. else
  368. {
  369. $where = function($query) use($word, $andor, $field, $searchfield, $custom) {
  370. foreach ($word as $k => $v)
  371. {
  372. foreach ($searchfield as $m => $n)
  373. {
  374. $query->where($n, "like", "%{$v}%", $andor);
  375. }
  376. }
  377. if ($custom && is_array($custom))
  378. {
  379. foreach ($custom as $k => $v)
  380. {
  381. $query->where($k, '=', $v);
  382. }
  383. }
  384. };
  385. }
  386. $adminIds = $this->getDataLimitAdminIds();
  387. if (is_array($adminIds))
  388. {
  389. $this->model->where($this->dataLimitField, 'in', $adminIds);
  390. }
  391. $list = [];
  392. $total = $this->model->where($where)->count();
  393. if ($total > 0)
  394. {
  395. if (is_array($adminIds))
  396. {
  397. $this->model->where($this->dataLimitField, 'in', $adminIds);
  398. }
  399. $list = $this->model->where($where)
  400. ->order($order)
  401. ->page($page, $pagesize)
  402. ->field("{$primarykey},{$field}")
  403. ->field("password,salt", true)
  404. ->select();
  405. }
  406. //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
  407. return json(['list' => $list, 'total' => $total]);
  408. }
  409. }