暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Yzncms [ 御宅男工作室 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2018 http://yzncms.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: fastadmin: https://www.fastadmin.net/
  10. // +----------------------------------------------------------------------
  11. // +----------------------------------------------------------------------
  12. // | 后台控制模块
  13. // +----------------------------------------------------------------------
  14. namespace app\common\controller;
  15. use app\admin\service\User;
  16. use think\facade\Config;
  17. use think\facade\Hook;
  18. use think\facade\Session;
  19. use think\Validate;
  20. //定义是后台
  21. define('IN_ADMIN', true);
  22. class Adminbase extends Base
  23. {
  24. //无需登录的方法,同时也就不需要鉴权了
  25. protected $noNeedLogin = [];
  26. //无需鉴权的方法,但需要登录
  27. protected $noNeedRight = [];
  28. //当前登录账号信息
  29. //public $_userinfo;
  30. //Multi方法可批量修改的字段
  31. protected $multiFields = 'status,listorder';
  32. /**
  33. * 权限控制类
  34. * @var Auth
  35. */
  36. protected $auth = null;
  37. //模型对象
  38. protected $modelClass = null;
  39. //快速搜索时执行查找的字段
  40. protected $searchFields = 'id';
  41. //Selectpage可显示的字段
  42. protected $selectpageFields = '*';
  43. //是否是关联查询
  44. protected $relationSearch = false;
  45. //前台提交过来,需要排除的字段数据
  46. protected $excludeFields = "";
  47. /**
  48. * 是否开启数据限制
  49. * 支持auth/personal
  50. * 表示按权限判断/仅限个人
  51. * 默认为禁用,若启用请务必保证表中存在admin_id字段
  52. */
  53. protected $dataLimit = false;
  54. //数据限制字段
  55. protected $dataLimitField = 'admin_id';
  56. //数据限制开启时自动填充限制字段值
  57. protected $dataLimitFieldAutoFill = true;
  58. //是否开启Validate验证
  59. protected $modelValidate = false;
  60. //是否开启模型场景验证
  61. protected $modelSceneValidate = false;
  62. /*
  63. * 引入后台控制器的traits
  64. */
  65. use \app\admin\library\traits\Curd;
  66. //初始化
  67. protected function initialize()
  68. {
  69. parent::initialize();
  70. $this->auth = User::instance();
  71. $modulename = $this->request->module();
  72. $controllername = parse_name($this->request->controller());
  73. $actionname = strtolower($this->request->action());
  74. $path = $controllername . '/' . $actionname;
  75. // 定义是否Dialog请求
  76. !defined('IS_DIALOG') && define('IS_DIALOG', $this->request->param("dialog") ? true : false);
  77. // 检测是否需要验证登录
  78. if (!$this->auth->match($this->noNeedLogin)) {
  79. if (defined('UID')) {
  80. return;
  81. }
  82. if (!$this->auth->isLogin()) {
  83. Hook::listen('admin_nologin', $this);
  84. $this->error('请先登陆', url('admin/index/login'));
  85. }
  86. define('UID', (int) $this->auth->id);
  87. // 是否是超级管理员
  88. define('IS_ROOT', $this->auth->isAdministrator());
  89. if (!IS_ROOT && config::get('site.admin_forbid_ip')) {
  90. // 检查IP地址访问
  91. $arr = explode(',', config::get('site.admin_forbid_ip'));
  92. foreach ($arr as $val) {
  93. //是否是IP段
  94. if (strpos($val, '*')) {
  95. if (strpos($this->request->ip(), str_replace('.*', '', $val)) !== false) {
  96. $this->error('403:你在IP禁止段内,禁止访问!');
  97. }
  98. } else {
  99. //不是IP段,用绝对匹配
  100. if ($this->request->ip() == $val) {
  101. $this->error('403:IP地址绝对匹配,禁止访问!');
  102. }
  103. }
  104. }
  105. }
  106. if (!IS_ROOT && !$this->auth->match($this->noNeedRight)) {
  107. //检测访问权限
  108. if (!$this->auth->check($path)) {
  109. Hook::listen('admin_nopermission', $this);
  110. $this->error('未授权访问!');
  111. }
  112. }
  113. }
  114. $site = Config::get("site.");
  115. $config = [
  116. 'modulename' => $modulename,
  117. 'controllername' => $controllername,
  118. 'actionname' => $actionname,
  119. ];
  120. //监听插件传入的变量
  121. $site = array_merge($site, $config, ...Hook::listen("config_init"));
  122. $this->assign('site', $site);
  123. $this->assign('auth', $this->auth);
  124. $this->assign('userInfo', Session::get('admin'));
  125. $this->view->filter(function ($content) {
  126. return Hook::listen("admin_view_filter", $content, true) ?: $content;
  127. });
  128. }
  129. /**
  130. * 渲染配置信息
  131. * @param mixed $name 键名或数组
  132. * @param mixed $value 值
  133. */
  134. protected function assignconfig($name, $value = '')
  135. {
  136. $this->view->site = array_merge($this->view->site ? $this->view->site : [], is_array($name) ? $name : [$name => $value]);
  137. }
  138. /**
  139. * 构建请求参数
  140. * @param mixed $searchfields 快速查询的字段
  141. * @param array $excludeFields 忽略构建搜索的字段
  142. * @param boolean $relationSearch 是否关联查询
  143. * @return array
  144. */
  145. protected function buildTableParames($searchfields = null, $excludeFields = [], $relationSearch = null)
  146. {
  147. $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
  148. $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
  149. $search = $this->request->get("search", '');
  150. $filter = $this->request->get("filter", '');
  151. $op = $this->request->get("op", '', 'trim');
  152. $sort = $this->request->get("sort", !empty($this->modelClass) && $this->modelClass->getPk() ? $this->modelClass->getPk() : 'id');
  153. $order = $this->request->get("order", "DESC");
  154. $limit = $this->request->get("limit/d", 999999);
  155. $page = $this->request->get("page/d", 1);
  156. //新增自动计算分页偏移
  157. $offset = $page ? ($page - 1) * $limit : 0;
  158. if ($this->request->has("offset")) {
  159. $offset = $this->request->get("offset/d", 0);
  160. }
  161. $this->request->withGet([config::get('paginate.var_page') => $page]);
  162. $filter = (array) json_decode($filter, true);
  163. $op = (array) json_decode($op, true);
  164. $filter = $filter ? $filter : [];
  165. $where = [];
  166. $alias = [];
  167. $bind = [];
  168. $name = '';
  169. $aliasName = '';
  170. if (!empty($this->modelClass) && $relationSearch) {
  171. $name = $this->modelClass->getTable();
  172. $alias[$name] = parse_name(basename(str_replace('\\', '/', get_class($this->modelClass))));
  173. $aliasName = $alias[$name] . '.';
  174. }
  175. $sortArr = explode(',', $sort);
  176. foreach ($sortArr as $index => &$item) {
  177. $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
  178. }
  179. unset($item);
  180. $sort = implode(',', $sortArr);
  181. $adminIds = $this->getDataLimitAdminIds();
  182. if (is_array($adminIds)) {
  183. $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
  184. }
  185. if ($search) {
  186. $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
  187. foreach ($searcharr as $k => &$v) {
  188. $v = stripos($v, ".") === false ? $aliasName . $v : $v;
  189. }
  190. unset($v);
  191. $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
  192. }
  193. $index = 0;
  194. foreach ($filter as $k => $v) {
  195. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
  196. continue;
  197. }
  198. $sym = isset($op[$k]) ? $op[$k] : '=';
  199. if (stripos($k, ".") === false) {
  200. $k = $aliasName . $k;
  201. }
  202. $v = !is_array($v) ? trim($v) : $v;
  203. $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
  204. //null和空字符串特殊处理
  205. if (!is_array($v)) {
  206. if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
  207. $sym = strtoupper($v);
  208. }
  209. if (in_array($v, ['""', "''"])) {
  210. $v = '';
  211. $sym = '=';
  212. }
  213. }
  214. switch ($sym) {
  215. case '=':
  216. case '<>':
  217. $where[] = [$k, $sym, (string) $v];
  218. break;
  219. case 'LIKE':
  220. case 'NOT LIKE':
  221. case 'LIKE %...%':
  222. case 'NOT LIKE %...%':
  223. $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
  224. break;
  225. case '>':
  226. case '>=':
  227. case '<':
  228. case '<=':
  229. $where[] = [$k, $sym, intval($v)];
  230. break;
  231. case 'FINDIN':
  232. case 'FINDINSET':
  233. case 'FIND_IN_SET':
  234. $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
  235. $findArr = array_values($v);
  236. foreach ($findArr as $idx => $item) {
  237. $bindName = "item_" . $index . "_" . $idx;
  238. $bind[$bindName] = $item;
  239. $where[] = ["FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)", [$bindName => $item]];
  240. }
  241. break;
  242. case 'IN':
  243. case 'IN(...)':
  244. case 'NOT IN':
  245. case 'NOT IN(...)':
  246. $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
  247. break;
  248. case 'BETWEEN':
  249. case 'NOT BETWEEN':
  250. $arr = array_slice(explode(',', $v), 0, 2);
  251. if (stripos($v, ',') === false || !array_filter($arr)) {
  252. continue 2;
  253. }
  254. //当出现一边为空时改变操作符
  255. if ($arr[0] === '') {
  256. $sym = $sym == 'BETWEEN' ? '<=' : '>';
  257. $arr = $arr[1];
  258. } elseif ($arr[1] === '') {
  259. $sym = $sym == 'BETWEEN' ? '>=' : '<';
  260. $arr = $arr[0];
  261. }
  262. $where[] = [$k, $sym, $arr];
  263. break;
  264. case 'RANGE':
  265. case 'NOT RANGE':
  266. $v = str_replace(' - ', ',', $v);
  267. $arr = array_slice(explode(',', $v), 0, 2);
  268. if (stripos($v, ',') === false || !array_filter($arr)) {
  269. continue 2;
  270. }
  271. //当出现一边为空时改变操作符
  272. if ($arr[0] === '') {
  273. $sym = $sym == 'RANGE' ? '<=' : '>';
  274. $arr = $arr[1];
  275. } elseif ($arr[1] === '') {
  276. $sym = $sym == 'RANGE' ? '>=' : '<';
  277. $arr = $arr[0];
  278. }
  279. $tableArr = explode('.', $k);
  280. if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->modelClass)) {
  281. //修复关联模型下时间无法搜索的BUG
  282. $relation = parse_name($tableArr[0], 1, false);
  283. $alias[$this->modelClass->$relation()->getTable()] = $tableArr[0];
  284. }
  285. $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
  286. break;
  287. case 'NULL':
  288. case 'IS NULL':
  289. case 'NOT NULL':
  290. case 'IS NOT NULL':
  291. $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
  292. break;
  293. default:
  294. break;
  295. }
  296. $index++;
  297. }
  298. if (!empty($this->modelClass)) {
  299. $this->modelClass->alias($alias);
  300. }
  301. $model = $this->modelClass;
  302. $where = function ($query) use ($where, $alias, $bind, &$model) {
  303. if (!empty($model)) {
  304. $model->alias($alias);
  305. //$model->bind($bind);
  306. }
  307. foreach ($where as $k => $v) {
  308. if (is_array($v)) {
  309. call_user_func_array([$query, 'where'], $v);
  310. } else {
  311. $query->where($v);
  312. }
  313. }
  314. };
  315. return [$page, $limit, $where, $sort, $order, $offset, $alias, $bind];
  316. }
  317. /**
  318. * 获取数据限制的管理员ID
  319. * 禁用数据限制时返回的是null
  320. * @return mixed
  321. */
  322. protected function getDataLimitAdminIds()
  323. {
  324. if (!$this->dataLimit) {
  325. return null;
  326. }
  327. if ($this->auth->isAdministrator()) {
  328. return null;
  329. }
  330. $adminIds = [];
  331. if (in_array($this->dataLimit, ['auth', 'personal'])) {
  332. $adminIds = $this->dataLimit == 'auth' ? $this->auth->getChildrenAdminIds(true) : [$this->auth->id];
  333. }
  334. return $adminIds;
  335. }
  336. /**
  337. *
  338. * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
  339. * 这里示例了所有的参数,所以比较复杂,实现上自己实现只需简单的几行即可
  340. *
  341. */
  342. protected function selectpage()
  343. {
  344. //设置过滤方法
  345. $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);
  346. //搜索关键词,客户端输入以空格分开,这里接收为数组
  347. $word = (array) $this->request->request("q_word/a");
  348. //当前页
  349. $page = $this->request->request("pageNumber");
  350. //分页大小
  351. $pagesize = $this->request->request("pageSize");
  352. //搜索条件
  353. $andor = $this->request->request("andOr", "and", "strtoupper");
  354. //排序方式
  355. $orderby = (array) $this->request->request("orderBy/a");
  356. //显示的字段
  357. $field = $this->request->request("showField");
  358. //主键
  359. $primarykey = $this->request->request("keyField");
  360. //主键值
  361. $primaryvalue = $this->request->request("keyValue");
  362. //搜索字段
  363. $searchfield = (array) $this->request->request("searchField/a");
  364. //自定义搜索条件
  365. $custom = (array) $this->request->request("custom/a");
  366. //是否返回树形结构
  367. $istree = $this->request->request("isTree", 0);
  368. $ishtml = $this->request->request("isHtml", 0);
  369. if ($istree) {
  370. $word = [];
  371. $pagesize = 99999;
  372. }
  373. $order = [];
  374. foreach ($orderby as $k => $v) {
  375. $order[$v[0]] = $v[1];
  376. }
  377. $field = $field ? $field : 'name';
  378. //如果有primaryvalue,说明当前是初始化传值
  379. if ($primaryvalue !== null) {
  380. //$where = [$primarykey => ['in', $primaryvalue]];
  381. $where = [$primarykey => explode(',', $primaryvalue)];
  382. $pagesize = 99999;
  383. } else {
  384. $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
  385. $logic = $andor == 'AND' ? '&' : '|';
  386. $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
  387. $searchfield = str_replace(',', $logic, $searchfield);
  388. $word = array_filter(array_unique($word));
  389. if (count($word) == 1) {
  390. $query->where($searchfield, "like", "%" . reset($word) . "%");
  391. } else {
  392. $query->where(function ($query) use ($word, $searchfield) {
  393. foreach ($word as $index => $item) {
  394. $query->whereOr(function ($query) use ($item, $searchfield) {
  395. $query->where($searchfield, "like", "%{$item}%");
  396. });
  397. }
  398. });
  399. }
  400. if ($custom && is_array($custom)) {
  401. foreach ($custom as $k => $v) {
  402. if (is_array($v) && 2 == count($v)) {
  403. $query->where($k, trim($v[0]), $v[1]);
  404. } else {
  405. $query->where($k, '=', $v);
  406. }
  407. }
  408. }
  409. };
  410. }
  411. $adminIds = $this->getDataLimitAdminIds();
  412. if (is_array($adminIds)) {
  413. $this->modelClass = $this->modelClass->where($this->dataLimitField, 'in', $adminIds);
  414. }
  415. $list = [];
  416. $total = $this->modelClass->where($where)->count();
  417. if ($total > 0) {
  418. $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);
  419. //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
  420. if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
  421. $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
  422. //修复自定义data-primary-key为字符串内容时,给排序字段添加上引号
  423. $primaryvalue = array_map(function ($value) {
  424. return '\'' . $value . '\'';
  425. }, $primaryvalue);
  426. $primaryvalue = implode(',', $primaryvalue);
  427. $this->modelClass->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
  428. } else {
  429. $this->modelClass->order($order);
  430. }
  431. $this->modelClass->removeOption('where');
  432. if (is_array($adminIds)) {
  433. $this->modelClass->where($this->dataLimitField, 'in', $adminIds);
  434. }
  435. $datalist = $this->modelClass->where($where)
  436. ->page($page, $pagesize)
  437. ->select();
  438. foreach ($datalist as $index => $item) {
  439. unset($item['password'], $item['salt']);
  440. if ($this->selectpageFields == '*') {
  441. $result = [
  442. $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
  443. $field => isset($item[$field]) ? $item[$field] : '',
  444. ];
  445. } else {
  446. $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array) $item), array_flip($fields));
  447. }
  448. $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
  449. $list[] = $result;
  450. }
  451. if ($istree && !$primaryvalue) {
  452. $tree = \util\Tree::instance();
  453. $tree->init(collection($list)->toArray(), 'pid');
  454. $list = $tree->getTreeList($tree->getTreeArray(0), $field);
  455. if (!$ishtml) {
  456. foreach ($list as &$item) {
  457. $item = str_replace('&nbsp;', ' ', $item);
  458. }
  459. unset($item);
  460. }
  461. }
  462. }
  463. //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
  464. return json(['data' => $list, 'count' => $total]);
  465. }
  466. //刷新Token
  467. protected function token()
  468. {
  469. $token = $this->request->param('__token__');
  470. //验证Token
  471. if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
  472. $this->error('令牌错误!', '', ['__token__' => $this->request->token()]);
  473. }
  474. //刷新Token
  475. $this->request->token();
  476. }
  477. }