This commit is contained in:
yyh931018@qq.com
2022-09-08 15:32:32 +08:00
commit 1b0c8f4196
4714 changed files with 974427 additions and 0 deletions

View File

@@ -0,0 +1,71 @@
<?php
namespace app\admin\controller\general;
use app\common\controller\Backend;
/**
* 地区管理
*
* @icon fa fa-circle-o
*/
class Area extends Backend
{
/**
* Area模型对象
* @var \app\common\model\Area
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\common\model\Area;
}
/**
* 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
* 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
* 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
*/
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = false;
//设置过滤方法
$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(['pid'=>655])
->where($where)
->order($sort, $order)
->paginate($limit);
foreach ($list as $row) {
$row->visible(['id','name','encoded']);
}
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
return $this->view->fetch();
}
}

View File

@@ -0,0 +1,160 @@
<?php
namespace app\admin\controller\general;
use app\common\controller\Backend;
/**
* 附件管理
*
* @icon fa fa-circle-o
* @remark 主要用于管理上传到服务器或第三方存储的数据
*/
class Attachment extends Backend
{
/**
* @var \app\common\model\Attachment
*/
protected $model = null;
protected $searchFields = 'id,filename,url';
protected $noNeedRight = ['classify'];
public function _initialize()
{
parent::_initialize();
$this->model = model('Attachment');
$this->view->assign("mimetypeList", \app\common\model\Attachment::getMimetypeList());
$this->view->assign("categoryList", \app\common\model\Attachment::getCategoryList());
$this->assignconfig("categoryList", \app\common\model\Attachment::getCategoryList());
}
/**
* 查看
*/
public function index()
{
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
$mimetypeQuery = [];
$filter = $this->request->request('filter');
$filterArr = (array)json_decode($filter, true);
if (isset($filterArr['category']) && $filterArr['category'] == 'unclassed') {
$filterArr['category'] = ',unclassed';
$this->request->get(['filter' => json_encode(array_diff_key($filterArr, ['category' => '']))]);
}
if (isset($filterArr['mimetype']) && preg_match("/(\/|\,|\*)/", $filterArr['mimetype'])) {
$mimetype = $filterArr['mimetype'];
$filterArr = array_diff_key($filterArr, ['mimetype' => '']);
$mimetypeQuery = function ($query) use ($mimetype) {
$mimetypeArr = array_filter(explode(',', $mimetype));
foreach ($mimetypeArr as $index => $item) {
$query->whereOr('mimetype', 'like', '%' . str_replace("/*", "/", $item) . '%');
}
};
}
$this->request->get(['filter' => json_encode($filterArr)]);
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = $this->model
->where($mimetypeQuery)
->where($where)
->order($sort, $order)
->paginate($limit);
$cdnurl = preg_replace("/\/(\w+)\.php$/i", '', $this->request->root());
foreach ($list as $k => &$v) {
$v['fullurl'] = ($v['storage'] == 'local' ? $cdnurl : $this->view->config['upload']['cdnurl']) . $v['url'];
}
unset($v);
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
return $this->view->fetch();
}
/**
* 选择附件
*/
public function select()
{
if ($this->request->isAjax()) {
return $this->index();
}
$mimetype = $this->request->get('mimetype', '');
$mimetype = substr($mimetype, -1) === '/' ? $mimetype . '*' : $mimetype;
$this->view->assign('mimetype', $mimetype);
return $this->view->fetch();
}
/**
* 添加
*/
public function add()
{
if ($this->request->isAjax()) {
$this->error();
}
return $this->view->fetch();
}
/**
* 删除附件
* @param array $ids
*/
public function del($ids = "")
{
if (!$this->request->isPost()) {
$this->error(__("Invalid parameters"));
}
$ids = $ids ? $ids : $this->request->post("ids");
if ($ids) {
\think\Hook::add('upload_delete', function ($params) {
if ($params['storage'] == 'local') {
$attachmentFile = ROOT_PATH . '/public' . $params['url'];
if (is_file($attachmentFile)) {
@unlink($attachmentFile);
}
}
});
$attachmentlist = $this->model->where('id', 'in', $ids)->select();
foreach ($attachmentlist as $attachment) {
\think\Hook::listen("upload_delete", $attachment);
$attachment->delete();
}
$this->success();
}
$this->error(__('Parameter %s can not be empty', 'ids'));
}
/**
* 归类
*/
public function classify()
{
if (!$this->auth->check('general/attachment/edit')) {
\think\Hook::listen('admin_nopermission', $this);
$this->error(__('You have no permission'), '');
}
if (!$this->request->isPost()) {
$this->error(__("Invalid parameters"));
}
$category = $this->request->post('category', '');
$ids = $this->request->post('ids');
if (!$ids) {
$this->error(__('Parameter %s can not be empty', 'ids'));
}
$categoryList = \app\common\model\Attachment::getCategoryList();
if ($category && !isset($categoryList[$category])) {
$this->error(__('Category not found'));
}
$category = $category == 'unclassed' ? '' : $category;
\app\common\model\Attachment::where('id', 'in', $ids)->update(['category' => $category]);
$this->success();
}
}

View File

@@ -0,0 +1,343 @@
<?php
namespace app\admin\controller\general;
use app\common\controller\Backend;
use app\common\library\Email;
use app\common\model\Config as ConfigModel;
use think\Cache;
use think\Db;
use think\Exception;
use think\Validate;
/**
* 系统配置
*
* @icon fa fa-cogs
* @remark 可以在此增改系统的变量和分组,也可以自定义分组和变量,如果需要删除请从数据库中删除
*/
class Config extends Backend
{
/**
* @var \app\common\model\Config
*/
protected $model = null;
protected $noNeedRight = ['check', 'rulelist', 'selectpage', 'get_fields_list'];
public function _initialize()
{
parent::_initialize();
// $this->model = model('Config');
$this->model = new ConfigModel;
ConfigModel::event('before_write', function ($row) {
if (isset($row['name']) && $row['name'] == 'name' && preg_match("/fast" . "admin/i", $row['value'])) {
throw new Exception(__("Site name incorrect"));
}
});
}
/**
* 查看
*/
public function index()
{
$siteList = [];
$groupList = ConfigModel::getGroupList();
foreach ($groupList as $k => $v) {
$siteList[$k]['name'] = $k;
$siteList[$k]['title'] = $v;
$siteList[$k]['list'] = [];
}
foreach ($this->model->all() as $k => $v) {
if (!isset($siteList[$v['group']])) {
continue;
}
$value = $v->toArray();
$value['title'] = __($value['title']);
if (in_array($value['type'], ['select', 'selects', 'checkbox', 'radio'])) {
$value['value'] = explode(',', $value['value']);
}
$value['content'] = json_decode($value['content'], true);
if (in_array($value['name'], ['categorytype', 'configgroup', 'attachmentcategory'])) {
$dictValue = (array)json_decode($value['value'], true);
foreach ($dictValue as $index => &$item) {
$item = __($item);
}
unset($item);
$value['value'] = json_encode($dictValue, JSON_UNESCAPED_UNICODE);
}
$value['tip'] = htmlspecialchars($value['tip']);
if ($value['name'] == 'cdnurl') {
//cdnurl不支持在线修改
continue;
}
$siteList[$v['group']]['list'][] = $value;
}
$index = 0;
foreach ($siteList as $k => &$v) {
$v['active'] = !$index ? true : false;
$index++;
}
$this->view->assign('siteList', $siteList);
$this->view->assign('typeList', ConfigModel::getTypeList());
$this->view->assign('ruleList', ConfigModel::getRegexList());
$this->view->assign('groupList', ConfigModel::getGroupList());
return $this->view->fetch();
}
/**
* 添加
*/
public function add()
{
if (!config('app_debug')) {
$this->error(__('Only work at development environment'));
}
if ($this->request->isPost()) {
$this->token();
$params = $this->request->post("row/a", [], 'trim');
if ($params) {
foreach ($params as $k => &$v) {
$v = is_array($v) && $k !== 'setting' ? implode(',', $v) : $v;
}
if (in_array($params['type'], ['select', 'selects', 'checkbox', 'radio', 'array'])) {
$params['content'] = json_encode(ConfigModel::decode($params['content']), JSON_UNESCAPED_UNICODE);
} else {
$params['content'] = '';
}
try {
$result = $this->model->create($params);
} catch (Exception $e) {
$this->error($e->getMessage());
}
if ($result !== false) {
try {
ConfigModel::refreshFile();
} catch (Exception $e) {
$this->error($e->getMessage());
}
$this->success();
} else {
$this->error($this->model->getError());
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
return $this->view->fetch();
}
/**
* 编辑
* @param null $ids
*/
public function edit($ids = null)
{
if ($this->request->isPost()) {
$this->token();
$row = $this->request->post("row/a", [], 'trim');
if ($row) {
$configList = [];
foreach ($this->model->all() as $v) {
if (isset($row[$v['name']])) {
$value = $row[$v['name']];
if (is_array($value) && isset($value['field'])) {
$value = json_encode(ConfigModel::getArrayData($value), JSON_UNESCAPED_UNICODE);
} else {
$value = is_array($value) ? implode(',', $value) : $value;
}
$v['value'] = $value;
$configList[] = $v->toArray();
}
}
// //清除数据
// $stu = $configList[7]['value'];
// $stu_back = db('config')->where('id',19)->find();
// if($stu == 1 && $stu_back['value'] == 0){
// //执行删除
// db('student')->delete();
// }
// $tea = $configList[8]['value'];
// $tea_back = db('config')->where('id',20)->find();
// if($stu == 1 && $tea_back['value'] == 0){
// //执行删除
// db('student')->delete();
// }
// $stu = $configList[7]['value'];
// $stu_back = db('config')->where('id',19)->find();
// if($stu == 1 && $stu_back['value'] == 0){
// //执行删除
// db('student')->delete();
// }
// $stu = $configList[7]['value'];
// $stu_back = db('config')->where('id',19)->find();
// if($stu == 1 && $stu_back['value'] == 0){
// //执行删除
// db('student')->delete();
// }
try {
$this->model->allowField(true)->saveAll($configList);
} catch (Exception $e) {
$this->error($e->getMessage());
}
try {
ConfigModel::refreshFile();
} catch (Exception $e) {
$this->error($e->getMessage());
}
$this->success();
}
$this->error(__('Parameter %s can not be empty', ''));
}
}
/**
* 删除
* @param string $ids
*/
public function del($ids = "")
{
if (!config('app_debug')) {
$this->error(__('Only work at development environment'));
}
$name = $this->request->post('name');
$config = ConfigModel::getByName($name);
if ($name && $config) {
try {
$config->delete();
ConfigModel::refreshFile();
} catch (Exception $e) {
$this->error($e->getMessage());
}
$this->success();
} else {
$this->error(__('Invalid parameters'));
}
}
/**
* 检测配置项是否存在
* @internal
*/
public function check()
{
$params = $this->request->post("row/a");
if ($params) {
$config = $this->model->get($params);
if (!$config) {
$this->success();
} else {
$this->error(__('Name already exist'));
}
} else {
$this->error(__('Invalid parameters'));
}
}
/**
* 规则列表
* @internal
*/
public function rulelist()
{
//主键
$primarykey = $this->request->request("keyField");
//主键值
$keyValue = $this->request->request("keyValue", "");
$keyValueArr = array_filter(explode(',', $keyValue));
$regexList = \app\common\model\Config::getRegexList();
$list = [];
foreach ($regexList as $k => $v) {
if ($keyValueArr) {
if (in_array($k, $keyValueArr)) {
$list[] = ['id' => $k, 'name' => $v];
}
} else {
$list[] = ['id' => $k, 'name' => $v];
}
}
return json(['list' => $list]);
}
/**
* 发送测试邮件
* @internal
*/
public function emailtest()
{
$row = $this->request->post('row/a');
$receiver = $this->request->post("receiver");
if ($receiver) {
if (!Validate::is($receiver, "email")) {
$this->error(__('Please input correct email'));
}
\think\Config::set('site', array_merge(\think\Config::get('site'), $row));
$email = new Email;
$result = $email
->to($receiver)
->subject(__("This is a test mail", config('site.name')))
->message('<div style="min-height:550px; padding: 100px 55px 200px;">' . __('This is a test mail content', config('site.name')) . '</div>')
->send();
if ($result) {
$this->success();
} else {
$this->error($email->getError());
}
} else {
$this->error(__('Invalid parameters'));
}
}
public function selectpage()
{
$id = $this->request->get("id/d");
$config = \app\common\model\Config::get($id);
if (!$config) {
$this->error(__('Invalid parameters'));
}
$setting = $config['setting'];
//自定义条件
$custom = isset($setting['conditions']) ? (array)json_decode($setting['conditions'], true) : [];
$custom = array_filter($custom);
$this->request->request(['showField' => $setting['field'], 'keyField' => $setting['primarykey'], 'custom' => $custom, 'searchField' => [$setting['field'], $setting['primarykey']]]);
$this->model = \think\Db::connect()->setTable($setting['table']);
return parent::selectpage();
}
/**
* 获取表列表
* @internal
*/
public function get_table_list()
{
$tableList = [];
$dbname = \think\Config::get('database.database');
$tableList = \think\Db::query("SELECT `TABLE_NAME` AS `name`,`TABLE_COMMENT` AS `title` FROM `information_schema`.`TABLES` where `TABLE_SCHEMA` = '{$dbname}';");
$this->success('', null, ['tableList' => $tableList]);
}
/**
* 获取表字段列表
* @internal
*/
public function get_fields_list()
{
$table = $this->request->request('table');
$dbname = \think\Config::get('database.database');
//从数据库中获取表字段信息
$sql = "SELECT `COLUMN_NAME` AS `name`,`COLUMN_COMMENT` AS `title`,`DATA_TYPE` AS `type` FROM `information_schema`.`columns` WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION";
//加载主表的列
$fieldList = Db::query($sql, [$dbname, $table]);
$this->success("", null, ['fieldList' => $fieldList]);
}
}

View File

@@ -0,0 +1,88 @@
<?php
namespace app\admin\controller\general;
use app\common\controller\Backend;
use think\Db;
/**
* 班级管理
*
* @icon fa fa-circle-o
*/
class Grade extends Backend
{
/**
* Grade模型对象
* @var \app\admin\model\Grade
*/
protected $model = null;
protected $selectpageFields = 'id,grade,class,name';
//无需要权限判断的方法
protected $noNeedRight = ['selectpage'];
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\Grade;
$this->view->assign("statusList", $this->model->getStatusList());
$this->view->assign("isSuperAdmin", $this->auth->isSuperAdmin());
$this->view->assign("group_id", $this->auth->getGroupIds()[0]);
}
/**
* 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
* 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
* 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
*/
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
//设置过滤方法
$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();
$wheres = [];
if(!$this->auth->isSuperAdmin()){
$groupIds = $this->auth->getGroupIds();
$wheres = ['group_id'=>['in',$groupIds]];
}
$list = $this->model
->with(['groups'])
->where($where)
->where($wheres)
->order($sort, $order)
->paginate($limit);
foreach ($list as $row) {
$row->getRelation('groups')->visible(['name']);
}
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
$this->assignconfig("isSuperAdmin", $this->auth->isSuperAdmin());
return $this->view->fetch();
}
public function selectpage(){
return parent::selectpage();
}
}

View File

@@ -0,0 +1,220 @@
<?php
namespace app\admin\controller\general;
use app\admin\model\AuthGroup;
use app\admin\model\Student;
use app\common\controller\Backend;
use app\common\model\Area;
use think\Db;
/**
* 编号管理
*
* @icon fa fa-circle-o
*/
class Identifier extends Backend
{
/**
* Identifier模型对象
* @var \app\admin\model\Identifier
*/
protected $model = null;
//无需要权限判断的方法
protected $noNeedRight = ['create_id'];
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\Identifier;
$this->view->assign("statusList", $this->model->getStatusList());
}
/**
* 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
* 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
* 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
*/
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
//设置过滤方法
$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();
$wheres = [];
if(!$this->auth->isSuperAdmin()){
$groupIds = $this->auth->getGroupIds();
$wheres = ['group_id'=>['in',$groupIds]];
}
$list = $this->model
->with(['groups'])
->where($where)
->where($wheres)
->order($sort, $order)
->paginate($limit);
foreach ($list as $row) {
$row->getRelation('groups')->visible(['name']);
}
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
$this->assignconfig("isSuperAdmin", $this->auth->isSuperAdmin());
return $this->view->fetch();
}
/**
* 添加
*
* @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;
}
//生成编号
//判断长度和数量
$length = $params['length'] - strlen($params['prefix']);
if(10**$length < $params['number'] + $params['first']){
$this->error('编号长度不足');
}
$data = [];
$suffix = sprintf("%'0{$params['length']}s",$params['first']);
for($i=0;$i<$params['number'];$i++){
$identifier = strtoupper($params['prefix']).$suffix;
//查询是否存在
$exist = $this->model->where('identifier', $identifier)->find();
if($exist){
$this->error("编号 $identifier 重复");
}
$data[] = [
'group_id' => $params['group_id'],
'identifier' => $identifier,
];
$suffix = sprintf("%'0{$params['length']}s",++$suffix);
}
$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)->saveAll($data);
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
* @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'));
}
if (false === $this->request->isPost()) {
$this->view->assign('row', $row);
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);
//查询是否存在
$exist = $this->model->where('identifier', $params['identifier'])->find();
if($exist && $exist['id'] != $params['id']){
$this->error("编号 {$params['identifier']} 重复");
}
$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();
}
/**
* 根据学校ID生成学生编号
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public function create_id(){
$group_id = $this->request->post("group_id");
$info = AuthGroup::where('id', $group_id)->find();
while ($info['level'] > 2){
$info = AuthGroup::where('id', $info['pid'])->find();
}
//地区编号
$area_encoded = Area::where('id', $info['city'])->value('encoded');
//当前学校学生最大编号
$student_number = Student::where('group_id', $group_id)->value('CONVERT(MAX(RIGHT(`identifier`,4)),UNSIGNED)');
$student_code = $area_encoded.sprintf("%'04s", $group_id).sprintf("%'04s", $student_number+1);
$this->success('', '', $student_code);
}
}

View File

@@ -0,0 +1,83 @@
<?php
namespace app\admin\controller\general;
use app\admin\model\Admin;
use app\common\controller\Backend;
use fast\Random;
use think\Session;
use think\Validate;
/**
* 个人配置
*
* @icon fa fa-user
*/
class Profile extends Backend
{
protected $searchFields = 'id,title';
/**
* 查看
*/
public function index()
{
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
$this->model = model('AdminLog');
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = $this->model
->where($where)
->where('admin_id', $this->auth->id)
->order($sort, $order)
->paginate($limit);
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
return $this->view->fetch();
}
/**
* 更新个人信息
*/
public function update()
{
if ($this->request->isPost()) {
$this->token();
$params = $this->request->post("row/a");
$params = array_filter(array_intersect_key(
$params,
array_flip(array('email', 'nickname', 'password', 'avatar'))
));
unset($v);
/*if (!Validate::is($params['email'], "email")) {
$this->error(__("Please input correct email"));
}*/
if (isset($params['password'])) {
if (!Validate::is($params['password'], "/^[\S]{6,30}$/")) {
$this->error(__("Please input correct password"));
}
$params['salt'] = Random::alnum();
$params['password'] = md5(md5($params['password']) . $params['salt']);
}
/*$exist = Admin::where('email', $params['email'])->where('id', '<>', $this->auth->id)->find();
if ($exist) {
$this->error(__("Email already exists"));
}*/
if ($params) {
$admin = Admin::get($this->auth->id);
$admin->save($params);
//因为个人资料面板读取的Session显示修改自己资料后同时更新Session
Session::set("admin", $admin->toArray());
$this->success();
}
$this->error();
}
return;
}
}

View File

@@ -0,0 +1,341 @@
<?php
namespace app\admin\controller\general;
use app\admin\library\Auth;
use app\common\controller\Backend;
use Exception;
use fast\Random;
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;
/**
* 狮友管理
*
* @icon fa fa-circle-o
*/
class Shiyou extends Backend
{
/**
* Shiyou模型对象
* @var \app\admin\model\Shiyou
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\Shiyou;
$this->view->assign("genderList", $this->model->getGenderList());
$this->view->assign("statusList", $this->model->getStatusList());
$this->view->assign("isSuperAdmin", $this->auth->isSuperAdmin());
$this->view->assign("group_id", $this->auth->getGroupIds()[0]);
}
/**
* 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
* 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
* 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
*/
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
//设置过滤方法
$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();
$wheres = [];
if(!$this->auth->isSuperAdmin()){
$groupIds = $this->auth->getGroupIds();
$wheres = ['group_id'=>['in',$groupIds]];
}
$list = $this->model
->with(['groups'])
->where($where)
->where($wheres)
->order($sort, $order)
->paginate($limit);
foreach ($list as $row) {
/*$row->visible(['id','nickname','mobile','gender','createtime','status']);
$row->visible(['groups']);*/
$row->getRelation('groups')->visible(['name']);
}
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
$this->assignconfig("isSuperAdmin", $this->auth->isSuperAdmin());
return $this->view->fetch();
}
/**
* 添加
*
* @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;
}
$result = false;
Db::startTrans();
try {
$params['salt'] = Random::alnum();
$params['password'] = md5(md5($params['password']) . $params['salt']);
$result = $this->model->validateFailException()->validate('Shiyou.add')->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
* @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'));
}
if (false === $this->request->isPost()) {
$this->view->assign('row', $row);
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);
$result = false;
Db::startTrans();
try {
if ($params['password']) {
$params['salt'] = Random::alnum();
$params['password'] = md5(md5($params['password']) . $params['salt']);
} else {
unset($params['password'], $params['salt']);
}
//这里需要针对mobile做唯一验证
$adminValidate = \think\Loader::validate('Shiyou');
$adminValidate->rule([
'mobile' => 'regex:1[3-9]\d{9}|unique:shiyou,mobile,' . $row->id,
]);
$result = $row->validateFailException()->validate('Shiyou.edit')->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();
}
/**
* 导入
*
* @return void
* @throws PDOException
* @throws BindParamException
*/
public 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;
}
}
$extend = [];
if(!in_array('服务队ID',$fields) && !in_array('group_id',$fields)){
//从服务队导入
$group_id = $this->request->param('ids');
//从狮友导入
if(empty($group_id)){
$groupInfo = $this->auth->getGroups()[0];
if($groupInfo['level'] != 3){
throw new \think\Exception('上传文件缺失参数 服务队ID');
}
$group_id = $groupInfo['group_id'];
}
$extend['group_id'] = $group_id;
}
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 !== '') {
if(empty($v)){
$row = []; break;
}
$row[$fieldArr[$k]] = $v;
}
}
if ($row) {
if(!empty($extend)) $row = array_merge($row, $extend);
$row['salt'] = Random::alnum();
$row['password'] = empty($row['password']) ? '123456' : $row['password'];
$row['password'] = md5(md5($row['password']) . $row['salt']);
$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();
}
}

View File

@@ -0,0 +1,248 @@
<?php
namespace app\admin\controller\general;
use app\common\controller\Backend;
use Exception;
use fast\Random;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\model\Area;
/**
* 学生管理
*
* @icon fa fa-circle-o
*/
class Student extends Backend
{
private $IdentifierModel;
/**
* Student模型对象
* @var \app\admin\model\Student
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\Student;
$this->IdentifierModel = new \app\admin\model\Identifier;
$this->view->assign("genderList", $this->model->getGenderList());
$this->view->assign("typeList", $this->model->getTypeList());
$this->view->assign("statusList", $this->model->getStatusList());
$this->view->assign("isSuperAdmin", $this->auth->isSuperAdmin());
$this->view->assign("group_id", $this->auth->getGroupIds()[0]);
}
/**
* 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
* 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
* 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
*/
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
//设置过滤方法
$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();
$wheres = [];
if(!$this->auth->isSuperAdmin()){
$groupIds = $this->auth->getGroupIds();
$wheres = ['student.group_id'=>['in',$groupIds]];
}
$list = $this->model
->with(['groups','grade'])
->where($where)
->where($wheres)
->order($sort, $order)
->paginate($limit);
foreach ($list as $row) {
$row->getRelation('groups')->visible(['name']);
$row->getRelation('grade')->visible(['grade','class']);
}
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
$this->assignconfig("isSuperAdmin", $this->auth->isSuperAdmin());
return $this->view->fetch();
}
/**
* 添加
*
* @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;
}
$result = false;
Db::startTrans();
try {
//编号状态
/*$identifier = $this->IdentifierModel->where('identifier', $params['identifier'])->find();
if(empty($identifier)){
$this->error("编号不存在");
}
if($identifier['status'] != 'normal'){
$this->error("编号已分配");
}
//修改编号状态
$this->IdentifierModel->where('identifier', $params['identifier'])->update(['status'=>'hidden']);*/
$params['salt'] = Random::alnum();
$params['password'] = md5(md5($params['password']) . $params['salt']);
$school = db('auth_group')->where('id',$params['group_id'])->find();
$params['school'] = $school['name'];
$info = db('auth_group')->where('id', $params['group_id'])->find();
while ($info['level'] > 2){
$info = db('auth_group')->where('id', $info['pid'])->find();
}
//地区编号
$area_encoded = db('area')->where('id', $info['city'])->find();
$params['city'] = $area_encoded['name'];
$result = $this->model->validateFailException()->validate('Student.add')->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
* @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'));
}
if (false === $this->request->isPost()) {
$this->view->assign('row', $row);
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);
$result = false;
Db::startTrans();
try {
if ($params['password']) {
$params['salt'] = Random::alnum();
$params['password'] = md5(md5($params['password']) . $params['salt']);
} else {
unset($params['password'], $params['salt']);
}
//这里需要针对mobile做唯一验证
$adminValidate = \think\Loader::validate('Student');
$adminValidate->rule([
'mobile' => 'regex:1[3-9]\d{9}|unique:student,mobile,' . $row->id,
]);
$result = $row->validateFailException()->validate('Student.edit')->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 {
//释放编号
$identifiers = array_column($list, 'identifier');
$this->IdentifierModel->where('identifier', 'in', $identifiers)->update(['status'=>'normal']);
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'));
}*/
}