审查视图

application/common/controller/Backend.php 18.7 KB
Karson authored
1 2 3 4 5 6 7 8 9
<?php

namespace app\common\controller;

use app\admin\library\Auth;
use think\Config;
use think\Controller;
use think\Hook;
use think\Lang;
10
use think\Loader;
Karson authored
11
use think\Session;
12
use fast\Tree;
Karson authored
13
use think\Validate;
Karson authored
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

/**
 * 后台控制器基类
 */
class Backend extends Controller
{

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 布局模板
     * @var string
     */
    protected $layout = 'default';

    /**
     * 权限控制类
     * @var Auth
     */
    protected $auth = null;

    /**
46 47 48 49 50 51
     * 模型对象
     * @var \think\Model
     */
    protected $model = null;

    /**
Karson authored
52 53 54 55 56 57 58 59 60 61 62 63
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'id';

    /**
     * 是否是关联查询
     */
    protected $relationSearch = false;

    /**
     * 是否开启数据限制
     * 支持auth/personal
64
     * 表示按权限判断/仅限个人
Karson authored
65 66 67 68 69 70 71 72
     * 默认为禁用,若启用请务必保证表中存在admin_id字段
     */
    protected $dataLimit = false;

    /**
     * 数据限制字段
     */
    protected $dataLimitField = 'admin_id';
73
74 75 76 77
    /**
     * 数据限制开启时自动填充限制字段值
     */
    protected $dataLimitFieldAutoFill = true;
Karson authored
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

    /**
     * 是否开启Validate验证
     */
    protected $modelValidate = false;

    /**
     * 是否开启模型场景验证
     */
    protected $modelSceneValidate = false;

    /**
     * Multi方法可批量修改的字段
     */
    protected $multiFields = 'status';

    /**
95 96 97 98 99
     * Selectpage可显示的字段
     */
    protected $selectpageFields = '*';

    /**
100 101 102 103 104
     * 前台提交过来,需要排除的字段数据
     */
    protected $excludeFields = "";

    /**
105 106 107 108 109 110 111
     * 导入文件首行类型
     * 支持comment/name
     * 表示注释或字段名
     */
    protected $importHeadType = 'comment';

    /**
Karson authored
112 113 114 115 116 117 118
     * 引入后台控制器的traits
     */
    use \app\admin\library\traits\Backend;

    public function _initialize()
    {
        $modulename = $this->request->module();
119
        $controllername = Loader::parseName($this->request->controller());
Karson authored
120 121 122 123 124
        $actionname = strtolower($this->request->action());

        $path = str_replace('.', '/', $controllername) . '/' . $actionname;

        // 定义是否Addtabs请求
125
        !defined('IS_ADDTABS') && define('IS_ADDTABS', input("addtabs") ? true : false);
Karson authored
126 127

        // 定义是否Dialog请求
128
        !defined('IS_DIALOG') && define('IS_DIALOG', input("dialog") ? true : false);
Karson authored
129 130 131 132 133 134 135 136 137

        // 定义是否AJAX请求
        !defined('IS_AJAX') && define('IS_AJAX', $this->request->isAjax());

        $this->auth = Auth::instance();

        // 设置当前请求的URI
        $this->auth->setRequestUri($path);
        // 检测是否需要验证登录
138
        if (!$this->auth->match($this->noNeedLogin)) {
Karson authored
139
            //检测是否登录
140
            if (!$this->auth->isLogin()) {
Karson authored
141 142 143
                Hook::listen('admin_nologin', $this);
                $url = Session::get('referer');
                $url = $url ? $url : $this->request->url();
144 145 146 147
                if ($url == '/') {
                    $this->redirect('index/login', [], 302, ['referer' => $url]);
                    exit;
                }
Karson authored
148 149 150
                $this->error(__('Please login first'), url('index/login', ['url' => $url]));
            }
            // 判断是否需要验证权限
151
            if (!$this->auth->match($this->noNeedRight)) {
152
                // 判断控制器和方法是否有对应权限
153
                if (!$this->auth->check($path)) {
Karson authored
154 155 156 157 158 159 160
                    Hook::listen('admin_nopermission', $this);
                    $this->error(__('You have no permission'), '');
                }
            }
        }

        // 非选项卡时重定向
161 162
        if (!$this->request->isPost() && !IS_AJAX && !IS_ADDTABS && !IS_DIALOG && input("ref") == 'addtabs') {
            $url = preg_replace_callback("/([\?|&]+)ref=addtabs(&?)/i", function ($matches) {
Karson authored
163 164
                return $matches[2] == '&' ? $matches[1] : '';
            }, $this->request->url());
165 166
            if (Config::get('url_domain_deploy')) {
                if (stripos($url, $this->request->server('SCRIPT_NAME')) === 0) {
167 168 169 170
                    $url = substr($url, strlen($this->request->server('SCRIPT_NAME')));
                }
                $url = url($url, '', false);
            }
Karson authored
171 172 173 174 175 176 177 178 179 180
            $this->redirect('index/index', [], 302, ['referer' => $url]);
            exit;
        }

        // 设置面包屑导航数据
        $breadcrumb = $this->auth->getBreadCrumb($path);
        array_pop($breadcrumb);
        $this->view->breadcrumb = $breadcrumb;

        // 如果有使用模板布局
181
        if ($this->layout) {
Karson authored
182 183 184 185
            $this->view->engine->layout('layout/' . $this->layout);
        }

        // 语言检测
186
        $lang = strip_tags($this->request->langset());
Karson authored
187 188 189 190 191 192 193 194 195 196

        $site = Config::get("site");

        $upload = \app\common\model\Config::upload();

        // 上传信息配置后
        Hook::listen("upload_config_init", $upload);

        // 配置信息
        $config = [
197
            'site'           => array_intersect_key($site, array_flip(['name', 'indexurl', 'cdnurl', 'version', 'timezone', 'languages'])),
Karson authored
198 199 200 201 202 203 204 205 206
            'upload'         => $upload,
            'modulename'     => $modulename,
            'controllername' => $controllername,
            'actionname'     => $actionname,
            'jsname'         => 'backend/' . str_replace('.', '/', $controllername),
            'moduleurl'      => rtrim(url("/{$modulename}", '', false), '/'),
            'language'       => $lang,
            'referer'        => Session::get("referer")
        ];
207
        $config = array_merge($config, Config::get("view_replace_str"));
208
Karson authored
209
        Config::set('upload', array_merge(Config::get('upload'), $upload));
210
Karson authored
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
        // 配置信息后
        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'));
    }

    /**
     * 加载语言文件
     * @param string $name
     */
    protected function loadlang($name)
    {
Karson authored
231
        $name = Loader::parseName($name);
232
        Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
Karson authored
233 234 235 236
    }

    /**
     * 渲染配置信息
237
     * @param mixed $name  键名或数组
238
     * @param mixed $value 值
Karson authored
239 240 241 242 243 244 245 246
     */
    protected function assignconfig($name, $value = '')
    {
        $this->view->config = array_merge($this->view->config ? $this->view->config : [], is_array($name) ? $name : [$name => $value]);
    }

    /**
     * 生成查询所需要的条件,排序方式
247
     * @param mixed   $searchfields   快速查询的字段
Karson authored
248 249 250 251 252 253 254 255 256 257
     * @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');
Karson authored
258
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
Karson authored
259 260 261
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset", 0);
        $limit = $this->request->get("limit", 0);
262 263
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
Karson authored
264 265 266
        $filter = $filter ? $filter : [];
        $where = [];
        $tableName = '';
267 268
        if ($relationSearch) {
            if (!empty($this->model)) {
269
                $name = $this->model->getTable();
270 271 272 273 274
                $tableName = $name . '.';
            }
            $sortArr = explode(',', $sort);
            foreach ($sortArr as $index => & $item) {
                $item = stripos($item, ".") === false ? $tableName . trim($item) : $item;
Karson authored
275
            }
276 277
            unset($item);
            $sort = implode(',', $sortArr);
Karson authored
278 279
        }
        $adminIds = $this->getDataLimitAdminIds();
280
        if (is_array($adminIds)) {
281
            $where[] = [$tableName . $this->dataLimitField, 'in', $adminIds];
Karson authored
282
        }
283
        if ($search) {
Karson authored
284
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
285
            foreach ($searcharr as $k => &$v) {
Karson authored
286 287 288 289 290
                $v = stripos($v, ".") === false ? $tableName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
291
        foreach ($filter as $k => $v) {
292 293 294
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
Karson authored
295
            $sym = isset($op[$k]) ? $op[$k] : '=';
296
            if (stripos($k, ".") === false) {
Karson authored
297 298
                $k = $tableName . $k;
            }
299
            $v = !is_array($v) ? trim($v) : $v;
Karson authored
300
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
301 302 303 304 305 306 307 308 309 310 311
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }
312
            switch ($sym) {
Karson authored
313
                case '=':
314
                case '<>':
315
                    $where[] = [$k, $sym, (string)$v];
Karson authored
316 317 318 319 320 321 322 323 324 325 326 327 328
                    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;
329
                case 'FINDIN':
330
                case 'FINDINSET':
331
                case 'FIND_IN_SET':
332 333 334 335 336 337
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    foreach ($v as $index => $item) {
                        $item = str_replace([' ', ',', "'"], '', $item);
                        $item = addslashes(htmlentities(strip_tags($item)));
                        $where[] = "FIND_IN_SET('{$item}', `" . ($relationSearch ? str_replace('.', '`.`', $k) : $k) . "`)";
                    }
338
                    break;
Karson authored
339 340 341 342
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
343
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
Karson authored
344 345 346 347
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
348
                    if (stripos($v, ',') === false || !array_filter($arr)) {
349
                        continue 2;
350
                    }
Karson authored
351
                    //当出现一边为空时改变操作符
352
                    if ($arr[0] === '') {
Karson authored
353 354
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
355
                    } elseif ($arr[1] === '') {
Karson authored
356 357 358 359 360 361 362 363 364
                        $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);
365
                    if (stripos($v, ',') === false || !array_filter($arr)) {
366
                        continue 2;
367
                    }
Karson authored
368
                    //当出现一边为空时改变操作符
369
                    if ($arr[0] === '') {
Karson authored
370 371
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
372
                    } elseif ($arr[1] === '') {
Karson authored
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
        }
388 389 390
        $where = function ($query) use ($where) {
            foreach ($where as $k => $v) {
                if (is_array($v)) {
Karson authored
391
                    call_user_func_array([$query, 'where'], $v);
392
                } else {
Karson authored
393 394 395 396 397 398 399 400 401 402 403 404 405 406
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit];
    }

    /**
     * 获取数据限制的管理员ID
     * 禁用数据限制时返回的是null
     * @return mixed
     */
    protected function getDataLimitAdminIds()
    {
407
        if (!$this->dataLimit) {
Karson authored
408 409
            return null;
        }
410
        if ($this->auth->isSuperAdmin()) {
411 412
            return null;
        }
Karson authored
413
        $adminIds = [];
414
        if (in_array($this->dataLimit, ['auth', 'personal'])) {
Karson authored
415 416 417 418 419 420 421
            $adminIds = $this->dataLimit == 'auth' ? $this->auth->getChildrenAdminIds(true) : [$this->auth->id];
        }
        return $adminIds;
    }

    /**
     * Selectpage的实现方法
422
     *
Karson authored
423 424
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数,所以比较复杂,实现上自己实现只需简单的几行即可
425
     *
Karson authored
426 427 428 429 430 431 432
     */
    protected function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
433
        $word = (array)$this->request->request("q_word/a");
Karson authored
434
        //当前页
435
        $page = $this->request->request("pageNumber");
Karson authored
436
        //分页大小
437
        $pagesize = $this->request->request("pageSize");
Karson authored
438
        //搜索条件
439
        $andor = $this->request->request("andOr", "and", "strtoupper");
Karson authored
440
        //排序方式
441
        $orderby = (array)$this->request->request("orderBy/a");
Karson authored
442
        //显示的字段
443
        $field = $this->request->request("showField");
Karson authored
444
        //主键
445
        $primarykey = $this->request->request("keyField");
Karson authored
446
        //主键值
447
        $primaryvalue = $this->request->request("keyValue");
Karson authored
448
        //搜索字段
449
        $searchfield = (array)$this->request->request("searchField/a");
Karson authored
450
        //自定义搜索条件
451
        $custom = (array)$this->request->request("custom/a");
452 453 454
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
455
        if ($istree) {
456 457 458
            $word = [];
            $pagesize = 99999;
        }
Karson authored
459
        $order = [];
460
        foreach ($orderby as $k => $v) {
Karson authored
461 462 463 464 465
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
466
        if ($primaryvalue !== null) {
Karson authored
467
            $where = [$primarykey => ['in', $primaryvalue]];
468
            $pagesize = 99999;
469 470
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
471 472
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
Karson authored
473 474 475 476 477
                $word = array_filter($word);
                if ($word) {
                    foreach ($word as $k => $v) {
                        $query->where(str_replace(',', $logic, $searchfield), "like", "%{$v}%");
                    }
Karson authored
478
                }
479 480
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
481 482 483 484 485
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
Karson authored
486 487 488 489 490
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
491
        if (is_array($adminIds)) {
Karson authored
492 493 494 495
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->count();
496 497
        if ($total > 0) {
            if (is_array($adminIds)) {
Karson authored
498 499
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
500
            $datalist = $this->model->where($where)
501 502
                ->order($order)
                ->page($page, $pagesize)
503
                ->field($this->selectpageFields)
504
                ->select();
505 506 507 508
            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                $list[] = [
                    $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
509 510
                    $field      => isset($item[$field]) ? $item[$field] : '',
                    'pid'       => isset($item['pid']) ? $item['pid'] : 0
511 512
                ];
            }
513
            if ($istree && !$primaryvalue) {
514 515 516
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
517
                if (!$ishtml) {
518 519 520 521 522 523
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
Karson authored
524 525 526 527
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }
Karson authored
528 529 530 531 532 533 534 535 536

    /**
     * 刷新Token
     */
    protected function token()
    {
        $token = $this->request->post('__token__');

        //验证Token
Karson authored
537
        if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
Karson authored
538 539 540 541 542 543
            $this->error(__('Token verification error'), '', ['__token__' => $this->request->token()]);
        }

        //刷新Token
        $this->request->token();
    }
Karson authored
544
}