Backend.php 16 KB

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