Backend.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. /**
  10. * 后台控制器基类
  11. */
  12. class Backend extends Controller
  13. {
  14. /**
  15. * 无需登录的方法,同时也就不需要鉴权了
  16. * @var array
  17. */
  18. protected $noNeedLogin = [];
  19. /**
  20. * 无需鉴权的方法,但需要登录
  21. * @var array
  22. */
  23. protected $noNeedRight = [];
  24. /**
  25. * 布局模板
  26. * @var string
  27. */
  28. protected $layout = 'default';
  29. /**
  30. * 权限控制类
  31. * @var Auth
  32. */
  33. protected $auth = null;
  34. /**
  35. * 快速搜索时执行查找的字段
  36. */
  37. protected $searchFields = 'id';
  38. /**
  39. * 是否是关联查询
  40. */
  41. protected $relationSearch = false;
  42. /**
  43. * 是否开启Validate验证
  44. */
  45. protected $modelValidate = false;
  46. /**
  47. * 是否开启模型场景验证
  48. */
  49. protected $modelSceneValidate = false;
  50. /**
  51. * Multi方法可批量修改的字段
  52. */
  53. protected $multiFields = 'status';
  54. /**
  55. * 引入后台控制器的traits
  56. */
  57. use \app\admin\library\traits\Backend;
  58. public function _initialize()
  59. {
  60. $modulename = $this->request->module();
  61. $controllername = strtolower($this->request->controller());
  62. $actionname = strtolower($this->request->action());
  63. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  64. // 定义是否Addtabs请求
  65. !defined('IS_ADDTABS') && define('IS_ADDTABS', input("addtabs") ? TRUE : FALSE);
  66. // 定义是否Dialog请求
  67. !defined('IS_DIALOG') && define('IS_DIALOG', input("dialog") ? TRUE : FALSE);
  68. // 定义是否AJAX请求
  69. !defined('IS_AJAX') && define('IS_AJAX', $this->request->isAjax());
  70. $this->auth = Auth::instance();
  71. // 设置当前请求的URI
  72. $this->auth->setRequestUri($path);
  73. // 检测是否需要验证登录
  74. if (!$this->auth->match($this->noNeedLogin))
  75. {
  76. //检测是否登录
  77. if (!$this->auth->isLogin())
  78. {
  79. Hook::listen('admin_nologin', $this);
  80. $url = Session::get('referer');
  81. $url = $url ? $url : $this->request->url();
  82. $this->error(__('Please login first'), url('index/login', ['url' => $url]));
  83. }
  84. // 判断是否需要验证权限
  85. if (!$this->auth->match($this->noNeedRight))
  86. {
  87. // 判断控制器和方法判断是否有对应权限
  88. if (!$this->auth->check($path))
  89. {
  90. Hook::listen('admin_nopermission', $this);
  91. $this->error(__('You have no permission'), '');
  92. }
  93. }
  94. }
  95. // 非选项卡时重定向
  96. if (!$this->request->isPost() && !IS_AJAX && !IS_ADDTABS && !IS_DIALOG && input("ref") == 'addtabs')
  97. {
  98. $url = preg_replace_callback("/([\?|&]+)ref=addtabs(&?)/i", function($matches) {
  99. return $matches[2] == '&' ? $matches[1] : '';
  100. }, $this->request->url());
  101. $this->redirect('index/index', [], 302, ['referer' => $url]);
  102. exit;
  103. }
  104. // 设置面包屑导航数据
  105. $breadcrumb = $this->auth->getBreadCrumb($path);
  106. array_pop($breadcrumb);
  107. $this->view->breadcrumb = $breadcrumb;
  108. // 如果有使用模板布局
  109. if ($this->layout)
  110. {
  111. $this->view->engine->layout('layout/' . $this->layout);
  112. }
  113. // 语言检测
  114. $lang = strip_tags(Lang::detect());
  115. $site = Config::get("site");
  116. $upload = \app\common\model\Config::upload();
  117. // 上传信息配置后
  118. Hook::listen("upload_config_init", $upload);
  119. // 配置信息
  120. $config = [
  121. 'site' => array_intersect_key($site, array_flip(['name', 'cdnurl', 'version', 'timezone', 'languages'])),
  122. 'upload' => $upload,
  123. 'modulename' => $modulename,
  124. 'controllername' => $controllername,
  125. 'actionname' => $actionname,
  126. 'jsname' => 'backend/' . str_replace('.', '/', $controllername),
  127. 'moduleurl' => rtrim(url("/{$modulename}", '', false), '/'),
  128. 'language' => $lang,
  129. 'fastadmin' => Config::get('fastadmin'),
  130. 'referer' => Session::get("referer")
  131. ];
  132. // 配置信息后
  133. Hook::listen("config_init", $config);
  134. //加载当前控制器语言包
  135. $this->loadlang($controllername);
  136. //渲染站点配置
  137. $this->assign('site', $site);
  138. //渲染配置信息
  139. $this->assign('config', $config);
  140. //渲染权限对象
  141. $this->assign('auth', $this->auth);
  142. //渲染管理员对象
  143. $this->assign('admin', Session::get('admin'));
  144. }
  145. /**
  146. * 加载语言文件
  147. * @param string $name
  148. */
  149. protected function loadlang($name)
  150. {
  151. Lang::load(APP_PATH . $this->request->module() . '/lang/' . Lang::detect() . '/' . str_replace('.', '/', $name) . '.php');
  152. }
  153. /**
  154. * 渲染配置信息
  155. * @param mixed $name 键名或数组
  156. * @param mixed $value 值
  157. */
  158. protected function assignconfig($name, $value = '')
  159. {
  160. $this->view->config = array_merge($this->view->config ? $this->view->config : [], is_array($name) ? $name : [$name => $value]);
  161. }
  162. /**
  163. * 生成查询所需要的条件,排序方式
  164. * @param mixed $searchfields 查询条件
  165. * @param boolean $relationSearch 是否关联查询
  166. * @return array
  167. */
  168. protected function buildparams($searchfields = null, $relationSearch = null)
  169. {
  170. $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
  171. $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
  172. $search = $this->request->get("search", '');
  173. $filter = $this->request->get("filter", '');
  174. $op = $this->request->get("op", '', 'trim');
  175. $sort = $this->request->get("sort", "id");
  176. $order = $this->request->get("order", "DESC");
  177. $offset = $this->request->get("offset", 0);
  178. $limit = $this->request->get("limit", 0);
  179. $filter = json_decode($filter, TRUE);
  180. $op = json_decode($op, TRUE);
  181. $filter = $filter ? $filter : [];
  182. $where = [];
  183. $tableName = '';
  184. if ($relationSearch)
  185. {
  186. if (!empty($this->model))
  187. {
  188. $class = get_class($this->model);
  189. $name = basename(str_replace('\\', '/', $class));
  190. $tableName = $this->model->getQuery()->getTable($name) . ".";
  191. }
  192. if (stripos($sort, ".") === false)
  193. {
  194. $sort = $tableName . $sort;
  195. }
  196. }
  197. if ($search)
  198. {
  199. $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
  200. foreach ($searcharr as $k => &$v)
  201. {
  202. $v = $tableName . $v;
  203. }
  204. unset($v);
  205. $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
  206. }
  207. foreach ($filter as $k => $v)
  208. {
  209. $sym = isset($op[$k]) ? $op[$k] : '=';
  210. if (stripos($k, ".") === false)
  211. {
  212. $k = $tableName . $k;
  213. }
  214. $sym = isset($op[$k]) ? $op[$k] : $sym;
  215. switch ($sym)
  216. {
  217. case '=':
  218. case '!=':
  219. case 'LIKE':
  220. case 'NOT LIKE':
  221. $where[] = [$k, $sym, $v];
  222. break;
  223. case '>':
  224. case '>=':
  225. case '<':
  226. case '<=':
  227. $where[] = [$k, $sym, intval($v)];
  228. break;
  229. case 'IN(...)':
  230. case 'NOT IN(...)':
  231. $where[] = [$k, str_replace('(...)', '', $sym), explode(',', $v)];
  232. break;
  233. case 'BETWEEN':
  234. case 'NOT BETWEEN':
  235. $where[] = [$k, $sym, array_slice(explode(',', $v), 0, 2)];
  236. break;
  237. case 'LIKE %...%':
  238. $where[] = [$k, 'LIKE', "%{$v}%"];
  239. break;
  240. case 'IS NULL':
  241. case 'IS NOT NULL':
  242. $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
  243. break;
  244. default:
  245. break;
  246. }
  247. }
  248. $where = function($query) use ($where) {
  249. foreach ($where as $k => $v)
  250. {
  251. if (is_array($v))
  252. {
  253. call_user_func_array([$query, 'where'], $v);
  254. }
  255. else
  256. {
  257. $query->where($v);
  258. }
  259. }
  260. };
  261. return [$where, $sort, $order, $offset, $limit];
  262. }
  263. /**
  264. * Selectpage的实现方法
  265. *
  266. * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
  267. * 这里示例了所有的参数,所以比较复杂,实现上自己实现只需简单的几行即可
  268. *
  269. */
  270. protected function selectpage()
  271. {
  272. //设置过滤方法
  273. $this->request->filter(['strip_tags', 'htmlspecialchars']);
  274. //搜索关键词,客户端输入以空格分开,这里接收为数组
  275. $word = (array) $this->request->request("q_word/a");
  276. //当前页
  277. $page = $this->request->request("page");
  278. //分页大小
  279. $pagesize = $this->request->request("per_page");
  280. //搜索条件
  281. $andor = $this->request->request("and_or");
  282. //排序方式
  283. $orderby = (array) $this->request->request("order_by/a");
  284. //显示的字段
  285. $field = $this->request->request("field");
  286. //主键
  287. $primarykey = $this->request->request("pkey_name");
  288. //主键值
  289. $primaryvalue = $this->request->request("pkey_value");
  290. //搜索字段
  291. $searchfield = (array) $this->request->request("search_field/a");
  292. //自定义搜索条件
  293. $custom = (array) $this->request->request("custom/a");
  294. $order = [];
  295. foreach ($orderby as $k => $v)
  296. {
  297. $order[$v[0]] = $v[1];
  298. }
  299. $field = $field ? $field : 'name';
  300. //如果有primaryvalue,说明当前是初始化传值
  301. if ($primaryvalue)
  302. {
  303. $where = [$primarykey => ['in', $primaryvalue]];
  304. }
  305. else
  306. {
  307. $where = function($query) use($word, $andor, $field, $searchfield, $custom) {
  308. foreach ($word as $k => $v)
  309. {
  310. foreach ($searchfield as $m => $n)
  311. {
  312. $query->where($n, "like", "%{$v}%", $andor);
  313. }
  314. }
  315. if ($custom && is_array($custom))
  316. {
  317. foreach ($custom as $k => $v)
  318. {
  319. $query->where($k, '=', $v);
  320. }
  321. }
  322. };
  323. }
  324. $list = [];
  325. $total = $this->model->where($where)->count();
  326. if ($total > 0)
  327. {
  328. $list = $this->model->where($where)
  329. ->order($order)
  330. ->page($page, $pagesize)
  331. ->field("{$primarykey},{$field}")
  332. ->field("password,salt", true)
  333. ->select();
  334. }
  335. //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
  336. return json(['list' => $list, 'total' => $total]);
  337. }
  338. }