框架升级及修复升级后的bug

This commit is contained in:
Dev
2026-10-16 18:13:09 +08:00
parent dafb0c96c0
commit 2d342bcbd7
537 changed files with 49836 additions and 40933 deletions
@@ -69,7 +69,7 @@ class Api
* @access public
* @param Request $request Request 对象
*/
public function __construct(Request $request = null)
public function __construct(?Request $request = null)
{
$this->request = is_null($request) ? Request::instance() : $request;
+13 -126
View File
@@ -3,6 +3,7 @@
namespace app\common\controller;
use app\admin\library\Auth;
use app\common\library\SelectPage;
use think\Config;
use think\Controller;
use think\Hook;
@@ -10,7 +11,6 @@ use think\Lang;
use think\Loader;
use think\Model;
use think\Session;
use fast\Tree;
use think\Validate;
/**
@@ -459,140 +459,27 @@ class Backend extends Controller
/**
* Selectpage的实现方法
*
* 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
* 这里示例了所有的参数,所以比较复杂,实现上自己实现只需简单的几行即可
*
*/
protected function selectpage()
{
//设置过滤方法
$this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);
//搜索关键词,客户端输入以空格分开,这里接收为数组
$word = (array)$this->request->request("q_word/a");
//当前页
$page = $this->request->request("pageNumber");
//分页大小
$pagesize = $this->request->request("pageSize");
//搜索条件
$andor = $this->request->request("andOr", "and", "strtoupper");
//排序方式
$orderby = (array)$this->request->request("orderBy/a");
//显示的字段
$field = $this->request->request("showField");
//主键
$primarykey = $this->request->request("keyField");
//主键值
$primaryvalue = $this->request->request("keyValue");
//搜索字段
$searchfield = (array)$this->request->request("searchField/a");
//自定义搜索条件
$custom = (array)$this->request->request("custom/a");
//是否返回树形结构
$istree = $this->request->request("isTree", 0);
$ishtml = $this->request->request("isHtml", 0);
if ($istree) {
$word = [];
$pagesize = 999999;
$selectPage = new SelectPage($this->model, $this->selectpageFields);
// 数据限制
$dataLimitIds = $this->getDataLimitAdminIds();
if (is_array($dataLimitIds)) {
$selectPage->setDataLimit($this->dataLimit, $this->dataLimitField, $dataLimitIds);
}
$order = [];
foreach ($orderby as $k => $v) {
$order[$v[0]] = $v[1];
try {
$result = $selectPage->execute($this->request->request());
} catch (\think\Exception $e) {
$this->error(__($e->getMessage()));
}
$field = $field ? $field : 'name';
//如果有primaryvalue,说明当前是初始化传值
if ($primaryvalue !== null) {
$where = [$primarykey => ['in', $primaryvalue]];
$pagesize = 999999;
} else {
$where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
$logic = $andor == 'AND' ? '&' : '|';
$searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
$searchfield = str_replace(',', $logic, $searchfield);
$word = array_filter(array_unique($word));
if (count($word) == 1) {
$query->where($searchfield, "like", "%" . reset($word) . "%");
} else {
$query->where(function ($query) use ($word, $searchfield) {
foreach ($word as $index => $item) {
$query->whereOr(function ($query) use ($item, $searchfield) {
$query->where($searchfield, "like", "%{$item}%");
});
}
});
}
if ($custom && is_array($custom)) {
foreach ($custom as $k => $v) {
if (is_array($v) && 2 == count($v)) {
$query->where($k, trim($v[0]), $v[1]);
} else {
$query->where($k, '=', $v);
}
}
}
};
}
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
$this->model->where($this->dataLimitField, 'in', $adminIds);
}
$list = [];
$total = $this->model->where($where)->count();
if ($total > 0) {
if (is_array($adminIds)) {
$this->model->where($this->dataLimitField, 'in', $adminIds);
}
$fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);
//如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
$primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
//修复自定义data-primary-key为字符串内容时,给排序字段添加上引号
$primaryvalue = array_map(function ($value) {
return '\'' . $value . '\'';
}, $primaryvalue);
$primaryvalue = implode(',', $primaryvalue);
$this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
} else {
$this->model->order($order);
}
$datalist = $this->model->where($where)
->page($page, $pagesize)
->select();
foreach ($datalist as $index => $item) {
unset($item['password'], $item['salt']);
if ($this->selectpageFields == '*') {
$result = [
$primarykey => $item[$primarykey] ?? '',
$field => $item[$field] ?? '',
];
} else {
$result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
}
$result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
$list[] = $result;
}
if ($istree && !$primaryvalue) {
$tree = Tree::instance();
$tree->init(collection($list)->toArray(), 'pid');
$list = $tree->getTreeList($tree->getTreeArray(0), $field);
if (!$ishtml) {
foreach ($list as &$item) {
$item = str_replace(' ', ' ', $item);
}
unset($item);
}
}
}
//这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
return json(['list' => $list, 'total' => $total]);
return json($result);
}
/**
+21 -4
View File
@@ -184,8 +184,7 @@ class Auth
$this->_user = User::get($user->id);
//设置Token
$this->_token = Random::uuid();
Token::set($this->_token, $user->id, $this->keeptime);
$this->_token = $this->generateToken($user->id);
//设置登录状态
$this->_logined = true;
@@ -224,6 +223,7 @@ class Auth
if ($user->loginfailure >= 10 && time() - $user->loginfailuretime < 86400) {
$this->setError('Please try again after 1 day');
return false;
}
if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
@@ -324,8 +324,7 @@ class Auth
$this->_user = $user;
$this->_token = Random::uuid();
Token::set($this->_token, $user->id, $this->keeptime);
$this->_token = $this->generateToken($user->id);
$this->_logined = true;
@@ -559,6 +558,24 @@ class Auth
return $datalist;
}
/**
* 生成并写入Token(如遇碰撞则重试)
* @param int $user_id
* @return string
* @throws Exception
*/
private function generateToken($user_id): string
{
$maxAttempts = 5;
for ($i = 0; $i < $maxAttempts; $i++) {
$token = Random::uuid();
if (Token::set($token, $user_id, $this->keeptime)) {
return $token;
}
}
throw new Exception('Failed to generate unique token');
}
/**
* 设置错误信息
*
+1 -1
View File
@@ -196,7 +196,7 @@ class Email
/**
* 设置错误
* @param string $error 信息信息
* @param string $error 错误信息
*/
protected function setError($error)
{
+69 -22
View File
@@ -3,6 +3,7 @@
namespace app\common\library;
use fast\Random;
use think\Db;
use think\Hook;
/**
@@ -43,13 +44,13 @@ class Ems
* 发送验证码
*
* @param int $email 邮箱
* @param int $code 验证码,为空时将自动生成4位数字
* @param int $code 验证码,为空时将自动生成6位数字
* @param string $event 事件
* @return boolean
*/
public static function send($email, $code = null, $event = 'default')
{
$code = is_null($code) ? Random::numeric(config('captcha.length')) : $code;
$code = is_null($code) ? Random::numeric(config('fastadmin.ems_captcha_length') ?: 6) : $code;
$time = time();
$ip = request()->ip();
$ems = \app\common\model\Ems::create(['event' => $event, 'email' => $email, 'code' => $code, 'ip' => $ip, 'createtime' => $time]);
@@ -111,31 +112,77 @@ class Ems
* @param int $email 邮箱
* @param int $code 验证码
* @param string $event 事件
* @param boolean $flush 验证成功是否删除
* @return boolean
*/
public static function check($email, $code, $event = 'default')
public static function check($email, $code, $event = 'default', $flush = false)
{
$time = time() - self::$expire;
$ems = \app\common\model\Ems::where(['email' => $email, 'event' => $event])
->order('id', 'DESC')
->find();
if ($ems) {
if ($ems['createtime'] > $time && $ems['times'] <= self::$maxCheckNums) {
$correct = $code == $ems['code'];
if (!$correct) {
$ems->times = $ems->times + 1;
$ems->save();
return false;
} else {
$result = Hook::listen('ems_check', $ems, null, true);
return true;
}
} else {
// 过期则清空该邮箱验证码
self::flush($email, $event);
if (empty($email) || empty($code)) {
return false;
}
$expireTime = time() - self::$expire;
// 开启事务
Db::startTrans();
try {
// 使用行锁查询最新的验证码记录
$ems = \app\common\model\Ems::where([
'email' => $email,
'event' => $event
])
->order('id', 'desc')
->lock(true) // 行锁
->find();
// 验证码记录不存在
if (!$ems) {
Db::rollback();
return false;
}
} else {
// 验证码已过期
if ($ems['createtime'] <= $expireTime) {
self::flush($email, $event);
Db::rollback();
return false;
}
// 验证次数已超限
if ($ems['times'] >= self::$maxCheckNums) {
Db::rollback();
return false;
}
// 先增加验证次数(无论验证成功失败都计数)
Db::name('ems')
->where('id', $ems['id'])
->setInc('times');
// 验证码不匹配
if ($code != $ems['code']) {
Db::commit(); // 提交次数增加
return false;
}
// 删除验证码
if ($flush) {
self::flush($email, $event);
}
// 验证成功,提交事务
Db::commit();
// 触发验证成功钩子
Hook::listen('ems_check', $ems);
return true;
} catch (\Exception $e) {
Db::rollback();
// 记录错误日志
\think\Log::record('EMS验证异常: ' . $e->getMessage(), 'error');
return false;
}
}
+1 -3
View File
@@ -19,10 +19,8 @@ class Log extends AbstractLogger
* @param array $context
*
* @return void
*
* @throws \Psr\Log\InvalidArgumentException
*/
public function log($level, $message, array $context = array())
public function log($level, $message, array $context = [])
{
\think\Log::write($message);
}
@@ -0,0 +1,449 @@
<?php
namespace app\common\library;
use fast\Tree;
use think\Db;
use think\db\Query;
use think\Exception;
use think\Model;
/**
* SelectPage 查询构建器
*/
class SelectPage
{
/**
* 模型实例
* @var Model
*/
protected $model;
/**
* 允许显示的字段
* @var array|string
*/
protected $selectpageFields = '*';
/**
* 数据限制模式
* @var bool|string
*/
protected $dataLimit = false;
/**
* 数据限制字段
* @var string
*/
protected $dataLimitField = 'admin_id';
/**
* 允许的表字段列表
* @var array
*/
protected $allowedFields = [];
/**
* 允许的操作符(ThinkPHP Builder::$exp 的键和值(不包含exp),去重后保留小写)
* @var array
*/
protected static $allowedOperators = [
'eq', 'neq', 'gt', 'egt', 'lt', 'elt',
'=', '<>', '>', '>=', '<', '<=',
'like', 'not like', 'notlike',
'in', 'not in', 'notin',
'between', 'not between', 'notbetween',
'null', 'not null', 'notnull',
'exists', 'not exists', 'notexists',
'> time', '< time', '>= time', '<= time',
'between time', 'not between time', 'notbetween time',
];
/**
* 允许排序的字段
* @var array
*/
protected $orderFields = [];
/**
* @param Model | Query $model 模型实例
* @param string $fields SelectPage可显示的字段
*/
public function __construct($model, $fields = '*')
{
$this->model = $model;
$this->selectpageFields = $fields;
$this->allowedFields = array_map('strtolower', $model->getTableFields());
$this->orderFields = $this->allowedFields;
}
/**
* 数据限制的ID集合
* @var array
*/
protected $dataLimitIds = [];
/**
* 设置数据限制
* @param bool|string $dataLimit auth/personal/false
* @param string $dataLimitField 限制字段
* @param array $dataLimitIds 允许的ID列表
* @return $this
*/
public function setDataLimit($dataLimit, $dataLimitField = 'admin_id', array $dataLimitIds = [])
{
$this->dataLimit = $dataLimit;
$this->dataLimitField = $dataLimitField;
$this->dataLimitIds = $dataLimitIds;
return $this;
}
/**
* 应用数据限制条件(每次构建新查询链前调用)
* ThinkPHP 的 count()/select() 执行后会清空 model options,
* 所以需要在每次查询前重新注入 dataLimit 条件。
* @return $this
*/
protected function applyDataLimit()
{
if ($this->dataLimit) {
$this->model->where($this->dataLimitField, 'in', $this->dataLimitIds);
}
return $this;
}
/**
* 执行查询
* @param array $params 请求参数
* @return array ['list' => [...], 'total' => int]
*/
public function execute(array $params)
{
$keywordWords = $this->getArrayParam($params, 'q_word');
$page = $params['pageNumber'] ?? 1;
$pageSize = $params['pageSize'] ?? 10;
$andor = strtoupper($params['andOr'] ?? 'AND');
$orderBy = $this->getArrayParam($params, 'orderBy');
$showField = $params['showField'] ?? 'name';
$keyField = $params['keyField'] ?? '';
$keyValue = $params['keyValue'] ?? null;
$searchField = $this->getArrayParam($params, 'searchField');
$custom = $this->getArrayParam($params, 'custom');
$isTree = (bool)($params['isTree'] ?? 0);
$isHtml = (bool)($params['isHtml'] ?? 0);
// 树形模式强制参数
if ($isTree) {
$keywordWords = [];
$pageSize = 999999;
}
// 验证字段
$this->validateField($showField);
$this->validateField($keyField);
// 验证搜索字段
foreach ($searchField as $f) {
$this->validateField($f);
}
// 验证自定义条件的字段和操作符
$this->validateCustomConditions($custom);
// 构建排序
$order = $this->buildOrder($orderBy);
// 构建查询条件
$where = $this->buildWhere(
$keywordWords,
$andor,
$showField,
$searchField,
$custom,
$keyField,
$keyValue
);
// 执行总数统计
$total = $this->applyDataLimit()
->model->where($where)
->count();
if ($total <= 0) {
return ['list' => [], 'total' => 0];
}
// 排序处理
if ($keyValue !== null && $keyField) {
$pageSize = 999999;
$this->applyPrimaryKeyOrder($keyField, $keyValue);
} else {
$this->model->order($order);
}
// 执行查询(count()会清空options,需重新应用dataLimit)
$dataList = $this->applyDataLimit()
->model->where($where)
->page($page, $pageSize)
->select();
// 构建结果集
$list = $this->buildResultList($dataList, $showField, $keyField);
// 树形结构处理
if ($isTree && !$keyValue) {
$list = $this->buildTreeList($list, $showField, $isHtml);
}
return ['list' => $list, 'total' => $total];
}
/**
* 标准化字段为数组(支持逗号分隔字符串)
*/
protected function normalizeField($field): array
{
if (is_array($field)) {
return $field;
}
if (is_string($field) && strpos($field, ',') !== false) {
return array_map('trim', explode(',', $field));
}
return $field !== '' ? [$field] : [];
}
/**
* 获取数组参数
*/
protected function getArrayParam(array $params, string $key): array
{
$value = $params[$key] ?? [];
if (is_array($value)) {
return $value;
}
if (is_string($value) && strpos($value, ',') !== false) {
return array_map('trim', explode(',', $value));
}
if ($value === '' || $value === null) {
return [];
}
return [$value];
}
/**
* 验证字段名是否在允许列表中
*/
protected function validateField(string $field)
{
$field = strtolower($field);
if (!in_array($field, $this->allowedFields, true)) {
throw new Exception('Invalid parameters');
}
}
/**
* 验证自定义搜索条件
*/
protected function validateCustomConditions(array $custom)
{
foreach ($custom as $k => $v) {
$field = strtolower($k);
if (!in_array($field, $this->allowedFields, true)) {
throw new Exception('Invalid parameters');
}
// 如果操作符是数组形式传入,校验操作符合法性
if (is_array($v) && count($v) >= 2) {
$operator = strtolower(trim($v[0]));
if (!in_array($operator, self::$allowedOperators, true)) {
throw new Exception('Invalid parameters');
}
}
}
}
/**
* 构建排序
*/
protected function buildOrder(array $orderBy): array
{
$order = [];
foreach ($orderBy as $v) {
if (!isset($v[0], $v[1])) {
continue;
}
$field = strtolower($v[0]);
$direction = strtoupper($v[1]) === 'ASC' ? 'ASC' : 'DESC';
if (in_array($field, $this->orderFields, true)) {
$order[$field] = $direction;
}
}
return $order;
}
/**
* 构建查询条件
*/
protected function buildWhere(
array $keywordWords,
string $andor,
string $showField,
array $searchField,
array $custom,
string $keyField,
$keyValue
)
{
// 如果有 keyValue,按主键值精确查询
if ($keyValue !== null && $keyField) {
return [$keyField => ['in', is_array($keyValue) ? $keyValue : explode(',', (string)$keyValue)]];
}
return function ($query) use ($keywordWords, $andor, $showField, $searchField, $custom) {
// 关键词搜索
$searchFields = $this->resolveSearchFields($searchField, $showField, $andor);
$words = array_filter(array_unique($keywordWords));
if (!empty($words)) {
if (count($words) === 1) {
$query->where($searchFields, 'like', '%' . reset($words) . '%');
} else {
$query->where(function ($query) use ($words, $searchFields) {
foreach ($words as $word) {
$query->whereOr($searchFields, 'like', '%' . $word . '%');
}
});
}
}
// 自定义条件
foreach ($custom as $k => $v) {
if (is_array($v) && count($v) >= 2) {
$operator = strtolower(trim($v[0]));
$value = $v[1];
$query->where(strtolower($k), $operator, $value);
} else {
$query->where(strtolower($k), '=', $v);
}
}
};
}
/**
* 解析搜索字段
*/
protected function resolveSearchFields(array $searchField, string $showField, string $andor): string
{
// 过滤掉不在允许列表中的字段
$validFields = [];
$inputFields = array_filter(array_map('trim', $searchField));
foreach ($inputFields as $field) {
$lowerField = strtolower($field);
if (in_array($lowerField, $this->allowedFields, true)) {
$validFields[] = $lowerField;
}
}
if (empty($validFields)) {
$lowerShow = strtolower($showField);
if (in_array($lowerShow, $this->allowedFields, true)) {
return $lowerShow;
}
return 'id';
}
$logic = $andor === 'AND' ? '&' : '|';
return implode($logic, $validFields);
}
/**
* 应用主键排序
*/
protected function applyPrimaryKeyOrder(string $keyField, $keyValue)
{
$values = is_array($keyValue) ? $keyValue : explode(',', (string)$keyValue);
$values = array_unique(array_filter(array_map(function ($v) {
return trim((string)$v);
}, $values)));
if (empty($values)) {
return;
}
$quotedValues = implode(',', array_map(function ($v) {
return Db::quote($v);
}, $values));
$this->model->orderRaw("FIELD(`{$keyField}`, {$quotedValues})");
}
/**
* 构建结果列表
*/
protected function buildResultList($dataList, string $showField, string $keyField): array
{
$list = [];
$fields = $this->resolveSelectpageFields();
foreach ($dataList as $item) {
$row = $item instanceof Model ? $item->toArray() : (array)$item;
// 移除敏感字段
unset($row['password'], $row['salt']);
if ($this->selectpageFields === '*') {
$result = [
$keyField => $row[$keyField] ?? '',
$showField => $row[$showField] ?? '',
];
} else {
$result = array_intersect_key($row, array_flip($fields));
}
// 添加父级ID
$result['pid'] = $row['pid'] ?? ($row['parent_id'] ?? 0);
// HTML 转义
$result = array_map(function ($value) {
return $value === null ? '' : htmlentities((string)$value, ENT_QUOTES, 'UTF-8');
}, $result);
$list[] = $result;
}
return $list;
}
/**
* 构建树形列表
*/
protected function buildTreeList(array $list, string $showField, bool $isHtml): array
{
$tree = Tree::instance();
$tree->init($list, 'pid');
$result = $tree->getTreeList($tree->getTreeArray(0), $showField);
if (!$isHtml) {
foreach ($result as &$item) {
$item = str_replace('&nbsp;', ' ', $item);
}
unset($item);
}
return $result;
}
/**
* 解析 SelectPage 显示字段
*/
protected function resolveSelectpageFields(): array
{
if (is_array($this->selectpageFields)) {
return $this->selectpageFields;
}
if ($this->selectpageFields && $this->selectpageFields !== '*') {
return array_map('trim', explode(',', $this->selectpageFields));
}
return [];
}
}
+82 -34
View File
@@ -3,6 +3,7 @@
namespace app\common\library;
use fast\Random;
use think\Db;
use think\Hook;
/**
@@ -26,8 +27,8 @@ class Sms
/**
* 获取最后一次手机发送的数据
*
* @param int $mobile 手机号
* @param string $event 事件
* @param int $mobile 手机号
* @param string $event 事件
* @return Sms
*/
public static function get($mobile, $event = 'default')
@@ -42,14 +43,14 @@ class Sms
/**
* 发送验证码
*
* @param int $mobile 手机号
* @param int $code 验证码,为空时将自动生成4位数字
* @param string $event 事件
* @param int $mobile 手机号
* @param int $code 验证码,为空时将自动生成6位数字
* @param string $event 事件
* @return boolean
*/
public static function send($mobile, $code = null, $event = 'default')
{
$code = is_null($code) ? Random::numeric(config('captcha.length')) : $code;
$code = is_null($code) ? Random::numeric(config('fastadmin.sms_captcha_length') ?: 6) : $code;
$time = time();
$ip = request()->ip();
$sms = \app\common\model\Sms::create(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'createtime' => $time]);
@@ -64,9 +65,9 @@ class Sms
/**
* 发送通知
*
* @param mixed $mobile 手机号,多个以,分隔
* @param string $msg 消息内容
* @param string $template 消息模板
* @param mixed $mobile 手机号,多个以,分隔
* @param string $msg 消息内容
* @param string $template 消息模板
* @return boolean
*/
public static function notice($mobile, $msg = '', $template = null)
@@ -83,34 +84,81 @@ class Sms
/**
* 校验验证码
*
* @param int $mobile 手机号
* @param int $code 验证码
* @param string $event 事件
* @param int $mobile 手机号
* @param int $code 验证码
* @param string $event 事件
* @param boolean $flush 验证成功是否删除
* @return boolean
*/
public static function check($mobile, $code, $event = 'default')
public static function check($mobile, $code, $event = 'default', $flush = false)
{
$time = time() - self::$expire;
$sms = \app\common\model\Sms::where(['mobile' => $mobile, 'event' => $event])
->order('id', 'DESC')
->find();
if ($sms) {
if ($sms['createtime'] > $time && $sms['times'] <= self::$maxCheckNums) {
$correct = $code == $sms['code'];
if (!$correct) {
$sms->times = $sms->times + 1;
$sms->save();
return false;
} else {
$result = Hook::listen('sms_check', $sms, null, true);
return $result;
}
} else {
// 过期则清空该手机验证码
self::flush($mobile, $event);
if (empty($mobile) || empty($code)) {
return false;
}
$expireTime = time() - self::$expire;
// 开启事务
Db::startTrans();
try {
// 使用行锁查询最新的验证码记录
$sms = \app\common\model\Sms::where([
'mobile' => $mobile,
'event' => $event
])
->order('id', 'desc')
->lock(true) // 行锁
->find();
// 验证码记录不存在
if (!$sms) {
Db::rollback();
return false;
}
} else {
// 验证码已过期
if ($sms['createtime'] <= $expireTime) {
self::flush($mobile, $event);
Db::rollback();
return false;
}
// 验证次数已超限
if ($sms['times'] >= self::$maxCheckNums) {
Db::rollback();
return false;
}
// 先增加验证次数(无论验证成功失败都计数)
Db::name('sms')
->where('id', $sms['id'])
->setInc('times');
// 验证码不匹配
if ($code != $sms['code']) {
Db::commit(); // 提交次数增加
return false;
}
// 删除验证码
if ($flush) {
self::flush($mobile, $event);
}
// 验证成功,提交事务
Db::commit();
// 触发验证成功钩子
Hook::listen('sms_check', $sms);
return true;
} catch (\Exception $e) {
Db::rollback();
// 记录错误日志
\think\Log::record('SMS验证异常: ' . $e->getMessage(), 'error');
return false;
}
}
@@ -118,8 +166,8 @@ class Sms
/**
* 清空指定手机号验证码
*
* @param int $mobile 手机号
* @param string $event 事件
* @param int $mobile 手机号
* @param string $event 事件
* @return boolean
*/
public static function flush($mobile, $event = 'default')
+6 -78
View File
@@ -86,6 +86,11 @@ class Upload
*/
protected function checkExecutable()
{
//禁止上传以.开头的文件
if (substr($this->fileInfo['name'], 0, 1) === '.') {
throw new UploadException(__('Uploaded file format is limited'));
}
//禁止上传PHP和HTML文件
if (in_array($this->fileInfo['type'], ['text/x-php', 'text/html']) || in_array($this->fileInfo['suffix'], ['php', 'html', 'htm', 'phar', 'phtml']) || preg_match("/^php(.*)/i", $this->fileInfo['suffix'])) {
throw new UploadException(__('Uploaded file format is limited'));
@@ -107,8 +112,7 @@ class Upload
throw new UploadException(__('Uploaded file format is limited'));
}
//验证文件后缀
if ($this->config['mimetype'] === '*'
|| in_array($this->fileInfo['suffix'], $mimetypeArr) || in_array('.' . $this->fileInfo['suffix'], $mimetypeArr)
if (in_array($this->fileInfo['suffix'], $mimetypeArr) || in_array('.' . $this->fileInfo['suffix'], $mimetypeArr)
|| in_array($typeArr[0] . "/*", $mimetypeArr) || (in_array($this->fileInfo['type'], $mimetypeArr) && stripos($this->fileInfo['type'], '/') !== false)) {
return true;
}
@@ -347,82 +351,6 @@ class Upload
return $file;
}
/**
* 普通上传
* @return \app\common\model\attachment|\think\Model
* @throws UploadException
*/
public function uploadFile($savekey = null)
{
if (empty($this->file)) {
throw new UploadException(__('No file upload or server upload limit exceeded'));
}
$this->checkSize();
$this->checkExecutable();
$this->checkMimetype();
$this->checkImage();
$savekey = $savekey ? $savekey : $this->getSavekey();
$savekey = '/' . ltrim($savekey, '/');
$uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
$fileName = substr($savekey, strripos($savekey, '/') + 1);
$destDir = ROOT_PATH . 'public' . str_replace('/', DS, $uploadDir);
$sha1 = $this->file->hash();
//如果是合并文件
if ($this->merging) {
if (!$this->file->check()) {
throw new UploadException($this->file->getError());
}
$destFile = $destDir . $fileName;
$sourceFile = $this->file->getRealPath() ?: $this->file->getPathname();
$info = $this->file->getInfo();
$this->file = null;
if (!is_dir($destDir)) {
@mkdir($destDir, 0755, true);
}
rename($sourceFile, $destFile);
$file = new File($destFile);
$file->setSaveName($fileName)->setUploadInfo($info);
} else {
$file = $this->file->move($destDir, $fileName);
if (!$file) {
// 上传失败获取错误信息
throw new UploadException($this->file->getError());
}
}
$this->file = $file;
$category = request()->post('category');
$category = array_key_exists($category, config('site.attachmentcategory') ?? []) ? $category : '';
$auth = Auth::instance();
$params = array(
'admin_id' => (int)session('admin.id'),
'user_id' => (int)$auth->id,
'filename' => mb_substr(htmlspecialchars(strip_tags($this->fileInfo['name'])), 0, 100),
'category' => $category,
'filesize' => $this->fileInfo['size'],
'imagewidth' => $this->fileInfo['imagewidth'],
'imageheight' => $this->fileInfo['imageheight'],
'imagetype' => $this->fileInfo['suffix'],
'imageframes' => 0,
'mimetype' => $this->fileInfo['type'],
'url' => $uploadDir . $file->getSaveName(),
'uploadtime' => time(),
'storage' => 'local',
'sha1' => $sha1,
'extparam' => '',
);
$attachment = new Attachment();
$attachment->data(array_filter($params));
$attachment->save();
\think\Hook::listen("upload_after", $attachment);
return $attachment;
}
/**
* 普通上传
* @return \app\common\model\attachment|\think\Model
@@ -55,6 +55,10 @@ class Mysql extends Driver
{
$expiretime = !is_null($expire) && $expire !== 0 ? time() + $expire : 0;
$token = $this->getEncryptedToken($token);
$exists = $this->handler->where('token', $token)->count();
if ($exists) {
return false;
}
$this->handler->insert(['token' => $token, 'user_id' => $user_id, 'createtime' => time(), 'expiretime' => $expiretime]);
return true;
}
@@ -90,14 +90,20 @@ class Redis extends Driver
$expire = $expire->getTimestamp() - time();
}
$key = $this->getEncryptedToken($token);
if ($this->handler->exists($key)) {
return false;
}
if ($expire) {
$result = $this->handler->setex($key, $expire, $user_id);
} else {
$result = $this->handler->set($key, $user_id);
$result = $this->handler->setnx($key, $user_id);
if (!$result) {
return false;
}
}
//写入会员关联的token
$this->handler->sAdd($this->getUserKey($user_id), $key);
return $result;
return (bool)$result;
}
/**
+1 -1
View File
@@ -219,7 +219,7 @@ class Config extends Model
}
file_put_contents(
CONF_PATH . 'extra' . DS . 'site.php',
'<?php' . "\n\nreturn " . var_export_short($config) . ";\n"
'<?php' . "\n\nreturn " . var_export($config, true) . ";\n"
);
return true;
}
@@ -7,6 +7,10 @@ use think\Model;
/**
* 会员模型
* @method static mixed getByUsername($str) 通过用户名查询用户
* @method static mixed getByNickname($str) 通过昵称查询用户
* @method static mixed getByMobile($str) 通过手机查询用户
* @method static mixed getByEmail($str) 通过邮箱查询用户
*/
class User extends Model
{