123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616 |
- <?php
- namespace app\common\controller;
- use app\admin\library\Auth;
- use app\common\library\Ip;
- use app\common\library\Ua;
- use app\common\utility\WhiteList;
- use app\main\constants\ErrorCodeConstants;
- use app\main\service\AdminService;
- use think\Config;
- use think\Controller;
- use think\Cookie;
- use think\Hook;
- use think\Lang;
- use think\Log;
- use think\Request;
- use think\Session;
- /**
- * 后台控制器基类
- */
- class Backend extends Controller
- {
- /**
- * 无需登录的方法,同时也就不需要鉴权了
- * @var array
- */
- protected $noNeedLogin = ['wxre', 'wxcallback','updateauth', 'autoviptoqdslogin'];
- /**
- * 无需鉴权的方法,但需要登录
- * @var array
- */
- protected $noNeedRight = ['recollect','export','ordersexport', 'getpalmsubaccountlist'];
- /**
- * 布局模板
- * @var string
- */
- protected $layout = 'default';
- /**
- * 权限控制类
- * @var Auth
- */
- protected $auth = null;
- /**
- * 快速搜索时执行查找的字段
- */
- protected $searchFields = 'id';
- /**
- * 是否是关联查询
- */
- protected $relationSearch = false;
- /**
- * 是否开启数据限制
- * 支持auth/personal
- * 表示按权限判断/仅限个人
- * 默认为禁用,若启用请务必保证表中存在admin_id字段
- */
- protected $dataLimit = false;
- /**
- * 数据限制字段
- */
- protected $dataLimitField = 'admin_id';
- /**
- * 是否开启Validate验证
- */
- protected $modelValidate = false;
- /**
- * 是否开启模型场景验证
- */
- protected $modelSceneValidate = false;
- /**
- * Multi方法可批量修改的字段
- */
- protected $multiFields = 'status';
- /**
- * 导入文件首行类型
- * 支持comment/name
- * 表示注释或字段名
- */
- protected $importHeadType = 'comment';
- /**
- * 当前登录用户的用户组id 超管1 普管2 渠道商3 代理商4
- */
- protected $group = null;
- /**
- * @var int 当前请求时间戳
- */
- protected $time = null;
- /**
- * 当前页面是否是微信三方平台授权页面
- * @var null
- */
- protected $platformAuthPage = false;
- /**
- * 引入后台控制器的traits
- */
- use \app\admin\library\traits\Backend;
- public function _initialize()
- {
- $this->time = $this->request->server('REQUEST_TIME');
- //config('site.url_agent', 'm{0}.mp.koread.cn'); //测试用,上线删除
- $modulename = $this->request->module();
- $controllername = strtolower($this->request->controller());
- $actionname = strtolower($this->request->action());
- $path = str_replace('.', '/', $controllername) . '/' . $actionname;
- // 定义是否Addtabs请求
- !defined('IS_ADDTABS') && define('IS_ADDTABS', input("addtabs") ? TRUE : FALSE);
- // 定义是否Dialog请求
- !defined('IS_DIALOG') && define('IS_DIALOG', input("dialog") ? TRUE : FALSE);
- // 定义是否AJAX请求
- !defined('IS_AJAX') && define('IS_AJAX', $this->request->isAjax());
- $this->auth = Auth::instance();
- // 设置当前请求的URI
- $this->auth->setRequestUri($path);
- // 检测是否需要验证登录
- if (!$this->auth->match($this->noNeedLogin))
- {
- //检测是否登录
- if (!$this->auth->isLogin())
- {
- Hook::listen('admin_nologin', $this);
- $url = Session::get('referer');
- $url = $url ? $url : get_url_no_port();
- // $this->error(__('Please login first'), url('index/login', ['url' => $url]));
- $this->redirect(url('index/login', ['url' => $url]));
- }
- // 判断账号是否已被禁止
- if ($this->auth->status != 'normal')
- {
- $url = Session::get('referer');
- $url = $url ? $url : get_url_no_port();
- $this->error('您的账号已无访问权限,请联系客服获取详情!', url('index/login', ['url' => $url]), '', 10);
- }
- // 判断是否需要验证权限
- if (!$this->auth->match($this->noNeedRight))
- {
- // 判断控制器和方法判断是否有对应权限
- if (!$this->auth->check($path))
- {
- Hook::listen('admin_nopermission', $this);
- $this->error(__('You have no permission'), '111');
- }
- }
- }
- if($this->auth->isLogin()){
- //密码修改后需要重新登录
- $admin = Session::get("admin");
- $groupIds = $this->auth->getGroupIds();
- $this->group = current($groupIds);
- $limit =AdminService::instance()->checkLimit($this->group, $admin['id'], Request::instance()->baseUrl(), Ip::ip());
- if ($limit->code != ErrorCodeConstants::SUCCESS) {
- $this->error($limit->msg, '', $limit->code);
- }
- //判断是否跳过强制授权
- $adminExtend = model('AdminExtend')->where('admin_id',$this->auth->id)->find();
- //判断配号代理商/渠道商,如果没有授权3个平台则跳转到授权页面,不弹出公告
- if(($this->group == 4 && $adminExtend->distribute == '1') || $this->group == 3){
- $adminCon = model('AdminConfig')->where('admin_id',$this->auth->id)->find();
- $is_fouce = $adminCon['is_fouce'];
- if($is_fouce == '1'){
- if(!model('Ptoken')->checkPlatformIsAuth($adminCon['platform_list'],$this->auth->id)){
- $this->platformAuthPage = true;
- if (!$this->request->isPost() && $controllername != "admin.config" && $controllername!='login' && $controllername!='loginout') { //检查是否需要跳转到授权页面
- Cookie::set('noNotice',1);
- $jumpUrl = Config::get('site.scheme').'://'.Config::get('site.url_root').'/admin/admin/config/index?ref=addtabs';
- $this->redirect($jumpUrl,[], 302);
- exit();
- }
- }else{
- if(Cookie::has('noNotice')){
- Cookie::delete('noNotice');
- }
- }
- }
- }
- $this->assign('backend_group',$this->group);
- //渠道商/代理商推广域名
- if ($this->group == 3) {
- //多账号切换
- $res = model('Relevance')->where("find_in_set({$this->auth->id},admin_ids)")->find();
- if(!empty($res)){
- $adminIds = $res->admin_ids;
- //多账号渠道添加到渠道城市白名单
- if($channelIds = explode(',',$adminIds)){
- foreach($channelIds as $id){
- WhiteList::addChannelCity($id);
- }
- }
- $admins = model('Admin')->where("id in({$adminIds})")->select();
- foreach($admins as $key=>$val){
- if($val->id == $this->auth->id){
- unset($admins[$key]);
- }
- }
- $this->assign('adminInfos',$admins);
- }
- }
- } else {
- $limit =AdminService::instance()->checkLimit(0, 0, Request::instance()->baseUrl(), Ip::ip());
- if ($limit->code != ErrorCodeConstants::SUCCESS) {
- $this->error($limit->msg, '', $limit->code);
- }
- }
- // 非选项卡时重定向
- if (!$this->request->isPost() && !IS_AJAX && !IS_ADDTABS && !IS_DIALOG && input("ref") == 'addtabs' && !$this->platformAuthPage)
- {
- $url = preg_replace_callback("/([\?|&]+)ref=addtabs(&?)/i", function ($matches) {
- return $matches[2] == '&' ? $matches[1] : '';
- }, get_url_no_port());
- $this->redirect('index/index', [], 302, ['referer' => $url]);
- exit;
- }
- //记录部分log信息
- Log::info('OS:' . Ua::getOs() . ' UA:' . Ua::getUa() . ' NetType:' . Ua::getNetType() . ' IP:' . Ip::ip() . ' [' . Ip::str() . '] admin_id:' . $this->auth->id . ' group:' . $this->group . ' REMOTE_ADDR:' . (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '') . ' HTTP_X_FORWARDED_FOR:' . (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : ''));
- $post = json_encode($_POST, JSON_UNESCAPED_UNICODE);
- Log::info('POST:' . mb_substr($post, 0, 500));
- // 设置面包屑导航数据
- $breadcrumb = $this->auth->getBreadCrumb($path);
- array_pop($breadcrumb);
- $this->view->breadcrumb = $breadcrumb;
- // 如果有使用模板布局
- if ($this->layout)
- {
- $this->view->engine->layout('layout/' . $this->layout);
- }
- // 语言检测
- $lang = strip_tags(Lang::detect());
- $site = Config::get("site");
- // 配置后台默认主题
- $site['skin'] = $site['skin'] ?? 'skin-blue-light';
- $upload = \app\common\model\Config::upload();
- // 上传信息配置后
- Hook::listen("upload_config_init", $upload);
- // 配置信息
- $config = [
- 'site' => array_intersect_key($site, array_flip(['name', 'cdnurl', 'version', 'timezone', 'languages', 'scheme', 'url_agent', 'url_referral'])),
- 'upload' => $upload,
- 'modulename' => $modulename,
- 'controllername' => $controllername,
- 'actionname' => $actionname,
- 'jsname' => 'backend/' . str_replace('.', '/', $controllername),
- 'moduleurl' => rtrim(url("/{$modulename}", '', false), '/'),
- 'language' => $lang,
- 'fastadmin' => Config::get('fastadmin'),
- 'referer' => Session::get("referer")
- ];
- Config::set('upload', array_merge(Config::get('upload'), $upload));
- /**
- * 动态初始化微信开放平台参数
- */
- if($this->group == 3 || $this->group == 4) { //判断是否是渠道商 或者 代理商
- $channel_id = $this->auth->agent_id ? $this->auth->agent_id : $this->auth->channel_id; //判断配号代理商 或者 普通代理商/渠道商
- if ($adminInfo = model('AdminConfig')->getAdminInfoAll($channel_id)) {
- Config::set('wechat.app_id', $adminInfo['platform_appid']);
- Config::set('wechat.secret', $adminInfo['platform_secret']);
- Config::set('wechat.token', $adminInfo['platform_token']);
- Config::set('wechat.aes_key', $adminInfo['platform_aes_key']);
- }
- }
- // 配置信息后
- Hook::listen("config_init", $config);
- //加载当前控制器语言包
- $this->loadlang($controllername);
- //渲染站点配置
- $this->assign('site', $site);
- //渲染配置信息
- $this->assign('config', $config);
- //渲染权限对象
- $this->assign('auth', $this->auth);
- //渲染管理员对象
- $this->assign('admin', Session::get('admin'));
- /**
- * 下发当前用户的用户组
- */
- $this->assignconfig('group', $this->group);
- $this->assignconfig('admin_id', $this->auth->id);
- if (!$this->request->isAjax() && ($controllername != 'notice' || $actionname != 'show')) {
- //检查是否有需要弹出的公告dialog
- if(!Cookie::has('noNotice')){ //如果需要跳转到授权公众号页面则不弹出notice
- if (Session::has('notice_id')) {
- $this->assignconfig('notice_id', Session::get('notice_id'));
- }
- }
- }
- //KL的IP压入永久白名单
- WhiteList::addChannelIp($this->request->ip());
- //KL的渠道城市压入永久白名单
- if($this->group == 3 || $this->group == 4){
- WhiteList::addChannelCity($this->auth->id);
- }
- }
- /**
- * 加载语言文件
- * @param string $name
- */
- protected function loadlang($name)
- {
- Lang::load(APP_PATH . $this->request->module() . '/lang/' . Lang::detect() . '/' . str_replace('.', '/', $name) . '.php');
- }
- /**
- * 渲染配置信息
- * @param mixed $name 键名或数组
- * @param mixed $value 值
- */
- protected function assignconfig($name, $value = '')
- {
- $this->view->config = array_merge($this->view->config ? $this->view->config : [], is_array($name) ? $name : [$name => $value]);
- }
- /**
- * 生成查询所需要的条件,排序方式
- * @param mixed $searchfields 快速查询的字段
- * @param boolean $relationSearch 是否关联查询
- * @return array
- */
- protected function buildparams($searchfields = null, $relationSearch = null)
- {
- $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
- $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
- $search = $this->request->get("search", '');
- $filter = $this->request->get("filter", '');
- $op = $this->request->get("op", '', 'trim');
- $sort = $this->request->get("sort", "id");
- $order = $this->request->get("order", "DESC");
- $offset = $this->request->get("offset", 0);
- $limit = $this->request->get("limit", 0);
- $filter = json_decode($filter, TRUE);
- $op = json_decode($op, TRUE);
- $filter = $filter ? $filter : [];
- $where = [];
- $tableName = '';
- if ($relationSearch)
- {
- if (!empty($this->model))
- {
- $tableName = $this->model->getQuery()->getTable() . ".";
- }
- $sort = stripos($sort, ".") === false ? $tableName . $sort : $sort;
- }
- $adminIds = $this->getDataLimitAdminIds();
- if (is_array($adminIds))
- {
- $where[] = [$tableName . $this->dataLimitField, 'in', $adminIds];
- }
- if ($search)
- {
- $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
- foreach ($searcharr as $k => &$v)
- {
- $v = stripos($v, ".") === false ? $tableName . $v : $v;
- }
- unset($v);
- $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
- }
- foreach ($filter as $k => $v)
- {
- $sym = isset($op[$k]) ? $op[$k] : '=';
- if (stripos($k, ".") === false)
- {
- $k = $tableName . $k;
- }
- $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
- switch ($sym)
- {
- case '=':
- case '!=':
- $where[] = [$k, $sym, (string) $v];
- break;
- case 'LIKE':
- case 'NOT LIKE':
- case 'LIKE %...%':
- case 'NOT LIKE %...%':
- $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
- break;
- case '>':
- case '>=':
- case '<':
- case '<=':
- $where[] = [$k, $sym, intval($v)];
- break;
- case 'IN':
- case 'IN(...)':
- case 'NOT IN':
- case 'NOT IN(...)':
- $where[] = [$k, str_replace('(...)', '', $sym), explode(',', $v)];
- break;
- case 'BETWEEN':
- case 'NOT BETWEEN':
- $arr = array_slice(explode(',', $v), 0, 2);
- if (stripos($v, ',') === false || !array_filter($arr))
- break;
- //当出现一边为空时改变操作符
- if ($arr[0] === '')
- {
- $sym = $sym == 'BETWEEN' ? '<=' : '>';
- $arr = $arr[1];
- }
- else if ($arr[1] === '')
- {
- $sym = $sym == 'BETWEEN' ? '>=' : '<';
- $arr = $arr[0];
- }
- $where[] = [$k, $sym, $arr];
- break;
- case 'RANGE':
- case 'NOT RANGE':
- $v = str_replace(' - ', ',', $v);
- $arr = array_slice(explode(',', $v), 0, 2);
- if (stripos($v, ',') === false || !array_filter($arr))
- break;
- //当出现一边为空时改变操作符
- if ($arr[0] === '')
- {
- $sym = $sym == 'RANGE' ? '<=' : '>';
- $arr = $arr[1];
- }
- else if ($arr[1] === '')
- {
- $sym = $sym == 'RANGE' ? '>=' : '<';
- $arr = $arr[0];
- }
- $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
- break;
- case 'LIKE':
- case 'LIKE %...%':
- $where[] = [$k, 'LIKE', "%{$v}%"];
- break;
- case 'NULL':
- case 'IS NULL':
- case 'NOT NULL':
- case 'IS NOT NULL':
- $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
- break;
- case 'FIND_IN_SET':
- $where[] = "FIND_IN_SET('{$v}', {$k})";
- break;
- default:
- break;
- }
- }
- $where = function($query) use ($where) {
- foreach ($where as $k => $v)
- {
- if (is_array($v))
- {
- call_user_func_array([$query, 'where'], $v);
- }
- else
- {
- $query->where($v);
- }
- }
- };
- return [$where, $sort, $order, $offset, $limit];
- }
- /**
- * 获取数据限制的管理员ID
- * 禁用数据限制时返回的是null
- * @return mixed
- */
- protected function getDataLimitAdminIds()
- {
- if (!$this->dataLimit)
- {
- return null;
- }
- if ($this->auth->isSuperAdmin())
- {
- return null;
- }
- $adminIds = [];
- if (in_array($this->dataLimit, ['auth', 'personal']))
- {
- $adminIds = $this->dataLimit == 'auth' ? $this->auth->getChildrenAdminIds(true) : [$this->auth->id];
- }
- return $adminIds;
- }
- /**
- * Selectpage的实现方法
- *
- * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
- * 这里示例了所有的参数,所以比较复杂,实现上自己实现只需简单的几行即可
- *
- */
- protected function selectpage()
- {
- //设置过滤方法
- $this->request->filter(['strip_tags', 'htmlspecialchars']);
- //搜索关键词,客户端输入以空格分开,这里接收为数组
- $word = (array) $this->request->request("q_word/a");
- //当前页
- $page = $this->request->request("page");
- //分页大小
- $pagesize = $this->request->request("per_page");
- //搜索条件
- $andor = $this->request->request("and_or");
- //排序方式
- $orderby = (array) $this->request->request("order_by/a");
- //显示的字段
- $field = $this->request->request("field");
- //主键
- $primarykey = $this->request->request("pkey_name");
- //主键值
- $primaryvalue = $this->request->request("pkey_value");
- //搜索字段
- $searchfield = (array) $this->request->request("search_field/a");
- //自定义搜索条件
- $custom = (array) $this->request->request("custom/a");
- $order = [];
- foreach ($orderby as $k => $v)
- {
- $order[$v[0]] = $v[1];
- }
- $field = $field ? $field : 'name';
- //如果有primaryvalue,说明当前是初始化传值
- if ($primaryvalue !== null)
- {
- $where = [$primarykey => ['in', $primaryvalue]];
- }
- else
- {
- $where = function($query) use($word, $andor, $field, $searchfield, $custom) {
- foreach ($word as $k => $v)
- {
- foreach ($searchfield as $m => $n)
- {
- $query->where($n, "like", "%{$v}%", $andor);
- }
- }
- if ($custom && is_array($custom))
- {
- foreach ($custom as $k => $v)
- {
- $query->where($k, '=', $v);
- }
- }
- };
- }
- $adminIds = $this->getDataLimitAdminIds();
- if (is_array($adminIds))
- {
- $this->model->where($this->dataLimitField, 'in', $adminIds);
- }
- $list = [];
- $total = $this->model->where($where)->count();
- if ($total > 0)
- {
- if (is_array($adminIds))
- {
- $this->model->where($this->dataLimitField, 'in', $adminIds);
- }
- $list = $this->model->where($where)
- ->order($order)
- ->page($page, $pagesize)
- ->field("{$primarykey},{$field}")
- ->field("password,salt", true)
- ->select();
- }
- //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
- return json(['list' => $list, 'total' => $total]);
- }
- /**
- * 获取当前账号的渠道ID
- * @return mixed|null
- */
- protected function getCurrentAccountChannelId()
- {
- return $this->auth->agent_id ? $this->auth->agent_id : $this->auth->channel_id;
- }
- }
|