Files
CardAuth/backend/app/Helpers/functions.php
T
root b317c1f1d8 fix: 超大 duration_days 导致卡密误标已使用
- 新增 calcExpireTime(): >36500天视为永久(null), 避免超出 MySQL DATETIME
- publicActivate 事务包裹, 失败回滚不残留 used 状态
- verify/订单发卡/自动发卡 统一使用安全过期时间
2026-10-11 12:40:37 +08:00

230 lines
5.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* 全局辅助函数
*/
/**
* 获取配置值
*/
function config(string $key, mixed $default = null): mixed
{
static $configs = [];
$keys = explode('.', $key, 2);
if (!isset($configs[$keys[0]])) {
$file = CONFIG_PATH . '/' . $keys[0] . '.php';
if (file_exists($file)) {
$configs[$keys[0]] = require $file;
} else {
return $default;
}
}
if (count($keys) === 1) {
return $configs[$keys[0]];
}
return dotGet($configs[$keys[0]], $keys[1], $default);
}
/**
* 点号访问数组
*/
function dotGet(array $array, string $key, mixed $default = null): mixed
{
$keys = explode('.', $key);
foreach ($keys as $segment) {
if (!is_array($array) || !array_key_exists($segment, $array)) {
return $default;
}
$array = $array[$segment];
}
return $array;
}
/**
* 获取环境变量
*/
function env(string $key, mixed $default = null): mixed
{
$value = $_ENV[$key] ?? getenv($key);
if ($value === false) return $default;
return match (strtolower($value)) {
'true', '(true)' => true,
'false', '(false)' => false,
'null', '(null)' => null,
default => $value,
};
}
/**
* 获取数据库实例
*/
function db(): \App\Core\Database
{
return \App\Core\Database::getInstance();
}
/**
* 生成UUID v4
*/
function uuid(): string
{
$data = random_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
/**
* 生成随机字符串
*/
function randomStr(int $length = 32): string
{
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$str = '';
for ($i = 0; $i < $length; $i++) {
$str .= $chars[random_int(0, strlen($chars) - 1)];
}
return $str;
}
/**
* 密码哈希
*/
function passwordHash(string $password): string
{
return password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
}
/**
* 验证密码
*/
function passwordVerify(string $password, string $hash): bool
{
return password_verify($password, $hash);
}
/**
* 获取客户端IP
*/
function clientIp(): string
{
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
return trim($ips[0]);
}
if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
return $_SERVER['HTTP_X_REAL_IP'];
}
return $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
}
/**
* 获取User-Agent
*/
function userAgent(): string
{
return $_SERVER['HTTP_USER_AGENT'] ?? '';
}
/**
* 记录日志(简化版)
*/
function logger(string $action, string $targetType = '', int $targetId = 0, array $detail = []): void
{
try {
$db = db();
$db->insert("INSERT INTO {$db->table('logs')} (user_id, action, target_type, target_id, detail, ip, user_agent, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())", [
$_SERVER['HTTP_X_USER_ID'] ?? 0,
$action,
$targetType,
$targetId,
json_encode($detail, JSON_UNESCAPED_UNICODE),
clientIp(),
userAgent(),
]);
} catch (\Throwable $e) {
error_log('Logger error: ' . $e->getMessage());
}
}
/**
* 语义化版本比较
* @return int -1 a<b, 0 a==b, 1 a>b
*/
function compareVersions(string $a, string $b): int
{
$normalize = static function (string $v): string {
$v = trim($v);
if ($v === '') {
return '0.0.0';
}
if ($v[0] === 'v' || $v[0] === 'V') {
$v = substr($v, 1);
}
return $v;
};
return version_compare($normalize($a), $normalize($b));
}
/**
* 时间格式化为北京时间字符串
* 用于安装统计等接口返回,确保前端展示为北京时间
*/
function beijingTime(?string $value): ?string
{
if ($value === null || $value === '' || $value === '0000-00-00 00:00:00') {
return $value;
}
try {
$dt = new \DateTimeImmutable($value, new \DateTimeZone(date_default_timezone_get() ?: 'UTC'));
return $dt->setTimezone(new \DateTimeZone('Asia/Shanghai'))->format('Y-m-d H:i:s');
} catch (\Throwable $e) {
return $value;
}
}
/**
* 将记录中多个时间字段转为北京时间
*/
function beijingTimeFields(array $row, array $fields): array
{
foreach ($fields as $field) {
if (array_key_exists($field, $row)) {
$row[$field] = beijingTime($row[$field]);
}
}
return $row;
}
/**
* 根据有效天数计算过期时间
* - days <= 0:永久,返回 null
* - 超大天数(超出 MySQL DATETIME 或 100 年):视为永久 null,避免插入失败导致卡被标已用但无授权
* @return string|null
*/
function calcExpireTime(int $days, ?string $baseTime = null): ?string
{
if ($days <= 0) {
return null;
}
$base = $baseTime ? strtotime($baseTime) : time();
if ($base === false) {
$base = time();
}
// 超过约 100 年视为永久(避免 strtotime 溢出 / 超出 DATETIME 9999-12-31)
if ($days > 36500) {
return null;
}
$ts = strtotime("+{$days} days", $base);
if ($ts === false) {
return null;
}
$max = strtotime('9999-12-31 23:59:59');
if ($ts === false || $ts > $max) {
return '9999-12-31 23:59:59';
}
return date('Y-m-d H:i:s', $ts);
}