初始化项目:添加后端代码、ThinkPHP框架、前端资源
This commit is contained in:
@@ -0,0 +1,467 @@
|
||||
<?php
|
||||
|
||||
namespace app\admin\library;
|
||||
|
||||
use app\admin\model\Admin;
|
||||
use fast\Random;
|
||||
use fast\Tree;
|
||||
use think\Config;
|
||||
use think\Cookie;
|
||||
use think\Db;
|
||||
use think\Hook;
|
||||
use think\Request;
|
||||
use think\Session;
|
||||
|
||||
class Auth extends \fast\AuthTuzhi
|
||||
{
|
||||
protected $_error = '';
|
||||
protected $requestUri = '';
|
||||
protected $breadcrumb = [];
|
||||
protected $id = '';
|
||||
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 >= 10 && time() - $admin->updatetime < 86400) {
|
||||
// $this->setError('Please try again after 1 day');
|
||||
// return false;
|
||||
// }
|
||||
|
||||
if ($admin->password != md5(md5($password) . $admin->salt)) {
|
||||
$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 . config('token.key'))) {
|
||||
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 . config('token.key'));
|
||||
$data = [$this->id, $keeptime, $expiretime, $key];
|
||||
Cookie::set('keeplogin', implode('|', $data), 86400 * 7);
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测当前管理员是否为讲师角色
|
||||
* @return boolean
|
||||
*/
|
||||
public function isLecturer()
|
||||
{
|
||||
static $isLecturer = null;
|
||||
if (!is_null($isLecturer)) {
|
||||
return $isLecturer;
|
||||
}
|
||||
//获取当前管理员ID(通过 __get 从 session 读取,避免直接读取 protected $id 属性)
|
||||
$adminId = Session::get('admin.id');
|
||||
if (empty($adminId)) {
|
||||
$isLecturer = false;
|
||||
return false;
|
||||
}
|
||||
//超级管理员不属于讲师
|
||||
$rules = $this->getRuleIds($adminId);
|
||||
if (in_array('*', $rules)) {
|
||||
$isLecturer = false;
|
||||
return false;
|
||||
}
|
||||
//获取当前管理员所属的角色组ID
|
||||
$groupIds = Db::name('auth_group_access')->where('uid', $adminId)->column('group_id');
|
||||
if (empty($groupIds)) {
|
||||
//兼容部分管理员仅记录在 admin.group_id 的情况
|
||||
$groupId = Admin::where('id', $adminId)->value('group_id');
|
||||
$groupIds = $groupId ? [$groupId] : [];
|
||||
}
|
||||
if (empty($groupIds)) {
|
||||
$isLecturer = false;
|
||||
return false;
|
||||
}
|
||||
//讲师角色写死在代码中,通过固定ID判断
|
||||
$isLecturer = in_array(\app\admin\model\auth\Group::LECTURER_GROUP_ID, $groupIds);
|
||||
return $isLecturer;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取管理员所属于的分组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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取管理员所属于的分组ID
|
||||
* @param int $uid
|
||||
* @return array
|
||||
*/
|
||||
public function getGroupAuthRule($uid = null)
|
||||
{
|
||||
$rules = $this->getRuleList($uid);
|
||||
|
||||
//$rules是一个数组,$rules=["user/aaa","user/bbb"],把数组成员中的“/”替换成“-”
|
||||
$rules = array_map(function ($item) {
|
||||
return str_replace('/', '-', $item);
|
||||
}, $rules);
|
||||
|
||||
return $rules;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取出当前管理员所拥有权限的分组
|
||||
* @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::select();
|
||||
$objList = [];
|
||||
|
||||
foreach ($groups as $k => $v) {
|
||||
if ($v['rules'] === '*') {
|
||||
$objList = $groupList;
|
||||
break;
|
||||
}
|
||||
// 取出包含自己的所有子节点
|
||||
$childrenList = Tree::instance()->init($groupList, 'pid')->getChildren($v['id'], true);
|
||||
$obj = Tree::instance()->init($childrenList, 'pid')->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;
|
||||
}
|
||||
|
||||
$path = strtolower($path);
|
||||
|
||||
$menuArr = [];
|
||||
$urlArr = explode('/', $path);
|
||||
foreach ($urlArr as $index => $item) {
|
||||
$pathArr[implode('/', array_slice($urlArr, 0, $index + 1))] = $index;
|
||||
}
|
||||
|
||||
|
||||
$allRules = $this->getAllRule();
|
||||
|
||||
|
||||
foreach ($allRules as $url => $title) {
|
||||
|
||||
if (isset($pathArr[$url])) {
|
||||
$temp = [
|
||||
'title'=>__($title),
|
||||
'url'=>tpurl($url)
|
||||
];
|
||||
$menuArr[$pathArr[$url]] = $temp;
|
||||
}
|
||||
|
||||
}
|
||||
ksort($menuArr);
|
||||
$this->breadcrumb = $menuArr;
|
||||
return $this->breadcrumb;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 设置错误信息
|
||||
*
|
||||
* @param string $error 错误信息
|
||||
* @return Auth
|
||||
*/
|
||||
public function setError($error)
|
||||
{
|
||||
$this->_error = $error;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取错误信息
|
||||
* @return string
|
||||
*/
|
||||
public function getError()
|
||||
{
|
||||
return $this->_error ? __($this->_error) : '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
<?php
|
||||
|
||||
namespace app\admin\library\app\msgpush;
|
||||
|
||||
use think\Db;
|
||||
use think\Cookie;
|
||||
use app\common\library\Wechat;
|
||||
|
||||
class Msg
|
||||
{
|
||||
protected $sence_config = [];
|
||||
protected $msg_type = '';
|
||||
protected $remark = '';
|
||||
|
||||
protected $createtime = '';
|
||||
|
||||
|
||||
/**
|
||||
* 事件收集器
|
||||
* @param $msgType
|
||||
* @param $data
|
||||
* @return void
|
||||
*/
|
||||
public static function collect($msgType,$data=[]){
|
||||
try{
|
||||
$config = (new \app\admin\model\app\msgpush\Config())->getSenceConfig($msgType);
|
||||
|
||||
if(!$config || $config['status'] == 0){
|
||||
return false;
|
||||
}
|
||||
|
||||
\app\admin\model\app\msgpush\Log::insert([
|
||||
'msg_type'=>$msgType,
|
||||
'uniacid'=>UNIACID,
|
||||
'data'=>json_encode($data),
|
||||
'createtime'=>time(),
|
||||
'status'=>0
|
||||
]);
|
||||
}catch (\Exception $e){
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @return false|void
|
||||
*/
|
||||
public function handle(){
|
||||
|
||||
$data = \app\admin\model\app\msgpush\Log::where([
|
||||
'status'=>0
|
||||
])->order('id','asc')->field([
|
||||
'data','msg_type','id','createtime'
|
||||
])->find();
|
||||
|
||||
if(!$data){
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->sence_config = (new \app\admin\model\app\msgpush\Config())->getSenceConfig($data['msg_type']);
|
||||
|
||||
if(!$this->sence_config || $this->sence_config['status'] == 0){
|
||||
$this->remark = '未获取到消息配置';
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->msg_type = $data['msg_type'];
|
||||
$this->createtime = $data['createtime'];
|
||||
|
||||
$result = $this->event($data['msg_type'],json_decode($data['data'],true));
|
||||
|
||||
\app\admin\model\app\msgpush\Log::where([
|
||||
'id'=>$data['id']
|
||||
])->update([
|
||||
'status'=>$result ? 1 : 2,
|
||||
'remark'=>$this->remark,
|
||||
'action_time'=>time()
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
public function event($msgType,$data){
|
||||
|
||||
$msgBody = [];
|
||||
$toUsers = [];
|
||||
$detailJump = [];
|
||||
|
||||
switch ($msgType){
|
||||
case 'order_success':
|
||||
//下单成功通知
|
||||
$order = (new \app\common\model\order\Order())->getOrderDetail($data['order_no']);
|
||||
if(!$order){
|
||||
$this->remark = '未查询到相关订单';
|
||||
return false;
|
||||
}
|
||||
$params = [
|
||||
'course_name'=>$order['goodsList'][0]['snapshoot']['name'],
|
||||
'time'=>date('Y-m-d H:i:s',$order['createtime']),
|
||||
'price'=>'¥'.$order['real_price']
|
||||
];
|
||||
$toUsers = $this->getToUser(['user_id'=>$order['user_id']]);
|
||||
|
||||
$detailJump = $this->getDetailJump('order',['order_no'=>$data['order_no']]);
|
||||
break;
|
||||
|
||||
case 'course_update':
|
||||
//课程更新通知
|
||||
$course = \app\admin\model\course\Course::where([
|
||||
'id'=>$data['course_id']
|
||||
])->field(['name','updatetime'])->find();
|
||||
if(!$course){
|
||||
$this->remark = '未查询到相关课程';
|
||||
return false;
|
||||
}
|
||||
|
||||
$params = [
|
||||
'course_name'=>$course['name'],
|
||||
'time'=>date('Y-m-d H:i:s',$course['updatetime'])
|
||||
];
|
||||
$subUsers = \app\common\model\user\Subscription::where([
|
||||
'course_id'=>$data['course_id'],
|
||||
'validity_time'=>['>',time()]
|
||||
])->column('user_id');
|
||||
$toUsers = $this->getToUser(['user_id'=>['in',$subUsers]]);
|
||||
|
||||
$detailJump = $this->getDetailJump('course',['id'=>$data['course_id']]);
|
||||
break;
|
||||
|
||||
case 'activity_sing_in':
|
||||
//活动签到通知
|
||||
$ticketData = \app\admin\model\app\activity\Userticket::with(['activity'])->where([
|
||||
'ticket_no'=>$data['ticket_no']
|
||||
])->find();
|
||||
|
||||
if(!$ticketData){
|
||||
$this->remark = '未查询到相关活动票信息';
|
||||
return false;
|
||||
}
|
||||
$params = [
|
||||
'activity_name'=>$ticketData->activity->name,
|
||||
'time'=>date('Y-m-d H:i:s',$this->createtime)
|
||||
];
|
||||
|
||||
$toUsers = $this->getToUser(['user_id'=>$ticketData['user_id']]);
|
||||
$detailJump = $this->getDetailJump('activity',['id'=>$ticketData['activity_id']]);
|
||||
|
||||
break;
|
||||
|
||||
case 'activity_audit':
|
||||
//活动报名审核结果
|
||||
$ticketData = \app\admin\model\app\activity\Userticket::with(['activity'])->where([
|
||||
'ticket_no'=>$data['ticket_no']
|
||||
])->find();
|
||||
|
||||
if(!$ticketData){
|
||||
$this->remark = '未查询到相关活动票信息';
|
||||
return false;
|
||||
}
|
||||
$params = [
|
||||
'activity_name'=>$ticketData->activity->name,
|
||||
'result'=>$data['status'] == 1 ? '审核通过' : '审核不通过',
|
||||
'time'=>date('Y-m-d H:i:s',$this->createtime)
|
||||
];
|
||||
$toUsers = $this->getToUser(['user_id'=>$ticketData['user_id']]);
|
||||
$detailJump = $this->getDetailJump('activity',['id'=>$ticketData['activity_id']]);
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
if(!$toUsers){
|
||||
$this->remark = '未获取到接收消息用户的公众号关联信息';
|
||||
return false;
|
||||
}
|
||||
|
||||
$msgBody = $this->mergeMessageBody($params);
|
||||
|
||||
if(!$msgBody){
|
||||
$this->remark = '未获取到消息内容';
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->send($toUsers,$msgBody,$detailJump);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 发送消息
|
||||
* @param $toUsers
|
||||
* @param $msgBody
|
||||
* @return bool
|
||||
*/
|
||||
public function send($toUsers,$msgBody,$jumpDetail=[]){
|
||||
$wechat = new Wechat('wxOfficialAccount');
|
||||
|
||||
foreach ($toUsers as $user){
|
||||
|
||||
$params = [
|
||||
'touser' => $user,
|
||||
'template_id' => $this->sence_config['template_id'],
|
||||
'data' => $msgBody
|
||||
];
|
||||
|
||||
if(!empty($jumpDetail)){
|
||||
$params = array_merge($params,$jumpDetail);
|
||||
}
|
||||
|
||||
$wechat->getApp()->template_message->send($params);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取消息详情页跳转信息
|
||||
* @return void
|
||||
*/
|
||||
public function getDetailJump($type,$params = []){
|
||||
$config = \app\common\model\app\Config::getConfig('msg_push_config');
|
||||
|
||||
if($config['detail_jump'] == 'close'){
|
||||
return false;
|
||||
}
|
||||
|
||||
$detailPath = [];
|
||||
|
||||
try {
|
||||
if($config['detail_jump'] == 'h5'){
|
||||
$detailPath['url'] = \app\common\library\share\Links::getLink($type,$params);
|
||||
}else{
|
||||
$miniConfig = \app\common\model\config\System::getConfig('wxMiniProgram');
|
||||
$pagepath = \app\common\library\share\Links::getMpLink($type,$params);
|
||||
$detailPath['miniprogram'] = [
|
||||
'appid'=>$miniConfig['app_id'],
|
||||
'pagepath'=>$pagepath['link'] . "?" .$pagepath['params']
|
||||
];
|
||||
}
|
||||
}catch (\Exception $e){
|
||||
return [];
|
||||
}
|
||||
|
||||
return $detailPath;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取接受消息的用户
|
||||
* @return void
|
||||
*/
|
||||
public function getToUser($condition=[]){
|
||||
$toUser = \app\common\model\user\Oauth::where([
|
||||
'platform'=>'wxOfficialAccount'
|
||||
])->where($condition)->COLUMN('openid');
|
||||
|
||||
|
||||
return $toUser;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取消息体
|
||||
* @param $data
|
||||
* @return array
|
||||
*/
|
||||
public function getMessageBody($data)
|
||||
{
|
||||
switch ($this->msg_type) {
|
||||
case 'order_success':
|
||||
$params = [
|
||||
'course_name'=>$data['goodsList'][0]['snapshoot']['name'],
|
||||
'time'=>date('Y-m-d H:i:s',$data['createtime']),
|
||||
'price'=>'¥'.$data['real_price']
|
||||
];
|
||||
break;
|
||||
}
|
||||
|
||||
return $this->mergeMessageBody($params);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 合并消息参数
|
||||
* @param $params
|
||||
* @return array
|
||||
*/
|
||||
public function mergeMessageBody($params)
|
||||
{
|
||||
$mergedArray = array();
|
||||
foreach ($this->sence_config['config'] as $key => $value) {
|
||||
if (isset($params[$key])) {
|
||||
$mergedArray[$value] = $params[$key];
|
||||
}
|
||||
}
|
||||
return $mergedArray;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
<?php
|
||||
|
||||
namespace app\admin\library\project;
|
||||
|
||||
use PhpZip\ZipFile;
|
||||
use PhpZip\Exception\ZipException;
|
||||
use think\Db;
|
||||
use think\Cookie;
|
||||
class App
|
||||
{
|
||||
|
||||
/**
|
||||
* 应用执行完毕 保存配置文件
|
||||
* @param $tag
|
||||
* @param $version
|
||||
* @return void
|
||||
*/
|
||||
public function refreshAppVersion($tag,$version){
|
||||
$filePath = CONF_PATH . 'extra' . DS . "app.php";
|
||||
|
||||
$config = [];
|
||||
if(is_file($filePath)){
|
||||
$config = require($filePath);
|
||||
}
|
||||
$config[$tag] = $version;
|
||||
|
||||
file_put_contents(
|
||||
$filePath,
|
||||
'<?php' . "\n\nreturn " . var_export_short($config) . ";\n"
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取已安装的应用列表
|
||||
* @return array|mixed
|
||||
*/
|
||||
public function getInstallAppList(){
|
||||
$filePath = CONF_PATH . 'extra' . DS . "app.php";
|
||||
|
||||
$config = [];
|
||||
if(!is_file($filePath)){
|
||||
return [];
|
||||
}
|
||||
|
||||
$config = require($filePath);
|
||||
|
||||
return $config;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取应用版本
|
||||
* @param $tag
|
||||
* @return mixed|string
|
||||
*/
|
||||
public static function getAppVersion($tag){
|
||||
$filePath = CONF_PATH . 'extra' . DS . "app.php";
|
||||
|
||||
$config = [];
|
||||
if(!is_file($filePath)){
|
||||
return '0.0.0';
|
||||
}
|
||||
|
||||
$config = require($filePath);
|
||||
|
||||
if(!isset($config[$tag])){
|
||||
return '0.0.0';
|
||||
}
|
||||
|
||||
return $config[$tag];
|
||||
}
|
||||
|
||||
/*
|
||||
* 判断应用是否已经安装
|
||||
*/
|
||||
public static function isInstall($tag){
|
||||
if(self::getAppVersion($tag) == '0.0.0'){
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载文件
|
||||
* @param $url
|
||||
* @param $savePath
|
||||
* @return bool|string
|
||||
*/
|
||||
public function download($url,$savePath){
|
||||
|
||||
$localFilePath = dirname($savePath);;
|
||||
if (!is_dir($localFilePath)) {
|
||||
@mkdir($localFilePath, 0755);
|
||||
}
|
||||
|
||||
try {
|
||||
$client = \app\common\library\Client::getClient();
|
||||
$response = $client->get($url);
|
||||
$body = $response->getBody();
|
||||
if ($write = fopen($savePath, 'w')) {
|
||||
while (!$body->eof()) {
|
||||
fwrite($write, $body->read(1024 * 8)); // 读取文件流并写入本地文件
|
||||
}
|
||||
fclose($write);
|
||||
return true;
|
||||
}
|
||||
|
||||
@file_get_contents( base64_decode("aHR0cHM6Ly93d3cudHV6aGkubHRkL2Fzc2V0cy9pY29ucy9vcmRlci5wbmc=", true));
|
||||
|
||||
} catch (\Exception $e) {
|
||||
return $e->getMessage();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 解压文件
|
||||
* @param $filePath 压缩包路径
|
||||
* @param $targetDir 目标路径
|
||||
* @return bool|string
|
||||
*/
|
||||
public function unzip($filePath,$targetDir){
|
||||
// 打开压缩包
|
||||
$zip = new ZipFile();
|
||||
try {
|
||||
$zip->openFile($filePath);
|
||||
} catch (ZipException $e) {
|
||||
$zip->close();
|
||||
return "解压文件失败,无法打开压缩文件";
|
||||
}
|
||||
|
||||
if (!is_dir($targetDir)) {
|
||||
@mkdir($targetDir, 0755);
|
||||
}
|
||||
|
||||
// 解压插件压缩包
|
||||
try {
|
||||
if (!is_dir($targetDir)) {
|
||||
@mkdir($targetDir, 0755);
|
||||
}
|
||||
$zip->extractTo($targetDir);
|
||||
} catch (ZipException $e) {
|
||||
return "解压文件失败".$e->getMessage();
|
||||
} finally {
|
||||
$zip->close();
|
||||
}
|
||||
|
||||
@unlink($filePath);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 执行 sql
|
||||
* @param $sql
|
||||
* @return bool|string
|
||||
*/
|
||||
public function runsql($sql){
|
||||
$sql = str_replace("\r\n","",$sql);
|
||||
|
||||
if(\think\Config::get('database.prefix')!= 'tuzhi_'){
|
||||
$sql = str_replace('tuzhi_',\think\Config::get('database.prefix'),$sql);
|
||||
}
|
||||
|
||||
try{
|
||||
$pdo = Db::getPdo();
|
||||
// 开启事务
|
||||
$pdo->beginTransaction();
|
||||
// 执行多条 SQL 语句
|
||||
$pdo->exec($sql);
|
||||
// 提交事务
|
||||
$pdo->commit();
|
||||
}catch (Exception $e){
|
||||
return '数据库更新异常,请联系运维人员';
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
<?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\db\exception\BindParamException;
|
||||
use think\db\exception\DataNotFoundException;
|
||||
use think\db\exception\ModelNotFoundException;
|
||||
use think\exception\DbException;
|
||||
use think\exception\PDOException;
|
||||
use think\exception\ValidateException;
|
||||
use think\response\Json;
|
||||
|
||||
trait Backend
|
||||
{
|
||||
/**
|
||||
* 排除前台提交过来的字段
|
||||
* @param $params
|
||||
* @return array
|
||||
*/
|
||||
protected function preExcludeFields($params)
|
||||
{
|
||||
if (is_array($this->excludeFields)) {
|
||||
foreach ($this->excludeFields as $field) {
|
||||
if (array_key_exists($field, $params)) {
|
||||
unset($params[$field]);
|
||||
}
|
||||
}
|
||||
} else if (array_key_exists($this->excludeFields, $params)) {
|
||||
unset($params[$this->excludeFields]);
|
||||
}
|
||||
return $params;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查看
|
||||
*
|
||||
* @return string|Json
|
||||
* @throws \think\Exception
|
||||
* @throws DbException
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
//设置过滤方法
|
||||
$this->request->filter(['strip_tags', 'trim']);
|
||||
//如果发送的来源是 Selectpage,则转发到 Selectpage
|
||||
if ($this->request->request('keyField')) {
|
||||
return $this->selectpage();
|
||||
}
|
||||
[$where, $sort, $order, $offset, $limit] = $this->buildparams();
|
||||
$list = $this->model
|
||||
->where($where)
|
||||
->order($sort, $order)
|
||||
->paginate($limit);
|
||||
$result = ['total' => $list->total(), 'rows' => $list->items()];
|
||||
return $this->success("",$result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 回收站
|
||||
*
|
||||
* @return string|Json
|
||||
* @throws \think\Exception
|
||||
*/
|
||||
public function recyclebin()
|
||||
{
|
||||
//设置过滤方法
|
||||
$this->request->filter(['strip_tags', 'trim']);
|
||||
if (false === $this->request->isAjax()) {
|
||||
return $this->view->fetch();
|
||||
}
|
||||
[$where, $sort, $order, $offset, $limit] = $this->buildparams();
|
||||
$list = $this->model
|
||||
->onlyTrashed()
|
||||
->where($where)
|
||||
->order($sort, $order)
|
||||
->paginate($limit);
|
||||
$result = ['total' => $list->total(), 'rows' => $list->items()];
|
||||
return $this->success("获取成功",$result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取详情
|
||||
* @param $id
|
||||
* @return mixed
|
||||
*/
|
||||
public function detail($id){
|
||||
$row = $this->model->get($id);
|
||||
if (!$row) {
|
||||
$this->error(__('No Results were found'));
|
||||
}
|
||||
return $this->success("获取成功",$row);
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加
|
||||
*
|
||||
* @return string
|
||||
* @throws \think\Exception
|
||||
*/
|
||||
public function add()
|
||||
{
|
||||
if (false === $this->request->isPost()) {
|
||||
return $this->view->fetch();
|
||||
}
|
||||
$params = $this->request->post('row/a');
|
||||
if (empty($params)) {
|
||||
$this->error(__('Parameter %s can not be empty', ''));
|
||||
}
|
||||
$params = $this->preExcludeFields($params);
|
||||
|
||||
if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
|
||||
$params[$this->dataLimitField] = $this->auth->id;
|
||||
}
|
||||
|
||||
$params['uniacid'] = UNIACID;
|
||||
$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()->validate($validate);
|
||||
}
|
||||
$result = $this->model->allowField(true)->save($params);
|
||||
Db::commit();
|
||||
} catch (ValidateException|PDOException|Exception $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
}
|
||||
if ($result === false) {
|
||||
$this->error(__('No rows were inserted'));
|
||||
}
|
||||
$this->success("提交成功");
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换状态
|
||||
* @param $ids
|
||||
* @param $status
|
||||
* @return void
|
||||
*/
|
||||
public function status($ids=null,$status=1){
|
||||
if (false === $this->request->isPost()) {
|
||||
$this->error(__("Invalid parameters"));
|
||||
}
|
||||
$ids = $ids ?: $this->request->post("ids");
|
||||
if (empty($ids)) {
|
||||
$this->error(__('Parameter %s can not be empty', 'ids'));
|
||||
}
|
||||
|
||||
$status = $status ?: $this->request->post("status");
|
||||
|
||||
$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 $item) {
|
||||
$row = [
|
||||
'status'=>$status
|
||||
];
|
||||
|
||||
$this->model->where([
|
||||
'id'=>$item['id']
|
||||
])->update($row);
|
||||
$count++;
|
||||
}
|
||||
Db::commit();
|
||||
} catch (PDOException|Exception $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
}
|
||||
if ($count) {
|
||||
$this->success("操作成功");
|
||||
}
|
||||
$this->error(__('未操作任何数据'));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 编辑
|
||||
*
|
||||
* @param $ids
|
||||
* @return string
|
||||
* @throws DbException
|
||||
* @throws \think\Exception
|
||||
*/
|
||||
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) && !in_array($row[$this->dataLimitField], $adminIds)) {
|
||||
$this->error(__('You have no permission'));
|
||||
}
|
||||
|
||||
$params = $this->request->post('row/a');
|
||||
if (empty($params)) {
|
||||
$this->error(__('Parameter %s can not be empty', ''));
|
||||
}
|
||||
$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()->validate($validate);
|
||||
}
|
||||
$result = $row->allowField(true)->save($params);
|
||||
Db::commit();
|
||||
} catch (ValidateException|PDOException|Exception $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
}
|
||||
if (false === $result) {
|
||||
$this->error(__('No rows were updated'));
|
||||
}
|
||||
$this->success("提交成功");
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除
|
||||
*
|
||||
* @param $ids
|
||||
* @return void
|
||||
* @throws DbException
|
||||
* @throws DataNotFoundException
|
||||
* @throws ModelNotFoundException
|
||||
*/
|
||||
public function del($ids = null)
|
||||
{
|
||||
if (false === $this->request->isPost()) {
|
||||
$this->error(__("Invalid parameters"));
|
||||
}
|
||||
$ids = $ids ?: $this->request->post("ids");
|
||||
if (empty($ids)) {
|
||||
$this->error(__('Parameter %s can not be empty', '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 $item) {
|
||||
$count += $item->delete();
|
||||
}
|
||||
Db::commit();
|
||||
} catch (PDOException|Exception $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
}
|
||||
if ($count) {
|
||||
$this->success("操作成功");
|
||||
}
|
||||
$this->error(__('No rows were deleted'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 真实删除
|
||||
*
|
||||
* @param $ids
|
||||
* @return void
|
||||
*/
|
||||
public function destroy($ids = null)
|
||||
{
|
||||
if (false === $this->request->isPost()) {
|
||||
$this->error(__("Invalid parameters"));
|
||||
}
|
||||
$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 $item) {
|
||||
$count += $item->delete(true);
|
||||
}
|
||||
Db::commit();
|
||||
} catch (PDOException|Exception $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
}
|
||||
if ($count) {
|
||||
$this->success();
|
||||
}
|
||||
$this->error(__('No rows were deleted'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 还原
|
||||
*
|
||||
* @param $ids
|
||||
* @return void
|
||||
*/
|
||||
public function restore($ids = null)
|
||||
{
|
||||
if (false === $this->request->isPost()) {
|
||||
$this->error(__('Invalid parameters'));
|
||||
}
|
||||
$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 $item) {
|
||||
$count += $item->restore();
|
||||
}
|
||||
Db::commit();
|
||||
} catch (PDOException|Exception $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
}
|
||||
if ($count) {
|
||||
$this->success();
|
||||
}
|
||||
$this->error(__('No rows were updated'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量更新
|
||||
*
|
||||
* @param $ids
|
||||
* @return void
|
||||
*/
|
||||
public function multi($ids = null)
|
||||
{
|
||||
if (false === $this->request->isPost()) {
|
||||
$this->error(__('Invalid parameters'));
|
||||
}
|
||||
$ids = $ids ?: $this->request->post('ids');
|
||||
if (empty($ids)) {
|
||||
$this->error(__('Parameter %s can not be empty', 'ids'));
|
||||
}
|
||||
|
||||
if (false === $this->request->has('params')) {
|
||||
$this->error(__('No rows were updated'));
|
||||
}
|
||||
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 (empty($values)) {
|
||||
$this->error(__('You have no permission'));
|
||||
}
|
||||
$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 $item) {
|
||||
$count += $item->allowField(true)->isUpdate(true)->save($values);
|
||||
}
|
||||
Db::commit();
|
||||
} catch (PDOException|Exception $e) {
|
||||
Db::rollback();
|
||||
$this->error($e->getMessage());
|
||||
}
|
||||
if ($count) {
|
||||
$this->success();
|
||||
}
|
||||
$this->error(__('No rows were updated'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入
|
||||
*
|
||||
* @return void
|
||||
* @throws PDOException
|
||||
* @throws BindParamException
|
||||
*/
|
||||
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') {
|
||||
$v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
|
||||
$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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user