Backend.php 16 KB

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