Backend.php 17 KB

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