feat: 云端图片存储(OSS/COS/七牛)+ 服务端代理读取,并补全文档
新增存储抽象层:图片可存本地或云对象存储,切换存储方式不影响已有图片。
存储层
- lib/storage.php 存储门面:本地优先读取、URL 生成、上传/删除、批量迁移、
服务端读取(storageRead)与访问方式判定(storageAccessMode)
- lib/storage/{local,oss,cos,qiniu}.php 四种后端驱动;http.php 共用 cURL 客户端;
meta.php 实例元数据鉴权(ECS RAM 角色 / CVM CAM 角色,免密钥)
- lib/settings.php 设置读写;云厂商密钥以 enc:v1:gcm 密文落库(db/.settings.key)
- 文件名改为内容指纹(md5 前 12 位_6 位随机[_角色].ext),内容不变则名不变,
因此可下发 immutable 长缓存
两种图片访问方式
- 直连存储:storageUrl() 产出对象存储地址(桶需允许匿名读)
- 服务端代理:media.php 鉴权后由服务器签名读取并同源回吐,桶可保持私有
· 未登录返回 403 纯文本(刻意不用 302,否则 <img> 会拿到一段 HTML)
· 对象键白名单防目录穿越;Content-Type 按扩展名白名单决定 + nosniff(防同源 XSS)
· 透传 If-None-Match / Range,上游 304 直接短路;private + immutable 长缓存
· 鉴权后立即 session_write_close(),避免排他会话锁把并行图片请求串行化
内网 endpoint 判定(修「开了代理后慢到不可用」)
- 内网地址只在与桶同地域的 ECS 上可路由;跨地域时 DNS 能解析但 TCP 连不通,
无脑「内网优先」会让每次读取先白等满一次连接超时(默认 10 秒)
- 改为先比本机 ECS 地域与桶地域(零成本、结论确定)→ 不同即跳过;
结论落缓存;内网只给 2 秒连接超时,传输层失败立刻标记且短期内不再重试
- 「测试连通性」升级为 PUT → GET 回读 → DELETE,并显式报出内网判定结论
界面与页面
- settings.php 系统设置页:驱动选择、各云配置、图片访问方式、连接测试、迁移进度
- storage_api.php 提供 stat / migrate / test 三个 JSON 接口
- detail / edit / annual_report / persons 原先直接拼本地路径(file_exists / '/'.$path),
迁云后会整块不渲染或 404,统一改为走存储门面
- js/main.js 增加破图占位兜底;config.php 统一下发 Referrer-Policy: same-origin
文档
- README 新增《图片存储与对象存储》整章:设计约定、两种访问方式取舍表、
直连存储逐项配置说明(桶 ACL / 防盗链白名单 / 跨域 CORS 与 crossorigin /
强制下载 / endpoint 地域 / 自定义域名)与上线检查清单、服务端代理实现要点、
迁移步骤、12 条踩坑记录、可直接复制的排障命令手册
This commit is contained in:
@@ -0,0 +1,228 @@
|
||||
<?php
|
||||
// ============================================
|
||||
// 文件: lib/storage/cos.php
|
||||
// 说明: 腾讯云 COS 驱动
|
||||
// 签名算法:COS 签名 V5(q-sign-algorithm=sha1)
|
||||
// 鉴权方式:SecretId/SecretKey 或 CVM CAM 角色(实例元数据,免密钥)
|
||||
// ============================================
|
||||
|
||||
class StorageCos {
|
||||
|
||||
private $cfg;
|
||||
private $cred = null;
|
||||
|
||||
public function __construct(array $cfg) {
|
||||
$this->cfg = $cfg;
|
||||
}
|
||||
|
||||
public function id() { return 'cos'; }
|
||||
|
||||
public function label() { return '腾讯云 COS'; }
|
||||
|
||||
// ---------- 凭据 ----------
|
||||
|
||||
private function credentials() {
|
||||
if ($this->cred !== null) return $this->cred;
|
||||
|
||||
if (($this->cfg['auth_mode'] ?? 'ak') === 'cvm_role') {
|
||||
$c = tencentCvmCamCredentials($this->cfg['cam_role_name'] ?? '');
|
||||
if (empty($c['ok'])) return $this->cred = ['ok' => false, 'error' => $c['error']];
|
||||
return $this->cred = $c;
|
||||
}
|
||||
|
||||
if (trim((string)($this->cfg['secret_id'] ?? '')) === ''
|
||||
|| trim((string)($this->cfg['secret_key'] ?? '')) === '') {
|
||||
return $this->cred = ['ok' => false, 'error' => '未填写 SecretId / SecretKey'];
|
||||
}
|
||||
return $this->cred = [
|
||||
'ok' => true,
|
||||
'id' => trim($this->cfg['secret_id']),
|
||||
'secret' => trim($this->cfg['secret_key']),
|
||||
'token' => '',
|
||||
'error' => '',
|
||||
];
|
||||
}
|
||||
|
||||
// ---------- 寻址 ----------
|
||||
|
||||
private function useHttps() {
|
||||
return ($this->cfg['https'] ?? '1') === '1';
|
||||
}
|
||||
|
||||
private function scheme() {
|
||||
return $this->useHttps() ? 'https' : 'http';
|
||||
}
|
||||
|
||||
private function host() {
|
||||
return trim((string)$this->cfg['bucket']) . '.cos.' . trim((string)$this->cfg['region']) . '.myqcloud.com';
|
||||
}
|
||||
|
||||
// 给对象键加上「对象前缀」(桶内目录)。库中始终存不带前缀的相对键,
|
||||
// 前缀只在驱动层拼接,因此改前缀不影响数据库里的历史记录。
|
||||
private function objectKey($key) {
|
||||
$key = ltrim((string)$key, '/');
|
||||
$prefix = trim((string)($this->cfg['prefix'] ?? ''), '/');
|
||||
return $prefix === '' ? $key : $prefix . '/' . $key;
|
||||
}
|
||||
|
||||
private function pathOf($key) {
|
||||
return '/' . storageEncodeKey(ltrim((string)$key, '/'));
|
||||
}
|
||||
|
||||
private function objectUrl($key) {
|
||||
return $this->scheme() . '://' . $this->host() . $this->pathOf($key);
|
||||
}
|
||||
|
||||
public function url($key) {
|
||||
$key = $this->objectKey($key);
|
||||
$custom = trim((string)($this->cfg['custom_domain'] ?? ''));
|
||||
if ($custom !== '') {
|
||||
return storageHostOf($custom, $this->useHttps()) . '/' . storageEncodeKey($key);
|
||||
}
|
||||
return $this->scheme() . '://' . $this->host() . '/' . storageEncodeKey($key);
|
||||
}
|
||||
|
||||
// ---------- 签名 V5 ----------
|
||||
|
||||
private function authorization($method, $path, $cred) {
|
||||
$signTime = (time() - 60) . ';' . (time() + 3600);
|
||||
|
||||
// 参与签名的请求头(键必须小写并按字典序排列)
|
||||
$headers = ['host' => $this->host()];
|
||||
if (($cred['token'] ?? '') !== '') {
|
||||
$headers['x-cos-security-token'] = $cred['token'];
|
||||
}
|
||||
ksort($headers);
|
||||
|
||||
$headerPairs = [];
|
||||
$headerNames = [];
|
||||
foreach ($headers as $k => $v) {
|
||||
$headerNames[] = $k;
|
||||
$headerPairs[] = $k . '=' . rawurlencode($v);
|
||||
}
|
||||
$httpHeaders = implode('&', $headerPairs);
|
||||
$headerList = implode(';', $headerNames);
|
||||
|
||||
$httpString = strtolower($method) . "\n"
|
||||
. $path . "\n"
|
||||
. "\n" // 无 URL 参数
|
||||
. $httpHeaders . "\n";
|
||||
|
||||
$stringToSign = "sha1\n" . $signTime . "\n" . sha1($httpString) . "\n";
|
||||
$signKey = hash_hmac('sha1', $signTime, $cred['secret']);
|
||||
$signature = hash_hmac('sha1', $stringToSign, $signKey);
|
||||
|
||||
return [
|
||||
'q-sign-algorithm=sha1',
|
||||
'q-ak=' . $cred['id'],
|
||||
'q-sign-time=' . $signTime,
|
||||
'q-key-time=' . $signTime,
|
||||
'q-header-list=' . $headerList,
|
||||
'q-url-param-list=',
|
||||
'q-signature=' . $signature,
|
||||
];
|
||||
}
|
||||
|
||||
private function buildHeaders($method, $key, $contentType, $cred) {
|
||||
$path = $this->pathOf($key);
|
||||
$parts = $this->authorization($method, $path, $cred);
|
||||
$headers = ['Authorization: ' . implode('&', $parts)];
|
||||
if ($contentType !== '') {
|
||||
$headers[] = 'Content-Type: ' . $contentType;
|
||||
}
|
||||
if (($cred['token'] ?? '') !== '') {
|
||||
$headers[] = 'x-cos-security-token: ' . $cred['token'];
|
||||
}
|
||||
return $headers;
|
||||
}
|
||||
|
||||
private function validateConfig() {
|
||||
foreach (['bucket' => '存储桶名称(含 APPID)', 'region' => '地域 Region'] as $f => $label) {
|
||||
if (trim((string)($this->cfg[$f] ?? '')) === '') {
|
||||
return "未填写{$label}";
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
// ---------- 操作 ----------
|
||||
|
||||
public function putFile($srcPath, $key, $mime = null) {
|
||||
return $this->putContents(file_get_contents($srcPath), $key, $mime ?: 'application/octet-stream');
|
||||
}
|
||||
|
||||
public function putContents($binary, $key, $mime = null) {
|
||||
if ($err = $this->validateConfig()) return ['ok' => false, 'error' => $err];
|
||||
$cred = $this->credentials();
|
||||
if (empty($cred['ok'])) return ['ok' => false, 'error' => $cred['error']];
|
||||
|
||||
$key = $this->objectKey($key);
|
||||
$mime = $mime ?: 'application/octet-stream';
|
||||
$res = storageHttp('PUT', $this->objectUrl($key),
|
||||
$this->buildHeaders('PUT', $key, $mime, $cred), $binary, 60);
|
||||
|
||||
if (!$res['ok']) {
|
||||
return ['ok' => false, 'error' => '上传到 COS 失败:' . $this->describe($res)];
|
||||
}
|
||||
return ['ok' => true, 'error' => ''];
|
||||
}
|
||||
|
||||
public function delete($key) {
|
||||
$cred = $this->credentials();
|
||||
if (empty($cred['ok'])) return ['ok' => false, 'error' => $cred['error']];
|
||||
|
||||
$key = $this->objectKey($key);
|
||||
$res = storageHttp('DELETE', $this->objectUrl($key),
|
||||
$this->buildHeaders('DELETE', $key, '', $cred), null, 30);
|
||||
|
||||
if (!$res['ok'] && $res['status'] !== 404) {
|
||||
return ['ok' => false, 'error' => '删除 COS 对象失败:' . $this->describe($res)];
|
||||
}
|
||||
return ['ok' => true, 'error' => ''];
|
||||
}
|
||||
|
||||
public function exists($key) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public function test() {
|
||||
if ($err = $this->validateConfig()) return ['ok' => false, 'error' => $err];
|
||||
$cred = $this->credentials();
|
||||
if (empty($cred['ok'])) return ['ok' => false, 'error' => $cred['error']];
|
||||
|
||||
// 探测对象也走前缀,顺便验证前缀目录的写权限
|
||||
$raw = '.movielog-probe/' . date('YmdHis') . '-' . bin2hex(random_bytes(4)) . '.txt';
|
||||
$key = $this->objectKey($raw);
|
||||
$body = 'movielog storage probe ' . date('c');
|
||||
|
||||
$res = storageHttp('PUT', $this->objectUrl($key),
|
||||
$this->buildHeaders('PUT', $key, 'text/plain', $cred), $body, 20);
|
||||
if (!$res['ok']) {
|
||||
return ['ok' => false, 'error' => '写入测试失败:' . $this->describe($res)];
|
||||
}
|
||||
|
||||
$del = $this->delete($raw); // delete() 内部会自行加前缀,故传原始键
|
||||
$mode = ($this->cfg['auth_mode'] ?? 'ak') === 'cvm_role'
|
||||
? 'CVM CAM 角色(免密钥)' : 'SecretId/SecretKey';
|
||||
$prefix = trim((string)($this->cfg['prefix'] ?? ''), '/');
|
||||
|
||||
return [
|
||||
'ok' => true,
|
||||
'error' => '',
|
||||
'message' => "连接成功({$mode})。桶 {$this->cfg['bucket']} 可读写,"
|
||||
. ($prefix !== '' ? "前缀 {$prefix}/," : '')
|
||||
. '测试对象已清理。' . ($del['ok'] ? '' : '(注意:测试对象删除失败,请检查删除权限)'),
|
||||
];
|
||||
}
|
||||
|
||||
private function describe($res) {
|
||||
$body = trim((string)$res['body']);
|
||||
$json = json_decode($body, true);
|
||||
if (is_array($json)) {
|
||||
$code = $json['Code'] ?? '';
|
||||
$msg = $json['Message'] ?? '';
|
||||
if ($code || $msg) return trim("{$code} {$msg}");
|
||||
}
|
||||
return $res['error'];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user