UserAuth.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. <?php
  2. namespace app\common\library;
  3. use app\common\model\User;
  4. use app\common\model\UserRule;
  5. use fast\Random;
  6. use fast\Tree;
  7. use think\Config;
  8. use think\Db;
  9. use think\Hook;
  10. use think\Request;
  11. use think\Session;
  12. use think\Validate;
  13. class UserAuth
  14. {
  15. protected static $instance = null;
  16. protected $_error = '';
  17. protected $_logined = false;
  18. protected $_user = null;
  19. protected $_token = '';
  20. //Token默认有效时长
  21. protected $keeptime = 2592000;
  22. protected $requestUri = '';
  23. protected $rules = [];
  24. //默认配置
  25. protected $config = [];
  26. protected $options = [];
  27. protected $allowFields = ['nickname', 'mobile', 'avatar', 'score', 'bio'];
  28. //权限菜单
  29. protected $menus = [];
  30. //面包屑导航
  31. protected $breadcrumb = [];
  32. public function __construct($options = [])
  33. {
  34. if ($config = Config::get('user')) {
  35. $this->options = array_merge($this->config, $config);
  36. }
  37. $this->options = array_merge($this->config, $options);
  38. }
  39. /**
  40. *
  41. * @param array $options 参数
  42. * @return Auth
  43. */
  44. public static function instance($options = [])
  45. {
  46. if (is_null(self::$instance)) {
  47. self::$instance = new static($options);
  48. }
  49. return self::$instance;
  50. }
  51. /**
  52. * 获取User模型
  53. * @return User
  54. */
  55. public function getUser()
  56. {
  57. return $this->_user;
  58. }
  59. /**
  60. * 兼容调用user模型的属性
  61. *
  62. * @param string $name
  63. * @return mixed
  64. */
  65. public function __get($name)
  66. {
  67. return $this->_user ? $this->_user->$name : null;
  68. }
  69. /**
  70. * 根据Token初始化
  71. *
  72. * @param string $token Token
  73. * @return boolean
  74. */
  75. public function init($token)
  76. {
  77. if ($this->_logined) {
  78. return true;
  79. }
  80. if ($this->_error)
  81. return false;
  82. $data = Token::get($token);
  83. if (!$data) {
  84. return false;
  85. }
  86. $user_id = intval($data['user_id']);
  87. if ($user_id > 0) {
  88. $user = User::get($user_id);
  89. if (!$user) {
  90. $this->setError('Account not exist');
  91. return false;
  92. }
  93. if ($user['status'] != 'normal') {
  94. $this->setError('Account is locked');
  95. return false;
  96. }
  97. $this->_user = $user;
  98. $this->_logined = true;
  99. $this->_token = $token;
  100. //初始化成功的事件
  101. Hook::listen("user_init_successed", $this->_user);
  102. return true;
  103. } else {
  104. $this->setError('You are not logged in');
  105. return false;
  106. }
  107. }
  108. /**
  109. * 注册用户
  110. *
  111. * @param string $username 用户名
  112. * @param string $password 密码
  113. * @param string $email 邮箱
  114. * @param string $mobile 手机号
  115. * @param array $extend 扩展参数
  116. * @return boolean
  117. */
  118. public function register($username, $password, $email = '', $mobile = '', $extend = [])
  119. {
  120. // 检测用户名或邮箱、手机号是否存在
  121. if (User::getByUsername($username)) {
  122. $this->setError('Username already exist');
  123. return false;
  124. }
  125. if ($email && User::getByEmail($email)) {
  126. $this->setError('Email already exist');
  127. return false;
  128. }
  129. if ($mobile && User::getByMobile($mobile)) {
  130. $this->setError('Mobile already exist');
  131. return false;
  132. }
  133. $ip = request()->ip();
  134. $time = time();
  135. $data = [
  136. 'username' => $username,
  137. 'password' => $password,
  138. 'email' => $email,
  139. 'mobile' => $mobile,
  140. 'level' => 1,
  141. 'score' => 0,
  142. 'avatar' => '',
  143. ];
  144. $params = array_merge($data, [
  145. 'nickname' => $username,
  146. 'salt' => Random::alnum(),
  147. 'jointime' => $time,
  148. 'joinip' => $ip,
  149. 'logintime' => $time,
  150. 'loginip' => $ip,
  151. 'prevtime' => $time,
  152. 'status' => 'normal'
  153. ]);
  154. $params['password'] = $this->getEncryptPassword($password, $params['salt']);
  155. $params = array_merge($params, $extend);
  156. ////////////////同步到Ucenter////////////////
  157. if (defined('UC_STATUS') && UC_STATUS) {
  158. $uc = new \addons\ucenter\library\client\Client();
  159. $user_id = $uc->uc_user_register($username, $password, $email);
  160. // 如果小于0则说明发生错误
  161. if ($user_id <= 0) {
  162. $this->setError($user_id > -4 ? 'Username is incorrect' : 'Email is incorrect');
  163. return false;
  164. } else {
  165. $params['id'] = $user_id;
  166. }
  167. }
  168. //账号注册时需要开启事务,避免出现垃圾数据
  169. Db::startTrans();
  170. try {
  171. $user = User::create($params, true);
  172. $this->_user = User::get($user->id);
  173. //设置Token
  174. $this->_token = Random::uuid();
  175. Token::set($this->_token, $user->id, $this->keeptime);
  176. //注册成功的事件
  177. Hook::listen("user_register_successed", $this->_user, $data);
  178. Db::commit();
  179. } catch (Exception $e) {
  180. $this->setError($e->getMessage());
  181. Db::rollback();
  182. return false;
  183. }
  184. return true;
  185. }
  186. /**
  187. * 获取密码加密后的字符串
  188. * @param string $password 密码
  189. * @param string $salt 密码盐
  190. * @return string
  191. */
  192. public function getEncryptPassword($password, $salt = '')
  193. {
  194. return md5(md5($password) . $salt);
  195. }
  196. /**
  197. * 用户登录
  198. *
  199. * @param string $account 账号,用户名、邮箱、手机号
  200. * @param string $password 密码
  201. * @return boolean
  202. */
  203. public function login($account, $password)
  204. {
  205. $field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username');
  206. $user = User::get([$field => $account]);
  207. if (!$user) {
  208. $this->setError('Account is incorrect');
  209. return false;
  210. }
  211. if ($user->status != 'normal') {
  212. $this->setError('Account is locked');
  213. return false;
  214. }
  215. if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
  216. $this->setError('Password is incorrect');
  217. return false;
  218. }
  219. //直接登录会员
  220. $this->direct($user->id);
  221. return true;
  222. }
  223. /**
  224. * 直接登录账号
  225. * @param int $user_id
  226. * @return boolean
  227. */
  228. public function direct($user_id)
  229. {
  230. $user = User::get($user_id);
  231. if ($user) {
  232. ////////////////同步到Ucenter////////////////
  233. if (defined('UC_STATUS') && UC_STATUS) {
  234. $uc = new \addons\ucenter\library\client\Client();
  235. $re = $uc->uc_user_login($this->user->id, $this->user->password . '#split#' . $this->user->salt, 3);
  236. // 如果小于0则说明发生错误
  237. if ($re <= 0) {
  238. $this->setError('Username or password is incorrect');
  239. return false;
  240. }
  241. }
  242. Db::startTrans();
  243. try {
  244. $ip = request()->ip();
  245. $time = time();
  246. //判断连续登录和最大连续登录
  247. if ($user->logintime < \fast\Date::unixtime('day')) {
  248. $user->successions = $user->logintime < \fast\Date::unixtime('day', -1) ? 1 : $user->successions + 1;
  249. $user->maxsuccessions = max($user->successions, $user->maxsuccessions);
  250. }
  251. $user->prevtime = $user->logintime;
  252. //记录本次登录的IP和时间
  253. $user->loginip = $ip;
  254. $user->logintime = $time;
  255. $user->save();
  256. //查询用户信息之后, 查询用户的积分等级
  257. $levelId = $user['level'];
  258. $levelName = Db::name("user_level")->where("level_id", $levelId)->column("level_name");
  259. $user['level_name'] = $levelName;
  260. $this->_user = $user;
  261. $this->_token = Random::uuid();
  262. Token::set($this->_token, $user->id, $this->keeptime);
  263. $this->_logined = true;
  264. //登录成功的事件
  265. Hook::listen("user_login_successed", $this->_user);
  266. Db::commit();
  267. } catch (Exception $e) {
  268. Db::rollback();
  269. $this->setError($e->getMessage());
  270. return false;
  271. }
  272. return true;
  273. } else {
  274. return false;
  275. }
  276. }
  277. /**
  278. * 注销
  279. *
  280. * @return boolean
  281. */
  282. public function logout()
  283. {
  284. if (!$this->_logined) {
  285. $this->setError('You are not logged in');
  286. return false;
  287. }
  288. //设置登录标识
  289. $this->_logined = false;
  290. //删除Token
  291. Token::delete($this->_token);
  292. //注销成功的事件
  293. Hook::listen("user_logout_successed", $this->_user);
  294. return true;
  295. }
  296. /**
  297. * 修改密码
  298. * @param string $newpassword 新密码
  299. * @param string $oldpassword 旧密码
  300. * @param bool $ignoreoldpassword 忽略旧密码
  301. * @return boolean
  302. */
  303. public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false)
  304. {
  305. if (!$this->_logined) {
  306. $this->setError('You are not logged in');
  307. return false;
  308. }
  309. //判断旧密码是否正确
  310. if ($this->_user->password == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword) {
  311. Db::startTrans();
  312. try {
  313. $salt = Random::alnum();
  314. $newpassword = $this->getEncryptPassword($newpassword, $salt);
  315. $this->_user->save(['password' => $newpassword, 'salt' => $salt]);
  316. Token::delete($this->_token);
  317. //修改密码成功的事件
  318. Hook::listen("user_changepwd_successed", $this->_user);
  319. Db::commit();
  320. } catch (Exception $e) {
  321. Db::rollback();
  322. $this->setError($e->getMessage());
  323. return false;
  324. }
  325. return true;
  326. } else {
  327. $this->setError('Password is incorrect');
  328. return false;
  329. }
  330. }
  331. /**
  332. * 检测是否是否有对应权限
  333. * @param string $path 控制器/方法
  334. * @param string $module 模块 默认为当前模块
  335. * @return boolean
  336. */
  337. public function check($path = null, $module = null)
  338. {
  339. if (!$this->_logined) return false;
  340. $ruleList = $this->getRuleList();
  341. $rules = [];
  342. foreach ($ruleList as $k => $v) {
  343. $rules[] = $v['name'];
  344. }
  345. $url = ($module ? $module : request()->module()) . '/' . (is_null($path) ? $this->getRequestUri() : $path);
  346. $url = is_null($path) ? $this->getRequestUri() : $path;
  347. $url = strtolower(str_replace('.', '/', $url));
  348. return in_array($url, $rules) ? true : false;
  349. }
  350. /**
  351. * 获取会员组别规则列表
  352. * @return array
  353. */
  354. public function getRuleList()
  355. {
  356. if ($this->rules) return $this->rules;
  357. if (!$this->_user) return [];
  358. $group = $this->_user->group;
  359. if (!$group) return [];
  360. $rules = explode(',', $group->rules);
  361. $this->rules = UserRule::where('status', 'normal')->where('id', 'in', $rules)->field('id,pid,name,title,ismenu')->select();
  362. return $this->rules;
  363. }
  364. /**
  365. * 获取当前请求的URI
  366. * @return string
  367. */
  368. public function getRequestUri()
  369. {
  370. return $this->requestUri;
  371. }
  372. /**
  373. * 设置当前请求的URI
  374. * @param string $uri
  375. */
  376. public function setRequestUri($uri)
  377. {
  378. $this->requestUri = $uri;
  379. }
  380. /**
  381. * 判断是否登录
  382. * @return boolean
  383. */
  384. public function isLogin()
  385. {
  386. if ($this->_logined) {
  387. return true;
  388. }
  389. return false;
  390. }
  391. /**
  392. * 获取当前Token
  393. * @return string
  394. */
  395. public function getToken()
  396. {
  397. return $this->_token;
  398. }
  399. /**
  400. * 获取会员基本信息
  401. */
  402. public function getUserinfo()
  403. {
  404. $data = $this->_user->toArray();
  405. $allowFields = $this->getAllowFields();
  406. $userinfo = array_intersect_key($data, array_flip($allowFields));
  407. $userinfo = array_merge($userinfo, Token::get($this->_token));
  408. return $userinfo;
  409. }
  410. /**
  411. * 获取允许输出的字段
  412. * @return array
  413. */
  414. public function getAllowFields()
  415. {
  416. return $this->allowFields;
  417. }
  418. /**
  419. * 重新设置允许输出的字段
  420. * @param array $fields
  421. */
  422. public function setAllowFields($fields)
  423. {
  424. $this->allowFields = $fields;
  425. }
  426. /**
  427. * 删除一个指定会员
  428. * @param int $user_id 会员ID
  429. * @return boolean
  430. */
  431. public function delete($user_id)
  432. {
  433. $user = User::get($user_id);
  434. if (!$user) {
  435. return false;
  436. }
  437. ////////////////同步到Ucenter////////////////
  438. if (defined('UC_STATUS') && UC_STATUS) {
  439. $uc = new \addons\ucenter\library\client\Client();
  440. $re = $uc->uc_user_delete($user['id']);
  441. // 如果小于0则说明发生错误
  442. if ($re <= 0) {
  443. $this->setError('Account is locked');
  444. return false;
  445. }
  446. }
  447. Db::startTrans();
  448. try {
  449. // 删除会员
  450. User::destroy($user_id);
  451. // 删除会员指定的所有Token
  452. Token::clear($user_id);
  453. Hook::listen("user_delete_successed", $user);
  454. Db::commit();
  455. } catch (Exception $e) {
  456. Db::rollback();
  457. $this->setError($e->getMessage());
  458. return false;
  459. }
  460. return true;
  461. }
  462. /**
  463. * 检测当前控制器和方法是否匹配传递的数组
  464. *
  465. * @param array $arr 需要验证权限的数组
  466. * @return boolean
  467. */
  468. public function match($arr = [])
  469. {
  470. $request = Request::instance();
  471. $arr = is_array($arr) ? $arr : explode(',', $arr);
  472. if (!$arr) {
  473. return false;
  474. }
  475. $arr = array_map('strtolower', $arr);
  476. // 是否存在
  477. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  478. return true;
  479. }
  480. // 没找到匹配
  481. return false;
  482. }
  483. /**
  484. * 设置会话有效时间
  485. * @param int $keeptime 默认为永久
  486. */
  487. public function keeptime($keeptime = 0)
  488. {
  489. $this->keeptime = $keeptime;
  490. }
  491. /**
  492. * 渲染用户数据
  493. * @param array $datalist 二维数组
  494. * @param mixed $fields 加载的字段列表
  495. * @param string $fieldkey 渲染的字段
  496. * @param string $renderkey 结果字段
  497. * @return array
  498. */
  499. public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
  500. {
  501. $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
  502. $ids = [];
  503. foreach ($datalist as $k => $v) {
  504. if (!isset($v[$fieldkey]))
  505. continue;
  506. $ids[] = $v[$fieldkey];
  507. }
  508. $list = [];
  509. if ($ids) {
  510. if (!in_array('id', $fields)) {
  511. $fields[] = 'id';
  512. }
  513. $ids = array_unique($ids);
  514. $selectlist = User::where('id', 'in', $ids)->column($fields);
  515. foreach ($selectlist as $k => $v) {
  516. $list[$v['id']] = $v;
  517. }
  518. }
  519. foreach ($datalist as $k => &$v) {
  520. $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null;
  521. }
  522. unset($v);
  523. return $datalist;
  524. }
  525. /**
  526. * 获取错误信息
  527. * @return string
  528. */
  529. public function getError()
  530. {
  531. return $this->_error ? __($this->_error) : '';
  532. }
  533. /**
  534. * 设置错误信息
  535. *
  536. * @param $error 错误信息
  537. * @return Auth
  538. */
  539. public function setError($error)
  540. {
  541. $this->_error = $error;
  542. return $this;
  543. }
  544. /**
  545. * 获得面包屑导航
  546. * @param string $path
  547. * @return array
  548. */
  549. public function getBreadCrumb($path = '')
  550. {
  551. if ($this->breadcrumb || !$path) return $this->breadcrumb;
  552. $path_rule_id = 0;
  553. if (empty($this->rules)) {
  554. $this->rules = $this->getRuleList();
  555. }
  556. $path = str_replace(".", "/", $path);
  557. foreach ($this->rules as $rule) {
  558. $path_rule_id = $rule['name'] == $path ? $rule['id'] : $path_rule_id;
  559. }
  560. if ($path_rule_id) {
  561. $this->breadcrumb = Tree::instance()->init($this->rules)->getParents($path_rule_id, true);
  562. foreach ($this->breadcrumb as $k => &$v) {
  563. $v['url'] = url($v['name']);
  564. $v['title'] = __($v['title']);
  565. }
  566. }
  567. return $this->breadcrumb;
  568. }
  569. /**
  570. * 获取左侧菜单栏
  571. *
  572. * @param array $params URL对应的badge数据
  573. * @return string
  574. */
  575. public function getSidebar($params = [], $fixedPage = 'dashboard')
  576. {
  577. $colorArr = ['red', 'green', 'yellow', 'blue', 'teal', 'orange', 'purple'];
  578. $colorNums = count($colorArr);
  579. $badgeList = [];
  580. $module = request()->module();
  581. // 生成菜单的badge
  582. foreach ($params as $k => $v) {
  583. $url = $k;
  584. if (is_array($v)) {
  585. $nums = isset($v[0]) ? $v[0] : 0;
  586. $color = isset($v[1]) ? $v[1] : $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
  587. $class = isset($v[2]) ? $v[2] : 'label';
  588. } else {
  589. $nums = $v;
  590. $color = $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
  591. $class = 'label';
  592. }
  593. //必须nums大于0才显示
  594. if ($nums) {
  595. $badgeList[$url] = '<small class="' . $class . ' pull-right bg-' . $color . '">' . $nums . '</small>';
  596. }
  597. }
  598. // 读取用户当前拥有的权限节点
  599. $userRule = $this->getRuleList();
  600. $selected = $referer = [];
  601. $refererUrl = Session::get('referer');
  602. $pinyin = new \Overtrue\Pinyin\Pinyin('Overtrue\Pinyin\MemoryFileDictLoader');
  603. // 必须将结果集转换为数组
  604. //$ruleList = collection(UserRule::where('status', 'normal')->where('ismenu', 1)->order('weigh', 'desc')->select())->toArray();//->cache("__usermenu__")
  605. $ruleList = $this->getMenuList();
  606. foreach ($ruleList as $k => &$v) {
  607. /*if (!in_array($v['name'], $userRule)) {
  608. unset($ruleList[$k]);
  609. continue;
  610. }*/
  611. $v['icon'] = $v['icon'] . ' fa-fw';
  612. $v['url'] = '/' . $module . '/' . $v['name'];
  613. $v['badge'] = isset($badgeList[$v['name']]) ? $badgeList[$v['name']] : '';
  614. $v['py'] = $pinyin->abbr($v['title'], '');
  615. $v['pinyin'] = $pinyin->permalink($v['title'], '');
  616. $v['title'] = __($v['title']);
  617. //$select_id = $v['name'] == $fixedPage ? $v['id'] : $select_id;
  618. $selected = $v['name'] == $fixedPage ? $v : $selected;
  619. $referer = url($v['url']) == $refererUrl ? $v : $referer;
  620. }
  621. if ($selected == $referer) {
  622. $referer = [];
  623. }
  624. $selected && $selected['url'] = url($selected['url']);
  625. $referer && $referer['url'] = url($referer['url']);
  626. $select_id = $selected ? $selected['id'] : 0;
  627. $menu = $nav = '';
  628. //是否启用多级菜单导航
  629. if (Config::get('fastadmin.multiplenav')) {
  630. $topList = [];
  631. foreach ($ruleList as $index => $item) {
  632. if (!$item['pid']) {
  633. $topList[] = $item;
  634. }
  635. }
  636. $selectParentIds = [];
  637. $tree = Tree::instance();
  638. $tree->init($ruleList);
  639. if ($select_id) {
  640. $selectParentIds = $tree->getParentsIds($select_id, true);
  641. }
  642. foreach ($topList as $index => $item) {
  643. $childList = Tree::instance()->getTreeMenu($item['id'], '<li class="@class" pid="@pid"><a href="@url@addtabs" addtabs="@id" url="@url" py="@py" pinyin="@pinyin"><i class="@icon"></i> <span>@title</span> <span class="pull-right-container">@caret @badge</span></a> @childlist</li>', $select_id, '', 'ul', 'class="treeview-menu"');
  644. $current = in_array($item['id'], $selectParentIds);
  645. $url = $childList ? 'javascript:;' : url($item['url']);
  646. $addtabs = $childList || !$url ? "" : (stripos($url, "?") !== false ? "&" : "?") . "ref=addtabs";
  647. $childList = str_replace('" pid="' . $item['id'] . '"', ' treeview ' . ($current ? '' : 'hidden') . '" pid="' . $item['id'] . '"', $childList);
  648. $nav .= '<li class="' . ($current ? 'active' : '') . '"><a href="' . $url . $addtabs . '" addtabs="' . $item['id'] . '" url="' . $url . '"><i class="' . $item['icon'] . '"></i> <span>' . $item['title'] . '</span> <span class="pull-right-container"> </span></a> </li>';
  649. $menu .= $childList;
  650. }
  651. } else {
  652. // 构造菜单数据
  653. Tree::instance()->init($ruleList);
  654. $menu = Tree::instance()->getTreeMenu(0, '<li class="@class"><a href="@url@addtabs" addtabs="@id" url="@url" py="@py" pinyin="@pinyin"><i class="@icon"></i> <span>@title</span> <span class="pull-right-container">@caret @badge</span></a> @childlist</li>', $select_id, '', 'ul', 'class="treeview-menu"');
  655. if ($selected) {
  656. $nav .= '<li role="presentation" id="tab_' . $selected['id'] . '" class="' . ($referer ? '' : 'active') . '"><a href="#con_' . $selected['id'] . '" node-id="' . $selected['id'] . '" aria-controls="' . $selected['id'] . '" role="tab" data-toggle="tab"><i class="' . $selected['icon'] . ' fa-fw"></i> <span>' . $selected['title'] . '</span> </a></li>';
  657. }
  658. if ($referer) {
  659. $nav .= '<li role="presentation" id="tab_' . $referer['id'] . '" class="active"><a href="#con_' . $referer['id'] . '" node-id="' . $referer['id'] . '" aria-controls="' . $referer['id'] . '" role="tab" data-toggle="tab"><i class="' . $referer['icon'] . ' fa-fw"></i> <span>' . $referer['title'] . '</span> </a> <i class="close-tab fa fa-remove"></i></li>';
  660. }
  661. }
  662. return [$menu, $nav, $selected, $referer];
  663. // 构造菜单数据
  664. //$usertree = new Tree();
  665. //$usertree->init($ruleList);
  666. //$usermenu = $usertree->getTreeMenu(0, '<li class="@class"><a href="@url@addtabs" addtabs="@id" url="@url" py="@py" pinyin="@pinyin"><i class="@icon"></i> <span>@title</span> <span class="pull-right-container">@caret @badge</span></a> @childlist</li>'."\n", $select_id, '', 'ul', 'class="treeview-menu"');
  667. //return $usermenu;
  668. }
  669. /**
  670. * 获取会员组别规则菜单
  671. * @return array
  672. */
  673. public function getMenuList()
  674. {
  675. if ($this->menus) return $this->menus;
  676. $group = $this->_user->group;
  677. if (!$group) return [];
  678. $rules = explode(',', $group->rules);
  679. $this->menus = collection(UserRule::where('status', 'normal')->where('id', 'in', $rules)->where('ismenu', 1)
  680. ->order('weigh', 'desc')->select())->toArray();//->field('id,pid,name,title,ismenu,status,icon')
  681. return $this->menus;
  682. }
  683. /**
  684. * 获取等级
  685. * @return array
  686. */
  687. public function getLevel()
  688. {
  689. if ($this->_logined) {//登录才能获取等级
  690. $rank = $this->_user->level;
  691. if (!$rank) {
  692. return false;
  693. }
  694. $lv = \think\Db::name('user_level')->where('level_id', $rank)->find();//->column('level_id,level_name,level_img');
  695. $this->addAllowFields(['level_name', 'level_img']);
  696. return $this->set(['level_name' => $lv['level_name'], 'level_img' => $lv['level_img']]);
  697. }
  698. }
  699. /**
  700. * 追加设置允许输出的字段
  701. * @param array $fields
  702. */
  703. public function addAllowFields($fields)
  704. {
  705. $this->allowFields = array_merge(
  706. $this->allowFields, array_change_key_case($fields)
  707. );
  708. }
  709. /**
  710. * 设置user扩展属性, name 为数组则为批量设置
  711. * @access public
  712. * @param string|array $name 配置参数名(支持二级配置 . 号分割)
  713. * @param mixed $value 配置值
  714. * @return mixed 具有扩展属性的user对象
  715. */
  716. public function set($name, $value = null)
  717. {
  718. if (!isset($this->_user)) $this->_user = [];
  719. // 字符串则表示单个配置设置
  720. if (is_string($name)) {
  721. if (!strpos($name, '.')) {
  722. $this->_user[strtolower($name)] = $value;
  723. } else {
  724. // 二维数组
  725. $name = explode('.', $name, 2);
  726. $this->_user[strtolower($name[0])][$name[1]] = $value;
  727. }
  728. return $value;
  729. }
  730. // 数组则表示批量设置
  731. if (is_array($name)) {
  732. foreach ($name as $k => $v) {
  733. if (!strpos($k, '.')) {
  734. $this->_user[strtolower($k)] = $v;
  735. } else {
  736. // 二维数组
  737. $k = explode('.', $k, 2);
  738. $this->_user[strtolower($k[0])][$k[1]] = $v;
  739. }
  740. }
  741. return $this->_user;
  742. }
  743. // 为空直接返回已有配置
  744. return $this->_user;
  745. }
  746. }