Userend.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. <?php
  2. namespace app\common\controller;
  3. use app\common\library\UserAuth as Auth;
  4. use fast\Tree;
  5. use think\Config;
  6. use think\Controller;
  7. use think\Hook;
  8. use think\Lang;
  9. use think\Loader;
  10. use think\Session;
  11. /**
  12. * 用户端控制器基类
  13. */
  14. class Userend extends Controller
  15. {
  16. /**
  17. * 无需登录的方法,同时也就不需要鉴权了
  18. * @var array
  19. */
  20. protected $noNeedLogin = ['login', 'register', 'third'];
  21. /**
  22. * 无需鉴权的方法,但需要登录
  23. * @var array
  24. */
  25. protected $noNeedRight = ['index', 'logout'];
  26. /**
  27. * 布局模板
  28. * @var string
  29. */
  30. protected $layout = 'default';
  31. /**
  32. * 权限Auth
  33. * @var Auth
  34. */
  35. protected $auth = null;
  36. /**
  37. * 模型对象
  38. * @var \think\Model
  39. */
  40. protected $model = null;
  41. /**
  42. * 快速搜索时执行查找的字段
  43. */
  44. protected $searchFields = 'id';
  45. /**
  46. * 是否是关联查询
  47. */
  48. protected $relationSearch = false;
  49. /**
  50. * 是否开启数据限制
  51. * 支持auth/personal
  52. * 表示按权限判断/仅限个人
  53. * 默认为禁用,若启用请务必保证表中存在user_id字段
  54. */
  55. protected $dataLimit = false;
  56. /**
  57. * 数据限制字段
  58. */
  59. protected $dataLimitField = 'user_id';
  60. /**
  61. * 数据限制开启时自动填充限制字段值
  62. */
  63. protected $dataLimitFieldAutoFill = true;
  64. /**
  65. * 是否开启Validate验证
  66. */
  67. protected $modelValidate = false;
  68. /**
  69. * 是否开启模型场景验证
  70. */
  71. protected $modelSceneValidate = false;
  72. /**
  73. * Multi方法可批量修改的字段
  74. */
  75. protected $multiFields = 'status';
  76. /**
  77. * Selectpage可显示的字段
  78. */
  79. protected $selectpageFields = '*';
  80. /**
  81. * 前台提交过来,需要排除的字段数据
  82. */
  83. protected $excludeFields = "";
  84. /**
  85. * 导入文件首行类型
  86. * 支持comment/name
  87. * 表示注释或字段名
  88. */
  89. protected $importHeadType = 'comment';
  90. protected $modulename = '';
  91. protected $controllername = '';
  92. protected $actionname = '';
  93. protected $config = [];
  94. /**
  95. * 引入会员控制器的traits
  96. */
  97. use \app\common\library\traits\Userend;
  98. public function _initialize()
  99. {
  100. parent::_initialize();
  101. //移除HTML标签
  102. $this->request->filter('trim,strip_tags,htmlspecialchars');
  103. $this->modulename = $this->request->module();
  104. $this->controllername = Loader::parseName($this->request->controller());
  105. $this->actionname = strtolower($this->request->action());
  106. $path = $this->controllername . '/' . $this->actionname;
  107. // 定义是否Addtabs请求
  108. !defined('IS_ADDTABS') && define('IS_ADDTABS', input("addtabs") ? true : false);
  109. // 定义是否Dialog请求
  110. !defined('IS_DIALOG') && define('IS_DIALOG', input("dialog") ? true : false);
  111. // 定义是否AJAX请求
  112. !defined('IS_AJAX') && define('IS_AJAX', $this->request->isAjax());
  113. $this->auth = Auth::instance();
  114. // token
  115. $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
  116. // 设置当前请求的URI
  117. $this->auth->setRequestUri($path);
  118. // 检测是否需要验证登录
  119. if (!$this->auth->match($this->noNeedLogin)) {
  120. //初始化
  121. $this->auth->init($token);
  122. //检测是否登录
  123. if (!$this->auth->isLogin()) {
  124. Hook::listen('user_nologin', $this);
  125. $url = Session::get('referer');
  126. $url = $url ? $url : $this->request->url();
  127. if ($url == '/') {
  128. $this->redirect('index/user/login', [], 302, ['referer' => $url]);
  129. exit;
  130. }
  131. $this->error(__('Please login first'), 'index/user/login');
  132. }
  133. // 判断是否需要验证权限
  134. if (!$this->auth->match($this->noNeedRight)) {
  135. // 判断控制器和方法判断是否有对应权限
  136. if (!$this->auth->check($path)) {
  137. Hook::listen('admin_nopermission', $this);
  138. $this->error(__('You have no permission'));
  139. }
  140. }
  141. } else {
  142. // 如果有传递token才验证是否登录状态
  143. if ($token) {
  144. $this->auth->init($token);
  145. }
  146. }
  147. // 非选项卡时重定向
  148. if (!$this->request->isPost() && !IS_AJAX && !IS_ADDTABS && !IS_DIALOG && input("ref") == 'addtabs') {
  149. $url = preg_replace_callback("/([\?|&]+)ref=addtabs(&?)/i", function ($matches) {
  150. return $matches[2] == '&' ? $matches[1] : '';
  151. }, $this->request->url());
  152. if (Config::get('url_domain_deploy')) {
  153. if (stripos($url, $this->request->server('SCRIPT_NAME')) === 0) {
  154. $url = substr($url, strlen($this->request->server('SCRIPT_NAME')));
  155. }
  156. $url = url($url, '', false);
  157. }
  158. $this->redirect('user/index/index', [], 302, ['referer' => $url]);
  159. exit;
  160. }
  161. // 设置面包屑导航数据
  162. $breadcrumb = $this->auth->getBreadCrumb($path);
  163. array_pop($breadcrumb);
  164. $this->assign('breadcrumb', $breadcrumb);
  165. // 如果有使用模板布局
  166. if ($this->layout) {
  167. $this->view->engine->layout('layout/' . $this->layout);
  168. }
  169. // 语言检测
  170. $lang = strip_tags($this->request->langset());
  171. $site = Config::get("site");
  172. $upload = \app\common\model\Config::upload();
  173. // 上传信息配置后
  174. Hook::listen("upload_config_init", $upload);
  175. // 配置信息
  176. $this->config = [
  177. 'site' => array_intersect_key($site, array_flip(['name', 'indexurl', 'cdnurl', 'version', 'timezone', 'languages'])),
  178. 'upload' => $upload,
  179. 'modulename' => $this->modulename,
  180. 'controllername' => $this->controllername,
  181. 'actionname' => $this->actionname,
  182. 'jsname' => 'userend/' . str_replace('.', '/', $this->controllername),
  183. 'moduleurl' => rtrim(url("/{$this->modulename}", '', false), '/'),
  184. 'language' => $lang,
  185. 'fastadmin' => Config::get('fastadmin'),
  186. 'referer' => Session::get("referer"),
  187. ];
  188. $this->config = array_merge($this->config, Config::get("view_replace_str"));
  189. Config::set('upload', array_merge(Config::get('upload'), $upload));
  190. // 配置信息后
  191. Hook::listen("config_init", $this->config);
  192. // 加载当前控制器语言包
  193. $this->loadlang($this->controllername);
  194. $this->assign('site', $site);
  195. $this->assign('config', $this->config);
  196. //渲染权限对象
  197. $this->assign('auth', $this->auth);
  198. $this->assign('user', $this->auth->getUser());
  199. }
  200. /**
  201. * 加载语言文件
  202. * @param string $name
  203. */
  204. protected function loadlang($name)
  205. {
  206. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
  207. //加载共用语言包
  208. //Lang::load(APP_PATH . 'lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
  209. }
  210. /**
  211. * 渲染配置信息
  212. * @param mixed $name 键名或数组
  213. * @param mixed $value 值
  214. */
  215. protected function assignconfig($name, $value = '')
  216. {
  217. $this->view->config = array_merge($this->view->config ? $this->view->config : [], is_array($name) ? $name : [$name => $value]);
  218. }
  219. /**
  220. * 生成查询所需要的条件,排序方式
  221. * @param mixed $searchfields 快速查询的字段
  222. * @param boolean $relationSearch 是否关联查询
  223. * @param string $aliasName 关联查询的主表别名
  224. * @return array
  225. */
  226. protected function buildparams($searchfields = null, $relationSearch = null, $aliasName = 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", 0);
  236. $limit = $this->request->get("limit", 0);
  237. $filter = (array)json_decode($filter, true);
  238. $op = (array)json_decode($op, true);
  239. $filter = $filter ? $filter : [];
  240. $where = [];
  241. $tableName = '';
  242. //如果是关联查询,则加上别名前缀(可在参数中指定主表别名)
  243. if ($relationSearch) {
  244. if (!empty($this->model)) {
  245. $name = $aliasName ? $aliasName : \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
  246. $tableName = $name . '.';
  247. }
  248. $sortArr = explode(',', $sort);
  249. foreach ($sortArr as & $item) {
  250. $item = stripos($item, ".") === false ? $tableName . trim($item) : $item;
  251. }
  252. unset($item);
  253. $sort = implode(',', $sortArr);
  254. }
  255. $userIds = $this->getDataLimitUserIds();
  256. if (is_array($userIds)) {
  257. $where[] = [$tableName . $this->dataLimitField, 'in', $userIds];
  258. }
  259. if ($search) {
  260. $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
  261. foreach ($searcharr as $k => &$v) {
  262. $v = stripos($v, ".") === false ? $tableName . $v : $v;
  263. }
  264. unset($v);
  265. $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
  266. }
  267. foreach ($filter as $k => $v) {
  268. $sym = isset($op[$k]) ? $op[$k] : '=';
  269. if (stripos($k, ".") === false) {
  270. $k = $tableName . $k;
  271. }
  272. $v = !is_array($v) ? trim($v) : $v;
  273. $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
  274. switch ($sym) {
  275. case '=':
  276. case '<>':
  277. $where[] = [$k, $sym, (string)$v];
  278. break;
  279. case 'LIKE':
  280. case 'NOT LIKE':
  281. case 'LIKE %...%':
  282. case 'NOT LIKE %...%':
  283. $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
  284. break;
  285. case '>':
  286. case '>=':
  287. case '<':
  288. case '<=':
  289. $where[] = [$k, $sym, intval($v)];
  290. break;
  291. case 'FINDIN':
  292. case 'FINDINSET':
  293. case 'FIND_IN_SET':
  294. $where[] = "FIND_IN_SET('{$v}', " . ($relationSearch ? $k : '`' . str_replace('.', '`.`', $k) . '`') . ")";
  295. break;
  296. case 'IN':
  297. case 'IN(...)':
  298. case 'NOT IN':
  299. case 'NOT IN(...)':
  300. $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
  301. break;
  302. case 'BETWEEN':
  303. case 'NOT BETWEEN':
  304. $arr = array_slice(explode(',', $v), 0, 2);
  305. if (stripos($v, ',') === false || !array_filter($arr))
  306. continue 2;
  307. //当出现一边为空时改变操作符
  308. if ($arr[0] === '') {
  309. $sym = $sym == 'BETWEEN' ? '<=' : '>';
  310. $arr = $arr[1];
  311. } else if ($arr[1] === '') {
  312. $sym = $sym == 'BETWEEN' ? '>=' : '<';
  313. $arr = $arr[0];
  314. }
  315. $where[] = [$k, $sym, $arr];
  316. break;
  317. case 'RANGE':
  318. case 'NOT RANGE':
  319. $v = str_replace(' - ', ',', $v);
  320. $arr = array_slice(explode(',', $v), 0, 2);
  321. if (stripos($v, ',') === false || !array_filter($arr))
  322. continue 2;
  323. //当出现一边为空时改变操作符
  324. if ($arr[0] === '') {
  325. $sym = $sym == 'RANGE' ? '<=' : '>';
  326. $arr = $arr[1];
  327. } else if ($arr[1] === '') {
  328. $sym = $sym == 'RANGE' ? '>=' : '<';
  329. $arr = $arr[0];
  330. }
  331. $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
  332. break;
  333. case 'LIKE':
  334. case 'LIKE %...%':
  335. $where[] = [$k, 'LIKE', "%{$v}%"];
  336. break;
  337. case 'NULL':
  338. case 'IS NULL':
  339. case 'NOT NULL':
  340. case 'IS NOT NULL':
  341. $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
  342. break;
  343. default:
  344. break;
  345. }
  346. }
  347. $where = function ($query) use ($where) {
  348. foreach ($where as $k => $v) {
  349. if (is_array($v)) {
  350. call_user_func_array([$query, 'where'], $v);
  351. } else {
  352. $query->where($v);
  353. }
  354. }
  355. };
  356. return [$where, $sort, $order, $offset, $limit];
  357. }
  358. /**
  359. * 获取数据限制的会员ID
  360. * 禁用数据限制时返回的是null
  361. * @return mixed
  362. */
  363. protected function getDataLimitUserIds()
  364. {
  365. if (!$this->dataLimit) {
  366. return null;
  367. }
  368. $userIds = [];
  369. if (in_array($this->dataLimit, ['auth', 'personal'])) {
  370. //$userIds = $this->dataLimit == 'auth' ? $this->auth->getChildrenUserIds(true) : [$this->auth->id];
  371. $userIds = [$this->auth->id];
  372. }
  373. return $userIds;
  374. }
  375. /**
  376. * Selectpage的实现方法
  377. *
  378. * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
  379. * 这里示例了所有的参数,所以比较复杂,实现上自己实现只需简单的几行即可
  380. *
  381. */
  382. protected function selectpage()
  383. {
  384. //设置过滤方法
  385. $this->request->filter(['strip_tags', 'htmlspecialchars']);
  386. //搜索关键词,客户端输入以空格分开,这里接收为数组
  387. $word = (array)$this->request->request("q_word/a");
  388. //当前页
  389. $page = $this->request->request("pageNumber");
  390. //分页大小
  391. $pagesize = $this->request->request("pageSize");
  392. //搜索条件
  393. $andor = $this->request->request("andOr", "and", "strtoupper");
  394. //排序方式
  395. $orderby = (array)$this->request->request("orderBy/a");
  396. //显示的字段
  397. $field = $this->request->request("showField");
  398. //主键
  399. $primarykey = $this->request->request("keyField");
  400. //主键值
  401. $primaryvalue = $this->request->request("keyValue");
  402. //搜索字段
  403. $searchfield = (array)$this->request->request("searchField/a");
  404. //自定义搜索条件
  405. $custom = (array)$this->request->request("custom/a");
  406. //是否返回树形结构
  407. $istree = $this->request->request("isTree", 0);
  408. $ishtml = $this->request->request("isHtml", 0);
  409. if ($istree) {
  410. $word = [];
  411. $pagesize = 99999;
  412. }
  413. $order = [];
  414. foreach ($orderby as $k => $v) {
  415. $order[$v[0]] = $v[1];
  416. }
  417. $field = $field ? $field : 'name';
  418. //如果有primaryvalue,说明当前是初始化传值
  419. if ($primaryvalue !== null) {
  420. $where = [$primarykey => ['in', $primaryvalue]];
  421. } else {
  422. $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
  423. $logic = $andor == 'AND' ? '&' : '|';
  424. $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
  425. foreach ($word as $k => $v) {
  426. $query->where(str_replace(',', $logic, $searchfield), "like", "%{$v}%");
  427. }
  428. if ($custom && is_array($custom)) {
  429. foreach ($custom as $k => $v) {
  430. if (is_array($v) && 2 == count($v)) {
  431. $query->where($k, trim($v[0]), $v[1]);
  432. } else {
  433. $query->where($k, '=', $v);
  434. }
  435. }
  436. }
  437. };
  438. }
  439. $userIds = $this->getDataLimitUserIds();
  440. if (is_array($userIds)) {
  441. $this->model->where($this->dataLimitField, 'in', $userIds);
  442. }
  443. $list = [];
  444. $total = $this->model->where($where)->count();
  445. if ($total > 0) {
  446. if (is_array($userIds)) {
  447. $this->model->where($this->dataLimitField, 'in', $userIds);
  448. }
  449. $datalist = $this->model->where($where)
  450. ->order($order)
  451. ->page($page, $pagesize)
  452. ->field($this->selectpageFields)
  453. ->select();
  454. foreach ($datalist as $index => $item) {
  455. unset($item['password'], $item['salt']);
  456. $list[] = [
  457. $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
  458. $field => isset($item[$field]) ? $item[$field] : '',
  459. 'pid' => isset($item['pid']) ? $item['pid'] : 0
  460. ];
  461. }
  462. if ($istree) {
  463. $tree = Tree::instance();
  464. $tree->init(collection($list)->toArray(), 'pid');
  465. $list = $tree->getTreeList($tree->getTreeArray(0), $field);
  466. if (!$ishtml) {
  467. foreach ($list as &$item) {
  468. $item = str_replace('&nbsp;', ' ', $item);
  469. }
  470. unset($item);
  471. }
  472. }
  473. }
  474. //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
  475. return json(['list' => $list, 'total' => $total]);
  476. }
  477. }