123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605 |
- <?php
- namespace app\common\controller;
- use app\admin\library\Auth;
- use think\Config;
- use think\Controller;
- use think\Hook;
- use think\Lang;
- use think\Loader;
- use think\Model;
- use think\Session;
- use fast\Tree;
- use think\Validate;
- class Backend extends Controller
- {
-
- protected $noNeedLogin = [];
-
- protected $noNeedRight = [];
-
- protected $layout = 'default';
-
- protected $auth = null;
-
- protected $model = null;
-
- protected $searchFields = 'id';
-
- protected $relationSearch = false;
-
- protected $dataLimit = false;
-
- protected $dataLimitField = 'admin_id';
-
- protected $dataLimitFieldAutoFill = true;
-
- protected $modelValidate = false;
-
- protected $modelSceneValidate = false;
-
- protected $multiFields = 'status';
-
- protected $selectpageFields = '*';
-
- protected $excludeFields = "";
-
- protected $importHeadType = 'comment';
-
- use \app\admin\library\traits\Backend;
- public function _initialize()
- {
- $modulename = $this->request->module();
- $controllername = Loader::parseName($this->request->controller());
- $actionname = strtolower($this->request->action());
- $path = str_replace('.', '/', $controllername) . '/' . $actionname;
-
- !defined('IS_ADDTABS') && define('IS_ADDTABS', input("addtabs") ? true : false);
-
- !defined('IS_DIALOG') && define('IS_DIALOG', input("dialog") ? true : false);
-
- !defined('IS_AJAX') && define('IS_AJAX', $this->request->isAjax());
-
- check_ip_allowed();
- $this->auth = Auth::instance();
-
- $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 : $this->request->url();
- if (in_array($this->request->pathinfo(), ['/', 'index/index'])) {
- $this->redirect('index/login', [], 302, ['referer' => $url]);
- exit;
- }
- $this->error(__('Please login first'), url('index/login', ['url' => $url]));
- }
-
- if (!$this->auth->match($this->noNeedRight)) {
-
- if (!$this->auth->check($path)) {
- Hook::listen('admin_nopermission', $this);
- $this->error(__('You have no permission'), '');
- }
- }
- }
-
- if (!$this->request->isPost() && !IS_AJAX && !IS_ADDTABS && !IS_DIALOG && input("ref") == 'addtabs') {
- $url = preg_replace_callback("/([\?|&]+)ref=addtabs(&?)/i", function ($matches) {
- return $matches[2] == '&' ? $matches[1] : '';
- }, $this->request->url());
- if (Config::get('url_domain_deploy')) {
- if (stripos($url, $this->request->server('SCRIPT_NAME')) === 0) {
- $url = substr($url, strlen($this->request->server('SCRIPT_NAME')));
- }
- $url = url($url, '', false);
- }
- $this->redirect('index/index', [], 302, ['referer' => $url]);
- exit;
- }
-
- $breadcrumb = [];
- if (!IS_DIALOG && !config('fastadmin.multiplenav') && config('fastadmin.breadcrumb')) {
- $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($this->request->langset());
- $site = Config::get("site");
- $upload = \app\common\model\Config::upload();
-
- Hook::listen("upload_config_init", $upload);
-
- $config = [
- 'site' => array_intersect_key($site, array_flip(['name', 'indexurl', 'cdnurl', 'version', 'timezone', 'languages'])),
- 'upload' => $upload,
- 'modulename' => $modulename,
- 'controllername' => $controllername,
- 'actionname' => $actionname,
- 'jsname' => 'backend/' . str_replace('.', '/', $controllername),
- 'moduleurl' => rtrim(url("/{$modulename}", '', false), '/'),
- 'language' => $lang,
- 'referer' => Session::get("referer")
- ];
- $config = array_merge($config, Config::get("view_replace_str"));
- Config::set('upload', array_merge(Config::get('upload'), $upload));
-
- 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'));
- }
-
- protected function loadlang($name)
- {
- $name = Loader::parseName($name);
- Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
- }
-
- protected function assignconfig($name, $value = '')
- {
- $this->view->config = array_merge($this->view->config ? $this->view->config : [], is_array($name) ? $name : [$name => $value]);
- }
-
- 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", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
- $order = $this->request->get("order", "DESC");
- $offset = $this->request->get("offset/d", 0);
- $limit = $this->request->get("limit/d", 999999);
-
- $page = $limit ? intval($offset / $limit) + 1 : 1;
- if ($this->request->has("page")) {
- $page = $this->request->get("page/d", 1);
- }
- $this->request->get([config('paginate.var_page') => $page]);
- $filter = (array)json_decode($filter, true);
- $op = (array)json_decode($op, true);
- $filter = $filter ? $filter : [];
- $where = [];
- $alias = [];
- $bind = [];
- $name = '';
- $aliasName = '';
- if (!empty($this->model) && $this->relationSearch) {
- $name = $this->model->getTable();
- $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
- $aliasName = $alias[$name] . '.';
- }
- $sortArr = explode(',', $sort);
- foreach ($sortArr as $index => & $item) {
- $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
- }
- unset($item);
- $sort = implode(',', $sortArr);
- $adminIds = $this->getDataLimitAdminIds();
- if (is_array($adminIds)) {
- $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
- }
- if ($search) {
- $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
- foreach ($searcharr as $k => &$v) {
- $v = stripos($v, ".") === false ? $aliasName . $v : $v;
- }
- unset($v);
- $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
- }
- $index = 0;
- foreach ($filter as $k => $v) {
- if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
- continue;
- }
- $sym = isset($op[$k]) ? $op[$k] : '=';
- if (stripos($k, ".") === false) {
- $k = $aliasName . $k;
- }
- $v = !is_array($v) ? trim($v) : $v;
- $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
-
- if (!is_array($v)) {
- if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
- $sym = strtoupper($v);
- }
- if (in_array($v, ['""', "''"])) {
- $v = '';
- $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 'FINDIN':
- case 'FINDINSET':
- case 'FIND_IN_SET':
- $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
- $findArr = array_values($v);
- foreach ($findArr as $idx => $item) {
- $bindName = "item_" . $index . "_" . $idx;
- $bind[$bindName] = $item;
- $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
- }
- break;
- case 'IN':
- case 'IN(...)':
- case 'NOT IN':
- case 'NOT IN(...)':
- $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
- break;
- case 'BETWEEN':
- case 'NOT BETWEEN':
- $arr = array_slice(explode(',', $v), 0, 2);
- if (stripos($v, ',') === false || !array_filter($arr)) {
- continue 2;
- }
-
- if ($arr[0] === '') {
- $sym = $sym == 'BETWEEN' ? '<=' : '>';
- $arr = $arr[1];
- } elseif ($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)) {
- continue 2;
- }
-
- if ($arr[0] === '') {
- $sym = $sym == 'RANGE' ? '<=' : '>';
- $arr = $arr[1];
- } elseif ($arr[1] === '') {
- $sym = $sym == 'RANGE' ? '>=' : '<';
- $arr = $arr[0];
- }
- $tableArr = explode('.', $k);
- if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
-
- $relation = Loader::parseName($tableArr[0], 1, false);
- $alias[$this->model->$relation()->getTable()] = $tableArr[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;
- }
- $index++;
- }
- if (!empty($this->model)) {
- $this->model->alias($alias);
- }
- $model = $this->model;
- $where = function ($query) use ($where, $alias, $bind, &$model) {
- if (!empty($model)) {
- $model->alias($alias);
- $model->bind($bind);
- }
- 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, $page, $alias, $bind];
- }
-
- 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;
- }
-
- protected function selectpage()
- {
-
- $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);
-
- $word = (array)$this->request->request("q_word/a");
-
- $page = $this->request->request("pageNumber");
-
- $pagesize = $this->request->request("pageSize");
-
- $andor = $this->request->request("andOr", "and", "strtoupper");
-
- $orderby = (array)$this->request->request("orderBy/a");
-
- $field = $this->request->request("showField");
-
- $primarykey = $this->request->request("keyField");
-
- $primaryvalue = $this->request->request("keyValue");
-
- $searchfield = (array)$this->request->request("searchField/a");
-
- $custom = (array)$this->request->request("custom/a");
-
- $istree = $this->request->request("isTree", 0);
- $ishtml = $this->request->request("isHtml", 0);
- if ($istree) {
- $word = [];
- $pagesize = 999999;
- }
- $order = [];
- foreach ($orderby as $k => $v) {
- $order[$v[0]] = $v[1];
- }
- $field = $field ? $field : 'name';
-
- if ($primaryvalue !== null) {
- $where = [$primarykey => ['in', $primaryvalue]];
- $pagesize = 999999;
- } else {
- $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
- $logic = $andor == 'AND' ? '&' : '|';
- $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
- $searchfield = str_replace(',', $logic, $searchfield);
- $word = array_filter(array_unique($word));
- if (count($word) == 1) {
- $query->where($searchfield, "like", "%" . reset($word) . "%");
- } else {
- $query->where(function ($query) use ($word, $searchfield) {
- foreach ($word as $index => $item) {
- $query->whereOr(function ($query) use ($item, $searchfield) {
- $query->where($searchfield, "like", "%{$item}%");
- });
- }
- });
- }
- if ($custom && is_array($custom)) {
- foreach ($custom as $k => $v) {
- if (is_array($v) && 2 == count($v)) {
- $query->where($k, trim($v[0]), $v[1]);
- } else {
- $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);
- }
- $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);
-
- if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
- $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
-
- $primaryvalue = array_map(function ($value) {
- return '\'' . $value . '\'';
- }, $primaryvalue);
- $primaryvalue = implode(',', $primaryvalue);
- $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
- } else {
- $this->model->order($order);
- }
- $datalist = $this->model->where($where)
- ->page($page, $pagesize)
- ->select();
- foreach ($datalist as $index => $item) {
- unset($item['password'], $item['salt']);
- if ($this->selectpageFields == '*') {
- $result = [
- $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
- $field => isset($item[$field]) ? $item[$field] : '',
- ];
- } else {
- $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
- }
- $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
- $list[] = $result;
- }
- if ($istree && !$primaryvalue) {
- $tree = Tree::instance();
- $tree->init(collection($list)->toArray(), 'pid');
- $list = $tree->getTreeList($tree->getTreeArray(0), $field);
- if (!$ishtml) {
- foreach ($list as &$item) {
- $item = str_replace(' ', ' ', $item);
- }
- unset($item);
- }
- }
- }
-
- return json(['list' => $list, 'total' => $total]);
- }
-
- protected function token()
- {
- $token = $this->request->param('__token__');
-
- if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
- $this->error(__('Token verification error'), '', ['__token__' => $this->request->token()]);
- }
-
- $this->request->token();
- }
- }
|