feat: 新增阿里云OSS适配器及分类图标优化
- 新增阿里云OSS SDK核心类库文件 - 新增OSS插件配置文件及钩子监听 - 新增分类图标SVG资源并优化为轻量化格式 - 替换定位接口为天地图逆地理编码接口 - 新增OSS图片缩略处理工具方法
这个提交包含在:
@@ -5,12 +5,10 @@ namespace app\common\library;
|
||||
use think\Db;
|
||||
|
||||
/**
|
||||
* 全国标准省/市/区县服务区域工具类
|
||||
* 服务区域工具类
|
||||
*
|
||||
* 规则:
|
||||
* - 默认全国所有省、市、区县全部开通,无需后台手动维护;
|
||||
* - 数据源取自 application/extra/national_areas.json(由全国行政区划字典构建,涵盖全国 34 个省级行政区、全部地级市及区县);
|
||||
* - 同时合并 fa_fc_area 表中历史自定义记录,确保旧 ID 与历史数据 100% 兼容。
|
||||
* 唯一数据源:fa_fc_area 数据库表。后台手动增/删/改,enabled 控制显隐。
|
||||
* national_areas.json 仅作为"恢复全国默认"时的种子数据源(误删或重装时一键灌入)。
|
||||
*/
|
||||
class NationalArea
|
||||
{
|
||||
@@ -18,9 +16,8 @@ class NationalArea
|
||||
protected static $allCache = null;
|
||||
|
||||
/**
|
||||
* 获取全国全部省/市/区县平铺列表
|
||||
*
|
||||
* @return array<int, array{id:int,province:string,city:string,district:string,lat:float|null,lng:float|null}>
|
||||
* 获取全部可选省/市/区县平铺列表
|
||||
* 只查 fa_fc_area WHERE enabled=1 ORDER BY sort asc, id asc。
|
||||
*/
|
||||
public static function all()
|
||||
{
|
||||
@@ -28,55 +25,24 @@ class NationalArea
|
||||
return self::$allCache;
|
||||
}
|
||||
|
||||
$jsonFile = APP_PATH . 'extra' . DS . 'national_areas.json';
|
||||
$list = [];
|
||||
if (is_file($jsonFile)) {
|
||||
$decoded = json_decode((string)file_get_contents($jsonFile), true);
|
||||
if (is_array($decoded)) {
|
||||
$list = $decoded;
|
||||
}
|
||||
}
|
||||
|
||||
// 合并数据库中已有的自定义启用区域(避免重复)
|
||||
try {
|
||||
$dbRows = Db::name('fc_area')
|
||||
$rows = Db::name('fc_area')
|
||||
->where('enabled', 1)
|
||||
->order('sort asc, id asc')
|
||||
->select();
|
||||
$seenKey = [];
|
||||
$seenId = [];
|
||||
foreach ($list as $idx => $item) {
|
||||
$k = $item['province'] . '|' . $item['city'] . '|' . $item['district'];
|
||||
$seenKey[$k] = $idx;
|
||||
$seenId[(int)$item['id']] = $idx;
|
||||
}
|
||||
foreach ($dbRows as $row) {
|
||||
$p = (string)$row['province'];
|
||||
$c = (string)$row['city'];
|
||||
$d = (string)$row['district'];
|
||||
$k = $p . '|' . $c . '|' . $d;
|
||||
$id = (int)$row['id'];
|
||||
if (isset($seenKey[$k])) {
|
||||
$targetIdx = $seenKey[$k];
|
||||
if ($row['lat'] !== null && $row['lng'] !== null) {
|
||||
$list[$targetIdx]['lat'] = (float)$row['lat'];
|
||||
$list[$targetIdx]['lng'] = (float)$row['lng'];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!isset($seenId[$id])) {
|
||||
$list[] = [
|
||||
'id' => $id,
|
||||
'province' => $p,
|
||||
'city' => $c,
|
||||
'district' => $d,
|
||||
'lat' => $row['lat'] !== null ? (float)$row['lat'] : null,
|
||||
'lng' => $row['lng'] !== null ? (float)$row['lng'] : null,
|
||||
];
|
||||
}
|
||||
foreach ($rows as $r) {
|
||||
$list[] = [
|
||||
'id' => (int)$r['id'],
|
||||
'province' => (string)$r['province'],
|
||||
'city' => (string)$r['city'],
|
||||
'district' => (string)$r['district'],
|
||||
'lat' => $r['lat'] !== null && $r['lat'] !== '' ? (float)$r['lat'] : null,
|
||||
'lng' => $r['lng'] !== null && $r['lng'] !== '' ? (float)$r['lng'] : null,
|
||||
];
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
// 忽略数据库读取异常,以全国静态字典兜底
|
||||
// 数据库异常返回空
|
||||
}
|
||||
|
||||
self::$allCache = $list;
|
||||
@@ -85,9 +51,6 @@ class NationalArea
|
||||
|
||||
/**
|
||||
* 按区域 ID 查找单条省/市/区县记录
|
||||
*
|
||||
* @param int $areaId 区县ID
|
||||
* @return array|null
|
||||
*/
|
||||
public static function findById($areaId)
|
||||
{
|
||||
@@ -105,11 +68,6 @@ class NationalArea
|
||||
|
||||
/**
|
||||
* 按区县名称(及可选省/市)查找匹配记录
|
||||
*
|
||||
* @param string $district 区县名称
|
||||
* @param string $city 可选城市名称
|
||||
* @param string $province 可选省份名称
|
||||
* @return array|null
|
||||
*/
|
||||
public static function findByName($district, $city = '', $province = '')
|
||||
{
|
||||
@@ -134,55 +92,71 @@ class NationalArea
|
||||
}
|
||||
|
||||
/**
|
||||
* 按经纬度坐标(gcj02)匹配最近的全国区县
|
||||
*
|
||||
* @param float $lat 纬度
|
||||
* @param float $lng 经度
|
||||
* @return array|null {areaId, province, city, district, distance}
|
||||
* 清内存缓存
|
||||
*/
|
||||
public static function locate($lat, $lng)
|
||||
public static function invalidate()
|
||||
{
|
||||
$best = null;
|
||||
foreach (self::all() as $row) {
|
||||
if ($row['lat'] === null || $row['lng'] === null) {
|
||||
continue;
|
||||
}
|
||||
$dist = self::haversine($lat, $lng, (float)$row['lat'], (float)$row['lng']);
|
||||
if ($best === null || $dist < $best['distance']) {
|
||||
$best = ['row' => $row, 'distance' => $dist];
|
||||
}
|
||||
}
|
||||
if (!$best || $best['distance'] > 1000) {
|
||||
return null;
|
||||
}
|
||||
$area = $best['row'];
|
||||
return [
|
||||
'areaId' => (int)$area['id'],
|
||||
'province' => (string)$area['province'],
|
||||
'city' => (string)$area['city'],
|
||||
'district' => (string)$area['district'],
|
||||
'distance' => $best['distance'],
|
||||
];
|
||||
self::$allCache = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算两点间 Haversine 球面距离(km,保留 1 位小数)
|
||||
* 从 national_areas.json 导入全国默认数据到 fa_fc_area
|
||||
*
|
||||
* @param float $lat1
|
||||
* @param float $lng1
|
||||
* @param float $lat2
|
||||
* @param float $lng2
|
||||
* @return float
|
||||
* 操作:先 TRUNCATE 清空现有覆盖层,再把 json 全量 INSERT 进去,全部 enabled=1。
|
||||
* 相当于把"覆盖层"重置为全国默认状态。
|
||||
*
|
||||
* @return int 导入条数
|
||||
*/
|
||||
public static function haversine($lat1, $lng1, $lat2, $lng2)
|
||||
public static function importFromJson()
|
||||
{
|
||||
$earth = 6371.0;
|
||||
$rad = M_PI / 180;
|
||||
$dLat = ($lat2 - $lat1) * $rad;
|
||||
$dLng = ($lng2 - $lng1) * $rad;
|
||||
$a = sin($dLat / 2) * sin($dLat / 2)
|
||||
+ cos($lat1 * $rad) * cos($lat2 * $rad) * sin($dLng / 2) * sin($dLng / 2);
|
||||
$c = 2 * asin(min(1.0, sqrt($a)));
|
||||
return round($earth * $c, 1);
|
||||
$jsonFile = APP_PATH . 'extra' . DS . 'national_areas.json';
|
||||
if (!is_file($jsonFile)) {
|
||||
throw new \RuntimeException('national_areas.json 不存在');
|
||||
}
|
||||
$decoded = json_decode((string)file_get_contents($jsonFile), true);
|
||||
if (!is_array($decoded)) {
|
||||
throw new \RuntimeException('national_areas.json 解析失败');
|
||||
}
|
||||
|
||||
// 清空现有覆盖层
|
||||
Db::execute('TRUNCATE TABLE `' . Db::getConfig('prefix') . 'fc_area`');
|
||||
|
||||
// 按 省→市→区县 自然排序后再入库,保证 id 自增顺序就是行政区顺序
|
||||
usort($decoded, function ($a, $b) {
|
||||
$cmp = strcmp((string)$a['province'], (string)$b['province']);
|
||||
if ($cmp !== 0) return $cmp;
|
||||
$cmp = strcmp((string)$a['city'], (string)$b['city']);
|
||||
if ($cmp !== 0) return $cmp;
|
||||
return strcmp((string)$a['district'], (string)$b['district']);
|
||||
});
|
||||
|
||||
$now = time();
|
||||
$chunk = [];
|
||||
$chunkSize = 200;
|
||||
$sort = 0;
|
||||
foreach ($decoded as $item) {
|
||||
$sort++;
|
||||
$chunk[] = [
|
||||
'province' => (string)$item['province'],
|
||||
'city' => (string)$item['city'],
|
||||
'district' => (string)$item['district'],
|
||||
'lat' => isset($item['lat']) && $item['lat'] !== null ? (float)$item['lat'] : null,
|
||||
'lng' => isset($item['lng']) && $item['lng'] !== null ? (float)$item['lng'] : null,
|
||||
'sort' => $sort,
|
||||
'enabled' => 1,
|
||||
'createtime' => $now,
|
||||
'updatetime' => $now,
|
||||
];
|
||||
if (count($chunk) >= $chunkSize) {
|
||||
Db::name('fc_area')->insertAll($chunk);
|
||||
$chunk = [];
|
||||
}
|
||||
}
|
||||
if (!empty($chunk)) {
|
||||
Db::name('fc_area')->insertAll($chunk);
|
||||
}
|
||||
|
||||
self::invalidate();
|
||||
return count($decoded);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
use OSS\Core\OssException;
|
||||
use OSS\Credentials\StaticCredentialsProvider;
|
||||
use OSS\OssClient;
|
||||
use think\Log;
|
||||
|
||||
/**
|
||||
* 阿里云OSS存储助手
|
||||
*
|
||||
* 开关口径:跟随后台「常规管理 → 插件管理 → alioss」的启用状态;
|
||||
* - 插件启用且 AccessKey/Bucket/Endpoint/CDN 配置完整 → 走云存储;
|
||||
* - 否则一律回落本地存储(public/uploads)。
|
||||
*
|
||||
* 上传策略(与 alioss 插件「服务器中转」模式一致):
|
||||
* 文件先落盘本地,再推送 OSS;推送成功后附件记录 storage=alioss(url 仍存相对路径,
|
||||
* 展示时拼插件配置的 CDN 域名),并根据 serverbackup 配置决定是否保留本地备份;
|
||||
* 推送失败自动回落本地,不阻断业务。
|
||||
*/
|
||||
class OssStorage
|
||||
{
|
||||
/** alioss 插件名 */
|
||||
const ADDON_NAME = 'alioss';
|
||||
|
||||
/** 附件表 storage 字段值(与 alioss 插件口径一致) */
|
||||
const STORAGE_NAME = 'alioss';
|
||||
|
||||
/**
|
||||
* 云存储开关是否开启
|
||||
* 插件启用(info.ini state=1)且核心配置非空才视为开启
|
||||
* @return bool
|
||||
*/
|
||||
public static function enabled()
|
||||
{
|
||||
$config = self::config();
|
||||
if ($config === null) {
|
||||
return false;
|
||||
}
|
||||
return !empty($config['accessKeyId'])
|
||||
&& !empty($config['accessKeySecret'])
|
||||
&& !empty($config['bucket'])
|
||||
&& !empty($config['endpoint'])
|
||||
&& !empty($config['cdnurl'])
|
||||
&& $config['bucket'] !== 'yourbucket';
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取 alioss 插件配置(插件停用或不存在时返回 null)
|
||||
* @return array|null
|
||||
*/
|
||||
protected static function config()
|
||||
{
|
||||
if (!function_exists('get_addon_info') || !function_exists('get_addon_config')) {
|
||||
return null;
|
||||
}
|
||||
$info = get_addon_info(self::ADDON_NAME);
|
||||
if (!$info || empty($info['state'])) {
|
||||
return null;
|
||||
}
|
||||
$config = get_addon_config(self::ADDON_NAME);
|
||||
return $config ?: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造 OssClient(签名V4,与 alioss 插件口径一致)
|
||||
* @return OssClient
|
||||
* @throws OssException
|
||||
*/
|
||||
protected static function client()
|
||||
{
|
||||
$config = self::config();
|
||||
return new OssClient([
|
||||
'accessKeyId' => $config['accessKeyId'],
|
||||
'endpoint' => $config['endpoint'],
|
||||
'bucket' => $config['bucket'],
|
||||
'region' => str_replace('-internal', '', substr(explode('.', $config['endpoint'])[0], 4)),
|
||||
'provider' => new StaticCredentialsProvider($config['accessKeyId'], $config['accessKeySecret']),
|
||||
'signatureVersion' => OssClient::OSS_SIGNATURE_VERSION_V4,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* CDN 域名(带协议,末尾无斜杠),形如 https://bucket.oss-cn-xxx.aliyuncs.com
|
||||
* @return string
|
||||
*/
|
||||
public static function cdnUrl()
|
||||
{
|
||||
$config = self::config();
|
||||
return rtrim((string)($config['cdnurl'] ?? ''), '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* 将已落盘的本地文件推送到 OSS
|
||||
* 对象键 = 去掉首斜杠的相对路径(/uploads/xxx → uploads/xxx),与附件表 url 口径一致
|
||||
* @param string $filePath 本地绝对路径
|
||||
* @param string $relativeUrl 相对URL(形如 /uploads/20261119/xxx.jpg)
|
||||
* @return bool 是否成功(失败写日志并返回 false,由调用方回落本地)
|
||||
*/
|
||||
public static function push($filePath, $relativeUrl)
|
||||
{
|
||||
if (!is_file($filePath)) {
|
||||
Log::write('[OssStorage] 推送OSS失败:本地文件不存在 path=' . $filePath);
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
$config = self::config();
|
||||
self::client()->uploadFile($config['bucket'], ltrim($relativeUrl, '/'), $filePath);
|
||||
return true;
|
||||
} catch (\Exception $e) {
|
||||
Log::write('[OssStorage] 推送OSS失败 url=' . $relativeUrl . ' err=' . $e->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否保留本地备份(对应插件配置「服务器中转模式备份」serverbackup)
|
||||
* @return bool
|
||||
*/
|
||||
public static function keepLocalBackup()
|
||||
{
|
||||
$config = self::config();
|
||||
return !$config || !empty($config['serverbackup']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除 OSS 端对象(失败仅记日志,不抛异常)
|
||||
* @param string $relativeUrl 相对URL(形如 /uploads/20261119/xxx.jpg)
|
||||
* @return bool
|
||||
*/
|
||||
public static function delete($relativeUrl)
|
||||
{
|
||||
try {
|
||||
$config = self::config();
|
||||
self::client()->deleteObject($config['bucket'], ltrim($relativeUrl, '/'));
|
||||
return true;
|
||||
} catch (\Exception $e) {
|
||||
Log::write('[OssStorage] 删除OSS对象失败 url=' . $relativeUrl . ' err=' . $e->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
在新工单中引用
屏蔽一个用户