Backend.php 17 KB

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