Backend.php 12 KB

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