Backend.php 18 KB

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