Backend.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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 = 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('admin', Session::get('admin'));
  142. }
  143. /**
  144. * 加载语言文件
  145. * @param string $name
  146. */
  147. protected function loadlang($name)
  148. {
  149. Lang::load(APP_PATH . $this->request->module() . '/lang/' . Lang::detect() . '/' . str_replace('.', '/', $name) . '.php');
  150. }
  151. /**
  152. * 渲染配置信息
  153. * @param mixed $name 键名或数组
  154. * @param mixed $value 值
  155. */
  156. protected function assignconfig($name, $value = '')
  157. {
  158. $this->view->config = array_merge($this->view->config ? $this->view->config : [], is_array($name) ? $name : [$name => $value]);
  159. }
  160. /**
  161. * 生成查询所需要的条件,排序方式
  162. * @param mixed $searchfields 查询条件
  163. * @param boolean $relationSearch 是否关联查询
  164. * @return array
  165. */
  166. protected function buildparams($searchfields = null, $relationSearch = null)
  167. {
  168. $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
  169. $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
  170. $search = $this->request->get("search", '');
  171. $filter = $this->request->get("filter", '');
  172. $op = $this->request->get("op", '');
  173. $sort = $this->request->get("sort", "id");
  174. $order = $this->request->get("order", "DESC");
  175. $offset = $this->request->get("offset", 0);
  176. $limit = $this->request->get("limit", 0);
  177. $filter = json_decode($filter, TRUE);
  178. $op = json_decode($op, TRUE);
  179. $filter = $filter ? $filter : [];
  180. $where = [];
  181. $tableName = '';
  182. if ($relationSearch)
  183. {
  184. if (!empty($this->model))
  185. {
  186. $class = get_class($this->model);
  187. $name = basename(str_replace('\\', '/', $class));
  188. $tableName = $this->model->getQuery()->getTable($name) . ".";
  189. }
  190. if (stripos($sort, ".") === false)
  191. {
  192. $sort = $tableName . $sort;
  193. }
  194. }
  195. if ($search)
  196. {
  197. $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
  198. foreach ($searcharr as $k => &$v)
  199. {
  200. $v = $tableName . $v;
  201. }
  202. unset($v);
  203. $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
  204. }
  205. foreach ($filter as $k => $v)
  206. {
  207. $sym = isset($op[$k]) ? $op[$k] : '=';
  208. if (stripos($k, ".") === false)
  209. {
  210. $k = $tableName . $k;
  211. }
  212. $sym = isset($op[$k]) ? $op[$k] : $sym;
  213. switch ($sym)
  214. {
  215. case '=':
  216. case '!=':
  217. case 'LIKE':
  218. case 'NOT LIKE':
  219. $where[] = [$k, $sym, $v];
  220. break;
  221. case '>':
  222. case '>=':
  223. case '<':
  224. case '<=':
  225. $where[] = [$k, $sym, intval($v)];
  226. break;
  227. case 'IN(...)':
  228. case 'NOT IN(...)':
  229. $where[] = [$k, str_replace('(...)', '', $sym), explode(',', $v)];
  230. break;
  231. case 'BETWEEN':
  232. case 'NOT BETWEEN':
  233. $where[] = [$k, $sym, array_slice(explode(',', $v), 0, 2)];
  234. break;
  235. case 'LIKE %...%':
  236. $where[] = [$k, 'LIKE', "%{$v}%"];
  237. break;
  238. case 'IS NULL':
  239. case 'IS NOT NULL':
  240. $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
  241. break;
  242. default:
  243. break;
  244. }
  245. }
  246. $where = function($query) use ($where) {
  247. foreach ($where as $k => $v)
  248. {
  249. if (is_array($v))
  250. {
  251. call_user_func_array([$query, 'where'], $v);
  252. }
  253. else
  254. {
  255. $query->where($v);
  256. }
  257. }
  258. };
  259. return [$where, $sort, $order, $offset, $limit];
  260. }
  261. /**
  262. * Selectpage的实现方法
  263. *
  264. * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
  265. * 这里示例了所有的参数,所以比较复杂,实现上自己实现只需简单的几行即可
  266. *
  267. */
  268. protected function selectpage()
  269. {
  270. //设置过滤方法
  271. $this->request->filter(['strip_tags', 'htmlspecialchars']);
  272. //搜索关键词,客户端输入以空格分开,这里接收为数组
  273. $word = (array) $this->request->request("q_word/a");
  274. //当前页
  275. $page = $this->request->request("page");
  276. //分页大小
  277. $pagesize = $this->request->request("per_page");
  278. //搜索条件
  279. $andor = $this->request->request("and_or");
  280. //排序方式
  281. $orderby = (array) $this->request->request("order_by/a");
  282. //显示的字段
  283. $field = $this->request->request("field");
  284. //主键
  285. $primarykey = $this->request->request("pkey_name");
  286. //主键值
  287. $primaryvalue = $this->request->request("pkey_value");
  288. //搜索字段
  289. $searchfield = (array) $this->request->request("search_field/a");
  290. //自定义搜索条件
  291. $custom = (array) $this->request->request("custom/a");
  292. $order = [];
  293. foreach ($orderby as $k => $v)
  294. {
  295. $order[$v[0]] = $v[1];
  296. }
  297. $field = $field ? $field : 'name';
  298. //如果有primaryvalue,说明当前是初始化传值
  299. if ($primaryvalue)
  300. {
  301. $where = [$primarykey => ['in', $primaryvalue]];
  302. }
  303. else
  304. {
  305. $where = function($query) use($word, $andor, $field, $searchfield, $custom) {
  306. foreach ($word as $k => $v)
  307. {
  308. foreach ($searchfield as $m => $n)
  309. {
  310. $query->where($n, "like", "%{$v}%", $andor);
  311. }
  312. }
  313. if ($custom && is_array($custom))
  314. {
  315. foreach ($custom as $k => $v)
  316. {
  317. $query->where($k, '=', $v);
  318. }
  319. }
  320. };
  321. }
  322. $list = [];
  323. $total = $this->model->where($where)->count();
  324. if ($total > 0)
  325. {
  326. $list = $this->model->where($where)
  327. ->order($order)
  328. ->page($page, $pagesize)
  329. ->field("{$primarykey},{$field}")
  330. ->field("password,salt", true)
  331. ->select();
  332. }
  333. //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
  334. return json(['list' => $list, 'total' => $total]);
  335. }
  336. }