Backend.php 23 KB

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