Backend.php 19 KB

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