用户 2026-11-05:「如果图片是放在本地服务器的…就不管它。
如果是传到 OSS 里面的…就用 OSS 的压缩就行了。」
查证:OSS 图片处理确实存在,取图 URL 加 x-oss-process 即可实时压缩,
原图不动、不占额外存储。
三处改动(缺一个都会出错):
1. OssDriver
- get() 新增 $process 参数
- authorization() 新增 $subresource:x-oss-process 属于子资源,
必须计入 CanonicalizedResource,否则 403 SignatureDoesNotMatch
- URL 拼接带上 ?x-oss-process=...
2. Storage::read()
- 新增 $process,仅当驱动是 oss 时透传
- 本地驱动忽略(用户明确要求「本地不管它」)
- 带 process 时跳过"本地优先"缓存(那个缓存里是原图,
拿原图当压缩版返回等于压缩没生效)
3. media.php
- 新增 ?w= 参数,白名单三档 400/800/1600
- 按尺寸分档缓存到 _proc/<w>/<key>,避免互相覆盖
- 无 w 时行为完全不变(300+ 处既有 img 不受影响)
白名单而非透传的理由:OSS 图片处理按次计费,
放任 ?w= 任意值会让 ?w=1、?w=9999 这类请求把处理次数打上去。
实测(一张 6602 KB 的图):
原图 6602 KB
w=400 26 KB 省 99.6%
w=800 108 KB 省 98%
w=1600 468 KB 省 93%
应用位置(保守,先动最确定的):
_attachments.php 照片墙缩略图 → w=400
trips/show.php 行程题图 → w=1600
下载链接一律不加 w(用户要原文件,不能偷偷降质)
303 lines
12 KiB
PHP
303 lines
12 KiB
PHP
<?php
|
||
/**
|
||
* 存储门面:全站**唯一**的附件读写出口。
|
||
*
|
||
* 三条纪律(照 MovieLog 的教训定,别绕过):
|
||
* ① 数据库只存「相对键」(如 avatars/ab12.jpg),绝不存完整 URL ——
|
||
* 换域名、换桶、换前缀都不用改历史数据。
|
||
* ② 页面绝不手拼路径,一律走 url()。
|
||
* ③ 云端失败**自动回退本地**,绝不因云配置问题丢用户的文件。
|
||
*/
|
||
|
||
declare(strict_types=1);
|
||
|
||
namespace App\Storage;
|
||
|
||
use App\Setting;
|
||
|
||
final class Storage
|
||
{
|
||
public const AVATAR_DIR = 'avatars';
|
||
|
||
/** OSS 默认配置模板 */
|
||
public static function ossDefaults(): array
|
||
{
|
||
return [
|
||
'auth_mode' => 'ak', // ak | ecs_role
|
||
'access_key_id' => '',
|
||
'access_key_secret' => '',
|
||
'bucket' => '',
|
||
'endpoint' => '', // 例:oss-cn-beijing.aliyuncs.com(不带 https://)
|
||
'prefix' => '', // 桶内前缀,一个桶放多个站点时用
|
||
'ram_role_name' => '', // 留空 = 自动取实例绑定的角色
|
||
'custom_domain' => '', // 可选,CDN / 自定义域名
|
||
'internal_endpoint' => '1', // 服务端读取优先走内网
|
||
'https' => '1',
|
||
];
|
||
}
|
||
|
||
// ---------------- 配置读写 ----------------
|
||
|
||
public static function driver(int $familyId): string
|
||
{
|
||
$d = (string)Setting::get($familyId, 'storage_driver', 'local');
|
||
return in_array($d, ['local', 'oss'], true) ? $d : 'local';
|
||
}
|
||
|
||
public static function config(int $familyId): array
|
||
{
|
||
$raw = json_decode((string)Setting::get($familyId, 'storage_config_oss', ''), true);
|
||
$saved = is_array($raw) ? $raw : [];
|
||
return array_merge(self::ossDefaults(), $saved);
|
||
}
|
||
|
||
public static function saveConfig(int $familyId, string $driver, array $oss): void
|
||
{
|
||
$driver = in_array($driver, ['local', 'oss'], true) ? $driver : 'local';
|
||
Setting::set($familyId, 'storage_driver', $driver);
|
||
Setting::set($familyId, 'storage_config_oss',
|
||
json_encode(array_merge(self::ossDefaults(), $oss), JSON_UNESCAPED_UNICODE));
|
||
EcsMeta::clearCache($familyId);
|
||
}
|
||
|
||
/** 配置是否填齐 —— 没填齐就强制退回本地,避免「传到云端、地址却按本地算」的错配 */
|
||
public static function configComplete(int $familyId): bool
|
||
{
|
||
if (self::driver($familyId) !== 'oss') {
|
||
return true;
|
||
}
|
||
$c = self::config($familyId);
|
||
$auth = ($c['auth_mode'] === 'ecs_role')
|
||
|| (trim((string)$c['access_key_id']) !== '' && trim((string)$c['access_key_secret']) !== '');
|
||
return $auth && trim((string)$c['bucket']) !== '' && trim((string)$c['endpoint']) !== '';
|
||
}
|
||
|
||
/** 实际生效的驱动(配置不全时是 local) */
|
||
public static function effectiveDriver(int $familyId): string
|
||
{
|
||
$want = self::driver($familyId);
|
||
if ($want !== 'local' && !self::configComplete($familyId)) {
|
||
return 'local';
|
||
}
|
||
return $want;
|
||
}
|
||
|
||
private static ?StorageDriver $instance = null;
|
||
private static ?int $instanceFor = null;
|
||
|
||
public static function disk(int $familyId): StorageDriver
|
||
{
|
||
$id = self::effectiveDriver($familyId);
|
||
if (self::$instance === null || self::$instanceFor !== $familyId || self::$instance->id() !== $id) {
|
||
self::$instance = $id === 'oss'
|
||
? new OssDriver($familyId, self::config($familyId))
|
||
: new LocalDriver(FB_UPLOADS);
|
||
self::$instanceFor = $familyId;
|
||
}
|
||
return self::$instance;
|
||
}
|
||
|
||
// ---------------- 读写 ----------------
|
||
|
||
/** 存一个上传的文件;云端失败自动回退本地 */
|
||
public static function putFile(int $familyId, string $srcPath, string $key, ?string $mime = null): array
|
||
{
|
||
$disk = self::disk($familyId);
|
||
$r = $disk->putFile($srcPath, $key, $mime);
|
||
if (!empty($r['ok'])) {
|
||
return $r;
|
||
}
|
||
if ($disk->id() !== 'local') {
|
||
$local = new LocalDriver(FB_UPLOADS);
|
||
$l = $local->putFile($srcPath, $key, $mime);
|
||
if (!empty($l['ok'])) {
|
||
return ['ok' => true, 'error' => '', 'note' => '云端上传失败,已自动存到本地:' . $r['error']];
|
||
}
|
||
}
|
||
return $r;
|
||
}
|
||
|
||
public static function putContents(int $familyId, string $binary, string $key, ?string $mime = null): array
|
||
{
|
||
$disk = self::disk($familyId);
|
||
$r = $disk->putContents($binary, $key, $mime);
|
||
if (!empty($r['ok'])) {
|
||
return $r;
|
||
}
|
||
if ($disk->id() !== 'local') {
|
||
$local = new LocalDriver(FB_UPLOADS);
|
||
$l = $local->putContents($binary, $key, $mime);
|
||
if (!empty($l['ok'])) {
|
||
return ['ok' => true, 'error' => '', 'note' => '云端上传失败,已自动存到本地:' . $r['error']];
|
||
}
|
||
}
|
||
return $r;
|
||
}
|
||
|
||
public static function delete(int $familyId, string $key): void
|
||
{
|
||
if ($key === '') {
|
||
return;
|
||
}
|
||
// 两个地方都试一遍:历史文件可能只在本地
|
||
self::disk($familyId)->delete($key);
|
||
if (self::effectiveDriver($familyId) !== 'local') {
|
||
(new LocalDriver(FB_UPLOADS))->delete($key);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 读取内容(代理、导出等场景)。
|
||
*
|
||
* 读取顺序与 exists() 一致,刻意设计成「本地优先」:
|
||
* 从本地搬到云端(或反过来)时,历史文件可能只在一边,
|
||
* 本地优先能保证迁移期的老文件照样打得开,也让回滚随时可行。
|
||
*/
|
||
/**
|
||
* 读一个对象。
|
||
*
|
||
* @param string $process OSS 图片处理参数(如 `image/resize,l_400/quality,q_80`)。
|
||
*
|
||
* 🔴 #56(用户 2026-11-05):「如果图片是放在本地服务器的…就不管它。
|
||
* 如果是传到 OSS 里面的…就用 OSS 的压缩就行了。」
|
||
*
|
||
* ## 两种驱动下的行为
|
||
*
|
||
* | 驱动 | `$process` 非空时 |
|
||
* |---|---|
|
||
* | `oss` | 透传给 `OssDriver::get()` ⇒ OSS 实时压缩 |
|
||
* | `local` | **忽略** —— 本地没有图片处理服务,不该假装有 |
|
||
*
|
||
* ⚠️ 带 `$process` 时**跳过本地缓存**:那个缓存里是**原图**,
|
||
* 拿原图当压缩版返回,等于压缩没生效而且用户以为生效了。
|
||
* (缓存由 media.php 自己按尺寸分目录管理,见那里的说明。)
|
||
*/
|
||
public static function read(int $familyId, string $key, string $process = ''): array
|
||
{
|
||
/* 只有无 process 时才走"本地优先":原图有缓存就直接读,
|
||
省掉整个 OSS round-trip。带 process 的必须去 OSS 要压缩版。 */
|
||
if ($process === '') {
|
||
$local = FB_UPLOADS . '/' . ltrim($key, '/');
|
||
if ($key !== '' && is_file($local)) {
|
||
$body = (string)@file_get_contents($local);
|
||
return ['ok' => true, 'status' => 200, 'headers' => [], 'body' => $body,
|
||
'error' => '', 'from' => 'local'];
|
||
}
|
||
}
|
||
|
||
$disk = self::disk($familyId);
|
||
/* 本地驱动不支持图片处理 ⇒ 忽略 process(用户明确要求"本地不管它") */
|
||
if ($process === '' || $disk->id() !== 'oss') {
|
||
return $disk->get($key);
|
||
}
|
||
return $disk->get($key, [], $process);
|
||
}
|
||
|
||
public static function exists(int $familyId, string $key): bool
|
||
{
|
||
if ($key === '') {
|
||
return false;
|
||
}
|
||
if (is_file(FB_UPLOADS . '/' . $key)) {
|
||
return true; // 本地优先(迁移期两者并存)
|
||
}
|
||
return self::disk($familyId)->exists($key);
|
||
}
|
||
|
||
/**
|
||
* 把刚取到的内容**回写一份到本地磁盘**,给下一次读用。
|
||
*
|
||
* 🔴 v47(用户 2026-10-13):「读书现在还是非常慢,这个问题需要彻底解决。」
|
||
* 实测:书架 35 张封面,每张 0.15~0.53s 去 OSS 取,**每次访问都重新取**。
|
||
* `read()` 本来就是"本地优先",但**只读不写** ⇒ OSS 上那份永远要远程拿。
|
||
* 这里补上"写回",于是第二次起直接命中本地文件(0 次远程调用)。
|
||
*
|
||
* ⚠️ 只给**图片**用(调用方判断)。理由:
|
||
* · 图片是"反复读、几乎不写、内容不变"的典型 —— 缓存收益最大;
|
||
* · 附件/原书文件可能是几十上百 MB,缓存它们会把磁盘吃满,
|
||
* 而且下载本来就是低频、一次性的事,缓存它没有意义。
|
||
*
|
||
* ⚠️ **绝不因为缓存失败而影响这次请求**:磁盘满、权限不对、路径怪,
|
||
* 一律静默跳过 —— 缓存是纯优化,不是功能。
|
||
*
|
||
* @return bool 真的写成功了吗(调用方一般不关心)
|
||
*/
|
||
public static function cacheLocally(string $key, string $binary): bool
|
||
{
|
||
$key = ltrim(str_replace('\\', '/', $key), '/');
|
||
if ($key === '' || $binary === '') {
|
||
return false;
|
||
}
|
||
// 与 media.php 同一条键净化判据:拒绝 `..`、绝对路径、点文件
|
||
if (strpos($key, "\0") !== false || strpos($key, '..') !== false
|
||
|| !preg_match('#^[A-Za-z0-9][A-Za-z0-9._/-]*$#', $key)) {
|
||
return false;
|
||
}
|
||
foreach (explode('/', $key) as $seg) {
|
||
if ($seg === '' || $seg === '.' || $seg[0] === '.') {
|
||
return false;
|
||
}
|
||
}
|
||
$dst = FB_UPLOADS . '/' . $key;
|
||
// 已经有了就不重复写(两个请求同时到也不会互相踩:内容一样)
|
||
if (is_file($dst) && filesize($dst) === strlen($binary)) {
|
||
return true;
|
||
}
|
||
$dir = dirname($dst);
|
||
if (!is_dir($dir)) {
|
||
if (!@mkdir($dir, 0775, true) && !is_dir($dir)) {
|
||
return false;
|
||
}
|
||
}
|
||
// 先写临时文件再 rename:避免"写了一半被另一个请求读到"(读到半张图)
|
||
$tmp = $dst . '.tmp' . getmypid();
|
||
if (@file_put_contents($tmp, $binary) === false) {
|
||
@unlink($tmp);
|
||
return false;
|
||
}
|
||
if (!@rename($tmp, $dst)) {
|
||
@unlink($tmp);
|
||
return false;
|
||
}
|
||
@chmod($dst, 0664);
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* **唯一出口**:把相对键变成可访问地址。
|
||
*
|
||
* ⚠️ 现在一律指向 `media.php` 代理,不再直接给 uploads/ 或 OSS 的地址:
|
||
* · 统一:本地与云端的差别被代理吃掉,前端只认一个地址形态;
|
||
* · 安全:桶可以设成私有、uploads/ 可以整个封死,能否看到附件由**登录态**决定,
|
||
* 而不是"知道文件名就能看";
|
||
* · 标准:Content-Type / 缓存 / 下载头由服务端统一给。
|
||
*
|
||
* 为什么保留这个方法:`media.php` 自己不调它(它用 read() 取字节),
|
||
* 所以不存在自递归;留在这里是为了让"谁想把键变成地址"永远只有一条路。
|
||
*/
|
||
public static function url(int $familyId, ?string $key): string
|
||
{
|
||
$key = trim((string)$key);
|
||
if ($key === '') {
|
||
return asset('/assets/avatar-default.svg');
|
||
}
|
||
if (preg_match('#^https?://#i', $key)) {
|
||
return $key;
|
||
}
|
||
return \media_url($key);
|
||
}
|
||
|
||
/**
|
||
* 直接拿「已保存的 OSS 配置」建一个 OSS 驱动来做连通性诊断。
|
||
*
|
||
* 与 disk() 的区别很重要:disk() 会按 effectiveDriver() 决定用哪个驱动,
|
||
* 当前选的是"本地"时就只会给你 LocalDriver —— 于是**用户没法在切到 OSS 之前
|
||
* 先把 OSS 测通**,只能"先切换、发现不行、再切回来"。这里绕开那个判断。
|
||
*/
|
||
public static function ossDiskForDiagnosis(int $familyId): ?OssDriver
|
||
{
|
||
$cfg = self::config($familyId);
|
||
$driver = new OssDriver($familyId, $cfg);
|
||
return $driver->validateConfig() === '' ? $driver : null;
|
||
}
|
||
} |