Files
FamilyBook/app/Storage/Storage.php
T

273 lines
11 KiB
PHP
Raw Normal View History

<?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() 一致,刻意设计成「本地优先」:
* 从本地搬到云端(或反过来)时,历史文件可能只在一边,
* 本地优先能保证迁移期的老文件照样打得开,也让回滚随时可行。
*/
public static function read(int $familyId, string $key): array
{
$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'];
}
return self::disk($familyId)->get($key);
}
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;
}
}