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:
2026-09-21 22:06:02 +08:00
parent dd957d45bd
commit 673a8abf78
21 changed files with 3746 additions and 57 deletions
+228
View File
@@ -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'];
}
}
+145
View File
@@ -0,0 +1,145 @@
<?php
// ============================================
// 文件: lib/storage/http.php
// 说明: 对象存储驱动共用的 HTTP 客户端与签名工具函数
// ============================================
// 该路径是否允许当前请求访问。
//
// 宝塔等环境会给站点加 .user.ini:open_basedir=/站点目录/:/tmp/。
// 此时对 /etc/ssl/... 这类"站外路径"调用 is_file() 会抛
// Warning: is_file(): open_basedir restriction in effect
// 而站点开着 display_errors,警告就会被打进响应体——对返回 JSON 的接口
// 是致命的(前端 JSON.parse 直接失败)。所以探测前先自己判断一遍。
function storagePathAllowed($path) {
$path = str_replace('\\', '/', trim((string)$path));
if ($path === '') return false;
$open = (string)ini_get('open_basedir');
if ($open !== '') {
$allowed = false;
foreach (explode(PATH_SEPARATOR, $open) as $dir) {
$dir = rtrim(str_replace('\\', '/', trim($dir)), '/');
if ($dir === '') continue;
if ($path === $dir || strpos($path, $dir . '/') === 0) {
$allowed = true;
break;
}
}
if (!$allowed) return false;
}
// 仍在允许目录内,也压掉可能的名权限/符号链接警告
return @is_file($path) && @is_readable($path);
}
// 定位系统 CA 证书,供 SSL 校验使用(找不到时返回 null,交由 curl 自行处理)
function storageCaBundle() {
static $ca = false;
if ($ca !== false) return $ca;
$candidates = [
ini_get('curl.cainfo'),
ini_get('openssl.cafile'),
'/etc/ssl/certs/ca-certificates.crt',
'/etc/pki/tls/certs/ca-bundle.crt',
'/etc/ssl/cert.pem',
];
foreach ($candidates as $path) {
if (storagePathAllowed($path)) {
$ca = (string)$path;
return $ca;
}
}
$ca = null;
return $ca;
}
/**
* 发起 HTTP 请求。
*
* @param string $method GET / PUT / POST / DELETE / HEAD
* @param string $url 完整 URL
* @param array $headers 形如 ['Content-Type: image/jpeg', ...]
* @param string|null $body 请求体
* @param int $timeout 总超时(秒)
* @param bool $insecure 是否跳过 SSL 证书校验(默认否)
* @param int|null $connectTimeout 连接阶段超时(秒)。默认由总超时推算;
* 想"快速失败"的地方(比如探测内网 endpoint)显式给一个很小的值。
*
* @return array ['ok'=>bool,'status'=>int,'headers'=>array,'body'=>string,'error'=>string]
*/
function storageHttp($method, $url, array $headers = [], $body = null, $timeout = 30, $insecure = false, $connectTimeout = null) {
$respHeaders = [];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => strtoupper($method),
CURLOPT_HTTPHEADER => $headers,
CURLOPT_CONNECTTIMEOUT => $connectTimeout === null
? min(10, max(3, $timeout))
: max(1, (int)$connectTimeout),
CURLOPT_TIMEOUT => $timeout,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_SSL_VERIFYPEER => !$insecure,
CURLOPT_SSL_VERIFYHOST => $insecure ? 0 : 2,
CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$respHeaders) {
$pos = strpos($line, ':');
if ($pos !== false) {
$name = strtolower(trim(substr($line, 0, $pos)));
$respHeaders[$name] = trim(substr($line, $pos + 1));
}
return strlen($line);
},
]);
$ca = storageCaBundle();
if ($ca && !$insecure) {
curl_setopt($ch, CURLOPT_CAINFO, $ca);
}
if ($body !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
$out = curl_exec($ch);
$err = curl_error($ch);
$errno = curl_errno($ch);
$status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($out === false) {
return [
'ok' => false, 'status' => 0, 'headers' => [],
'body' => '',
'error' => $errno === CURLE_OPERATION_TIMEDOUT
? "请求超时({$timeout}s)"
: "网络错误({$errno}): {$err}",
];
}
return [
'ok' => $status >= 200 && $status < 300,
'status' => $status,
'headers' => $respHeaders,
'body' => $out,
'error' => $status >= 200 && $status < 300 ? '' : "HTTP {$status}",
];
}
// 生成对象的访问 URL(路径部分逐段编码,保留斜杠)
function storageEncodeKey($key) {
$key = ltrim((string)$key, '/');
$segments = explode('/', $key);
return implode('/', array_map('rawurlencode', $segments));
}
// 解析 host 形式:bucket.endpoint 或自定义域名
function storageHostOf($domain, $useHttps = true) {
$domain = preg_replace('#^https?://#i', '', trim((string)$domain));
return ($useHttps ? 'https://' : 'http://') . rtrim($domain, '/');
}
// 统一把失败信息压缩成一行,便于写入设置页展示
function storageShortError($text, $max = 200) {
$text = preg_replace('/\s+/', ' ', trim((string)$text));
return mb_strlen($text, 'UTF-8') > $max ? mb_substr($text, 0, $max, 'UTF-8') . '…' : $text;
}
+118
View File
@@ -0,0 +1,118 @@
<?php
// ============================================
// 文件: lib/storage/local.php
// 说明: 本地硬盘存储驱动(默认,行为与改造前一致)
// ============================================
class StorageLocal {
public function id() { return 'local'; }
public function label() { return '本地硬盘'; }
// 把文件落到站点目录下(先尝试 rename,跨文件系统时退化为 copy+unlink)
public function putFile($srcPath, $key, $mime = null) {
$target = $this->absPath($key);
$dir = dirname($target);
if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
return ['ok' => false, 'error' => "无法创建目录:{$dir}"];
}
if (@rename($srcPath, $target)) {
@chmod($target, 0644);
return ['ok' => true, 'error' => ''];
}
if (@copy($srcPath, $target)) {
@unlink($srcPath);
@chmod($target, 0644);
return ['ok' => true, 'error' => ''];
}
return ['ok' => false, 'error' => "写入文件失败:{$key}(请检查目录权限)"];
}
public function putContents($binary, $key, $mime = null) {
$target = $this->absPath($key);
$dir = dirname($target);
if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
return ['ok' => false, 'error' => "无法创建目录:{$dir}"];
}
if (@file_put_contents($target, $binary) === false) {
return ['ok' => false, 'error' => "写入文件失败:{$key}(请检查目录权限)"];
}
@chmod($target, 0644);
return ['ok' => true, 'error' => ''];
}
public function delete($key) {
$target = $this->absPath($key);
if (is_file($target)) {
return @unlink($target);
}
return true; // 不存在视为成功
}
public function url($key) {
return '/' . ltrim((string)$key, '/');
}
public function exists($key) {
return is_file($this->absPath($key));
}
/**
* 服务端读取对象。本地驱动直接读盘。
* 返回结构与 storageHttp() 同构(etag / last-modified 供 media.php 做 304 判断)。
*/
public function get($key, array $extra = []) {
$abs = $this->absPath($key);
if (!is_file($abs) || !is_readable($abs)) {
return ['ok' => false, 'status' => 404, 'headers' => [], 'body' => '', 'error' => '对象不存在'];
}
$body = @file_get_contents($abs);
if ($body === false) {
return ['ok' => false, 'status' => 500, 'headers' => [], 'body' => '', 'error' => '读取文件失败'];
}
return [
'ok' => true,
'status' => 200,
'headers' => [
'content-type' => storageMimeOfFile($abs),
'content-length' => (string)strlen($body),
'etag' => '"' . md5($body) . '"',
'last-modified' => gmdate('D, d M Y H:i:s \G\M\T', (int)@filemtime($abs)),
],
'body' => $body,
'error' => '',
];
}
public function test() {
// 验证上传目录可写
$probe = UPLOAD_DIR . '.storage_test_' . uniqid();
if (@file_put_contents($probe, 'ok') === false) {
return ['ok' => false, 'error' => '上传目录不可写:' . UPLOAD_DIR];
}
@unlink($probe);
$free = @disk_free_space(ROOT_DIR);
$msg = '本地存储正常,上传目录可写。';
if ($free !== false) {
$msg .= ' 剩余空间 ' . formatBytes($free) . '。';
}
return ['ok' => true, 'error' => '', 'message' => $msg];
}
private function absPath($key) {
return ROOT_DIR . '/' . ltrim((string)$key, '/');
}
}
// 字节数格式化(设置页展示用)
function formatBytes($bytes, $precision = 2) {
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max(0, (float)$bytes);
$i = 0;
while ($bytes >= 1024 && $i < count($units) - 1) {
$bytes /= 1024;
$i++;
}
return round($bytes, $i === 0 ? 0 : $precision) . ' ' . $units[$i];
}
+207
View File
@@ -0,0 +1,207 @@
<?php
// ============================================
// 文件: lib/storage/meta.php
// 说明: 云主机实例元数据鉴权(免密钥访问对象存储)
// - 阿里云 ECS:RAM 角色 → STS 临时凭据
// - 腾讯云 CVM:CAM 角色 → 临时密钥
// 服务器不在对应云上时,元数据地址不可达,会返回明确错误。
// ============================================
// 元数据地址不可达时的超时(秒)——必须短,避免拖慢页面
const STORAGE_META_TIMEOUT = 3;
/**
* 阿里云 ECS:获取 RAM 角色的 STS 临时凭据。
*
* @param string $roleName 指定的 RAM 角色名;留空则自动发现实例绑定的第一个角色
* @param bool $force 忽略缓存强制刷新
* @return array ['ok'=>bool,'id'=>string,'secret'=>string,'token'=>string,'expires'=>int,'error'=>string]
*/
function aliyunEcsRamCredentials($roleName = '', $force = false) {
static $memo = [];
$roleName = trim((string)$roleName);
$memoKey = 'aliyun:' . $roleName;
if (!$force && isset($memo[$memoKey])) return $memo[$memoKey];
// 跨请求缓存(临时凭据有效期通常 >= 1 小时)
if (!$force) {
$cached = getSettingJson('cache_meta_aliyun', []);
if (!empty($cached['expires']) && $cached['expires'] > time() + 300
&& ($cached['role'] ?? '') === $roleName) {
return $memo[$memoKey] = $cached + ['ok' => true, 'error' => ''];
}
}
$base = 'http://100.100.100.200/latest/meta-data/ram/security-credentials/';
// IMDSv2:先取一次性 token(实例关闭 v1 时必须)
$token = '';
$t = storageHttp('PUT', 'http://100.100.100.200/latest/api/token',
['X-aliyun-ecs-metadata-token-ttl-seconds: 21600'], null, STORAGE_META_TIMEOUT);
if ($t['ok'] && trim($t['body']) !== '') {
$token = trim($t['body']);
}
$authHeader = $token !== '' ? ["X-aliyun-ecs-metadata-token: {$token}"] : [];
// 角色名
if ($roleName === '') {
$r = storageHttp('GET', $base, $authHeader, null, STORAGE_META_TIMEOUT);
if (!$r['ok']) {
return $memo[$memoKey] = aliyunMetaFail($r, '无法访问 ECS 元数据服务');
}
$first = trim(strtok($r['body'], "\r\n"));
if ($first === '') {
return $memo[$memoKey] = aliyunMetaFail(null, '该实例未绑定 RAM 角色');
}
$roleName = $first;
}
$r = storageHttp('GET', $base . rawurlencode($roleName), $authHeader, null, STORAGE_META_TIMEOUT);
if (!$r['ok']) {
return $memo[$memoKey] = aliyunMetaFail($r, "获取 RAM 角色 {$roleName} 的临时凭据失败");
}
$json = json_decode($r['body'], true);
if (!is_array($json) || empty($json['AccessKeyId']) || empty($json['AccessKeySecret'])) {
$returned = is_array($json) ? ($json['Code'] ?? '') : '';
return $memo[$memoKey] = aliyunMetaFail(null, '元数据返回内容异常' . ($returned ? "({$returned})" : ''));
}
$expires = !empty($json['Expiration']) ? (int)strtotime($json['Expiration']) : time() + 1800;
$cred = [
'ok' => true,
'id' => (string)$json['AccessKeyId'],
'secret' => (string)$json['AccessKeySecret'],
'token' => (string)($json['SecurityToken'] ?? ''),
'expires' => $expires,
'error' => '',
'role' => $roleName,
];
setSettingJson('cache_meta_aliyun', $cred);
return $memo[$memoKey] = $cred;
}
function aliyunMetaFail($resp, $prefix) {
$detail = $resp === null ? '' : ($resp['error'] ?? '');
return [
'ok' => false, 'id' => '', 'secret' => '', 'token' => '', 'expires' => 0,
'error' => $prefix . ($detail ? ":{$detail}" : '')
. '(请确认服务器位于阿里云 ECS,且实例已绑定 RAM 角色;否则请改用 AccessKey 方式)',
];
}
/**
* 当前 ECS 所在地域 ID(如 cn-qingdao、cn-beijing)。不在阿里云 ECS 上时返回空串。
*
* 用途:判断「内网 endpoint 能不能用」。`oss-<region>-internal.aliyuncs.com`
* **只在与该桶同地域的 ECS 上可路由**;跨地域时 DNS 照常解析(秒回 A 记录)
* 但 TCP 永远连不通,于是每次读取都要先白等一次连接超时——这是「服务端代理
* 慢到不可用」的典型成因。先比地域,可以完全免掉这类探测。
*
* 地域不会变,结果缓存 1 小时。
*
* @param bool $force 忽略缓存强制重取
* @return string 地域 ID,未知时为空串
*/
function aliyunEcsRegion($force = false) {
static $memo = null;
if (!$force && $memo !== null) return $memo;
if (!$force) {
$cached = getSettingJson('cache_ecs_region', []);
if (!empty($cached['expires']) && $cached['expires'] > time()) {
return $memo = (string)($cached['region'] ?? '');
}
}
$r = storageHttp('GET', 'http://100.100.100.200/latest/meta-data/region-id',
[], null, STORAGE_META_TIMEOUT, false, 2);
$region = $r['ok'] ? trim((string)$r['body']) : '';
if ($region !== '' && !preg_match('#^[A-Za-z0-9-]+$#', $region)) $region = '';
setSettingJson('cache_ecs_region', ['region' => $region, 'expires' => time() + 3600]);
return $memo = $region;
}
/**
* 腾讯云 CVM:获取 CAM 角色的临时密钥。
*
* @param string $roleName 指定的 CAM 角色名;留空则自动发现
* @param bool $force 忽略缓存强制刷新
* @return array ['ok'=>bool,'id'=>string,'secret'=>string,'token'=>string,'expires'=>int,'error'=>string]
*/
function tencentCvmCamCredentials($roleName = '', $force = false) {
static $memo = [];
$roleName = trim((string)$roleName);
$memoKey = 'tencent:' . $roleName;
if (!$force && isset($memo[$memoKey])) return $memo[$memoKey];
if (!$force) {
$cached = getSettingJson('cache_meta_tencent', []);
if (!empty($cached['expires']) && $cached['expires'] > time() + 300
&& ($cached['role'] ?? '') === $roleName) {
return $memo[$memoKey] = $cached + ['ok' => true, 'error' => ''];
}
}
// 腾讯云元数据服务需要先获取会话 token
$token = '';
$t = storageHttp('PUT', 'http://metadata.tencentyun.com/latest/api/token',
['X-ttc-metadata-token-ttl-seconds: 21600'], null, STORAGE_META_TIMEOUT);
if ($t['ok'] && trim($t['body']) !== '') {
$token = trim($t['body']);
}
$authHeader = $token !== '' ? ["X-ttc-metadata-token: {$token}"] : [];
$base = 'http://metadata.tencentyun.com/latest/meta-data/cam/security-credentials/';
if ($roleName === '') {
$r = storageHttp('GET', $base, $authHeader, null, STORAGE_META_TIMEOUT);
if (!$r['ok']) {
return $memo[$memoKey] = tencentMetaFail($r, '无法访问 CVM 元数据服务');
}
$first = trim(strtok($r['body'], "\r\n"));
if ($first === '') {
return $memo[$memoKey] = tencentMetaFail(null, '该实例未绑定 CAM 角色');
}
$roleName = $first;
}
$r = storageHttp('GET', $base . rawurlencode($roleName), $authHeader, null, STORAGE_META_TIMEOUT);
if (!$r['ok']) {
return $memo[$memoKey] = tencentMetaFail($r, "获取 CAM 角色 {$roleName} 的临时密钥失败");
}
$json = json_decode($r['body'], true);
if (!is_array($json) || empty($json['TmpSecretId']) || empty($json['TmpSecretKey'])) {
$returned = is_array($json) ? ($json['Code'] ?? '') : '';
return $memo[$memoKey] = tencentMetaFail(null, '元数据返回内容异常' . ($returned ? "({$returned})" : ''));
}
$cred = [
'ok' => true,
'id' => (string)$json['TmpSecretId'],
'secret' => (string)$json['TmpSecretKey'],
'token' => (string)($json['Token'] ?? ''),
'expires' => !empty($json['ExpiredTime']) ? (int)$json['ExpiredTime'] : time() + 1800,
'error' => '',
'role' => $roleName,
];
setSettingJson('cache_meta_tencent', $cred);
return $memo[$memoKey] = $cred;
}
function tencentMetaFail($resp, $prefix) {
$detail = $resp === null ? '' : ($resp['error'] ?? '');
return [
'ok' => false, 'id' => '', 'secret' => '', 'token' => '', 'expires' => 0,
'error' => $prefix . ($detail ? ":{$detail}" : '')
. '(请确认服务器位于腾讯云 CVM,且实例已绑定 CAM 角色;否则请改用 SecretId 方式)',
];
}
// 清除元数据凭据缓存(设置页"重新探测"时使用)
function clearMetaCredentialCache() {
deleteSetting('cache_meta_aliyun');
deleteSetting('cache_meta_tencent');
deleteSetting('cache_ecs_region');
deleteSetting('cache_oss_internal');
}
+427
View File
@@ -0,0 +1,427 @@
<?php
// ============================================
// 文件: lib/storage/oss.php
// 说明: 阿里云 OSS 驱动
// 签名算法:OSS 签名 V1(HMAC-SHA1)
// 鉴权方式:AccessKey 或 ECS RAM 角色(实例元数据,免密钥)
// ============================================
class StorageOss {
private $cfg;
private $cred = null;
public function __construct(array $cfg) {
$this->cfg = $cfg;
}
public function id() { return 'oss'; }
public function label() { return '阿里云 OSS'; }
// ---------- 凭据 ----------
private function credentials() {
if ($this->cred !== null) return $this->cred;
if (($this->cfg['auth_mode'] ?? 'ak') === 'ecs_role') {
$c = aliyunEcsRamCredentials($this->cfg['ram_role_name'] ?? '');
if (empty($c['ok'])) return $this->cred = ['ok' => false, 'error' => $c['error']];
return $this->cred = $c;
}
if (trim((string)($this->cfg['access_key_id'] ?? '')) === ''
|| trim((string)($this->cfg['access_key_secret'] ?? '')) === '') {
return $this->cred = ['ok' => false, 'error' => '未填写 AccessKey ID / AccessKey Secret'];
}
return $this->cred = [
'ok' => true,
'id' => trim($this->cfg['access_key_id']),
'secret' => trim($this->cfg['access_key_secret']),
'token' => '',
'error' => '',
];
}
// ---------- 寻址 ----------
private function useHttps() {
return ($this->cfg['https'] ?? '1') === '1';
}
private function scheme() {
return $this->useHttps() ? 'https' : 'http';
}
private function endpoint() {
return preg_replace('#^https?://#i', '', trim((string)($this->cfg['endpoint'] ?? '')));
}
/**
* 服务端读取时优先使用的内网 endpoint(ECS ↔ OSS 同地域内网流量免费、更快)。
* 只把标准的 `<region>.aliyuncs.com` 推导为 `<region>-internal.aliyuncs.com`;
* 自定义域名 / VPC 域名 / 已是内网域名的一律不猜,返回空串表示"不适用"。
*/
private function internalEndpoint() {
if (($this->cfg['internal_endpoint'] ?? '1') === '0') return '';
$ep = $this->endpoint();
if ($ep === '' || strpos($ep, '-internal.') !== false) return '';
if (preg_match('#^(oss-[a-z0-9-]+)\.aliyuncs\.com$#i', $ep, $m)) {
return $m[1] . '-internal.aliyuncs.com';
}
return '';
}
// 给对象键加上「对象前缀」(桶内目录)。库中始终存不带前缀的相对键,
// 前缀只在驱动层拼接,因此改前缀不影响数据库里的历史记录。
private function objectKey($key) {
$key = ltrim((string)$key, '/');
$prefix = trim((string)($this->cfg['prefix'] ?? ''), '/');
return $prefix === '' ? $key : $prefix . '/' . $key;
}
private function host() {
return trim((string)$this->cfg['bucket']) . '.' . $this->endpoint();
}
private function objectUrl($key) {
return $this->scheme() . '://' . $this->host() . '/' . storageEncodeKey($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);
}
// ---------- 签名 ----------
private function authorization($method, $key, $contentType, $date, $cred) {
$canonicalizedHeaders = '';
if (($cred['token'] ?? '') !== '') {
$canonicalizedHeaders = "x-oss-security-token:{$cred['token']}\n";
}
$canonicalizedResource = '/' . trim((string)$this->cfg['bucket']) . '/' . ltrim((string)$key, '/');
$stringToSign = $method . "\n" // VERB
. "\n" // Content-MD5(未使用)
. $contentType . "\n" // Content-Type
. $date . "\n" // Date
. $canonicalizedHeaders
. $canonicalizedResource;
$signature = base64_encode(hash_hmac('sha1', $stringToSign, $cred['secret'], true));
return 'OSS ' . $cred['id'] . ':' . $signature;
}
private function buildHeaders($method, $key, $contentType, $cred) {
$date = gmdate('D, d M Y H:i:s \G\M\T');
$headers = [
'Date: ' . $date,
'Content-Type: ' . $contentType,
'Authorization: ' . $this->authorization($method, $key, $contentType, $date, $cred),
];
if (($cred['token'] ?? '') !== '') {
$headers[] = 'x-oss-security-token: ' . $cred['token'];
}
return $headers;
}
/**
* GET/HEAD 的请求头。故意**不发送** Content-Type 头(签名串里的 Content-Type 用空串),
* 这是 OSS 签名 V1 对读取类请求的标准做法。
* $extra 里放条件/断点头(If-None-Match、If-Modified-Since、Range)——
* 它们不属于 CanonicalizedOSSHeaders(只有 x-oss-* 才计入),因此不影响签名。
*/
private function readHeaders($key, $cred, array $extra = [], $method = 'GET') {
$date = gmdate('D, d M Y H:i:s \G\M\T');
$headers = [
'Date: ' . $date,
'Authorization: ' . $this->authorization($method, $key, '', $date, $cred),
];
if (($cred['token'] ?? '') !== '') {
$headers[] = 'x-oss-security-token: ' . $cred['token'];
}
foreach ($extra as $h) {
$headers[] = $h;
}
return $headers;
}
// ---------- 内网 endpoint 可用性 ----------
//
// 内网 endpoint(oss-<地域>-internal.aliyuncs.com)只在**与桶同地域**的 ECS 上
// 可路由。跨地域时 DNS 会照常解析出一个 A 记录(解析耗时 ~1ms,看不出异常),
// 但 TCP 连接永远建不起来,只能等满连接超时。若不做判定就无脑"内网优先",
// 每读一张图都要先白等一次超时再回退公网——图片多的页面直接慢到不可用。
// 所以这里先比地域(零成本、结论确定),拿不准才真的探一次,并把结论缓存下来。
/** 桶所在地域(从标准 endpoint 解析);自定义/VPC 域名返回空串。 */
private function bucketRegion() {
if (preg_match('#^oss-([a-z0-9-]+?)(?:-internal)?\.aliyuncs\.com$#i', $this->endpoint(), $m)) {
return strtolower($m[1]);
}
return '';
}
/**
* 探测内网 endpoint 是否可用,并把结论写入缓存。
* @param bool $force 忽略缓存结论重新探测(设置页"测试连通性"用)
* @return array ['ok'=>bool,'reason'=>string]
*/
private function probeInternal($force = false) {
$internal = $this->internalEndpoint();
$out = ['ok' => false, 'reason' => ''];
if ($internal === '') {
return ['ok' => false, 'reason' => '未启用,或 endpoint 不是标准 OSS 域名'];
}
$bucketRegion = $this->bucketRegion();
$ecsRegion = function_exists('aliyunEcsRegion') ? aliyunEcsRegion($force) : '';
if ($bucketRegion !== '' && $ecsRegion !== '' && $bucketRegion !== $ecsRegion) {
// 跨地域:不必探测,内网一定不通
$out['reason'] = "本机在 {$ecsRegion}、桶在 {$bucketRegion},不是同一地域";
} else {
$cred = $this->credentials();
if (empty($cred['ok'])) {
$out['reason'] = '凭据不可用,无法探测';
} else {
// 对桶根发一个签名 HEAD:只要拿到任何 HTTP 状态码就说明内网可路由
// (没有 ListBucket 权限会回 403,但这已经证明网络通)。
$url = $this->scheme() . '://' . trim((string)$this->cfg['bucket']) . '.' . $internal . '/';
$res = storageHttp('HEAD', $url, $this->readHeaders('/', $cred, [], 'HEAD'),
null, 3, false, 2);
$out['ok'] = $res['status'] > 0;
$out['reason'] = $out['ok']
? "内网可达(HTTP {$res['status']})"
: '内网 endpoint 连接失败:' . ($res['error'] ?? '');
}
}
setSettingJson('cache_oss_internal', [
'endpoint' => $internal,
'ok' => $out['ok'] ? 1 : 0,
'reason' => $out['reason'],
'expires' => time() + ($out['ok'] ? 3600 : 1800),
]);
return $out;
}
/** 内网 endpoint 现在能不能用(结论走缓存,不会每个请求都探测)。 */
private function internalUsable() {
$internal = $this->internalEndpoint();
if ($internal === '') return false;
$cache = getSettingJson('cache_oss_internal', []);
if (!empty($cache['expires']) && $cache['expires'] > time()
&& ($cache['endpoint'] ?? '') === $internal) {
return !empty($cache['ok']);
}
return !empty($this->probeInternal()['ok']);
}
/** 内网这次真的连不上 → 立刻记下,半小时内不再重试(避免每张图都白等)。 */
private function markInternalDown($reason) {
if ($this->internalEndpoint() === '') return;
setSettingJson('cache_oss_internal', [
'endpoint' => $this->internalEndpoint(),
'ok' => 0,
'reason' => $reason,
'expires' => time() + 1800,
]);
}
/**
* 供设置页展示:内网 endpoint 的推导结果与可用性判定。
* @param bool $probe 强制重新探测
* @return array ['endpoint'=>string,'ok'=>bool,'reason'=>string]
*/
public function internalStatus($probe = false) {
$internal = $this->internalEndpoint();
if ($internal === '') return ['endpoint' => '', 'ok' => false, 'reason' => ''];
$cache = getSettingJson('cache_oss_internal', []);
$cached = !empty($cache['expires']) && $cache['expires'] > time()
&& ($cache['endpoint'] ?? '') === $internal;
if ($probe || !$cached) {
$r = $this->probeInternal($probe);
return ['endpoint' => $internal, 'ok' => !empty($r['ok']), 'reason' => (string)$r['reason']];
}
return [
'endpoint' => $internal,
'ok' => !empty($cache['ok']),
'reason' => (string)($cache['reason'] ?? ''),
];
}
private function validateConfig() {
foreach (['bucket' => 'Bucket 名称', 'endpoint' => 'Endpoint'] 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' => '上传到 OSS 失败:' . $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' => '删除 OSS 对象失败:' . $this->describe($res)];
}
return ['ok' => true, 'error' => ''];
}
public function exists($key) {
return true; // 远端不做逐次 HEAD 探测,交由页面兜底
}
/**
* 服务端读取对象(供 media.php 代理回吐)。
* 私有桶同样可读——用的是实例角色 / AccessKey 签名,与桶的公共读权限无关。
* $extra 用于透传条件头(If-None-Match / If-Modified-Since)与 Range,实现 304 短路与断点。
* 返回结构与 storageHttp() 同构:['ok','status','headers','body','error']
*/
public function get($key, array $extra = []) {
if ($err = $this->validateConfig()) {
return ['ok' => false, 'status' => 0, 'headers' => [], 'body' => '', 'error' => $err];
}
$cred = $this->credentials();
if (empty($cred['ok'])) {
return ['ok' => false, 'status' => 0, 'headers' => [], 'body' => '', 'error' => $cred['error']];
}
$key = $this->objectKey($key);
$headers = $this->readHeaders($key, $cred, $extra);
// 候选主机:内网优先(同地域内网流量免费、延迟更低),传输层失败再回退公网。
// 内网是否**真的可用**先判定(结论有缓存)——跨地域时内网不可路由,
// 无脑尝试会让每张图先白等一次连接超时。
// Authorization 的 CanonicalizedResource 只含 /bucket/key,与主机无关,故可复用同一组头。
$hosts = [];
$internal = $this->internalEndpoint();
if ($internal !== '' && $this->internalUsable()) $hosts[] = $internal;
$hosts[] = $this->endpoint();
$res = null;
foreach ($hosts as $i => $host) {
$isInternal = ($internal !== '' && $host === $internal);
$url = $this->scheme() . '://' . trim((string)$this->cfg['bucket']) . '.' . $host
. '/' . storageEncodeKey($key);
// 内网只给 2 秒连接超时:万一判定失效,也只损失 2 秒而不是默认的 10 秒
$res = storageHttp('GET', $url, $headers, null, 60, false, $isInternal ? 2 : null);
if ($res['status'] === 0) {
if ($isInternal) {
$this->markInternalDown('连接失败:' . ($res['error'] ?? ''));
}
if (isset($hosts[$i + 1])) continue; // 连不上 → 换下一个主机
}
break;
}
return $res ?: ['ok' => false, 'status' => 0, 'headers' => [], 'body' => '', 'error' => '无法连接 OSS'];
}
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);
$binary = 'movielog storage probe ' . date('c');
$res = storageHttp('PUT', $this->objectUrl($key),
$this->buildHeaders('PUT', $key, 'text/plain', $cred), $binary, 20);
if (!$res['ok']) {
return ['ok' => false, 'error' => '写入测试失败:' . $this->describe($res)];
}
// 回读验证:「服务端代理」模式(media.php)完全依赖这条读取链路,
// 所以测试连通性必须把 GET 也走一遍——写入成功不等于读得回来。
$read = $this->get($raw);
$readErr = '';
if (!$read['ok']) {
$readErr = $this->describe($read);
} elseif (trim((string)$read['body']) !== trim($binary)) {
$readErr = '回读到的内容与写入不一致';
}
$del = $this->delete($raw); // delete() 内部会自行加前缀,故传原始键
$mode = ($this->cfg['auth_mode'] ?? 'ak') === 'ecs_role'
? 'ECS RAM 角色(免密钥)' : 'AccessKey';
$prefix = trim((string)($this->cfg['prefix'] ?? ''), '/');
// 内网 endpoint 的结论要明说:跨地域时它是**静默拖慢**的元凶,
// 不报出来用户根本无从察觉。
$internalNote = '';
if ($this->internalEndpoint() !== '') {
$probe = $this->probeInternal(true);
$internalNote = $probe['ok']
? "服务端读取走内网 {$probe['endpoint']}({$probe['reason']})。"
: '内网 endpoint 已自动跳过(原因:' . $probe['reason'] . '),'
. '读取改走公网 ' . $this->endpoint() . ',功能不受影响。';
}
return [
'ok' => true,
'read_ok' => $readErr === '',
'error' => '',
'message' => "连接成功({$mode})。桶 {$this->cfg['bucket']} 可读写,"
. ($prefix !== '' ? "前缀 {$prefix}/," : '')
. ($readErr === ''
? '服务端读取已验证——可安全启用「服务端代理」访问方式。'
: "但服务端读取失败:{$readErr}(请先排查读取权限,暂不要启用「服务端代理」)。")
. $internalNote
. '测试对象已清理。' . ($del['ok'] ? '' : '(注意:测试对象删除失败,请检查删除权限)'),
];
}
// 把 HTTP 响应压成一句可读的错误
private function describe($res) {
$body = trim((string)$res['body']);
if ($body !== '') {
if (preg_match('#<Message>(.*?)</Message>#s', $body, $m)) {
$code = preg_match('#<Code>(.*?)</Code>#s', $body, $c) ? $c[1] : '';
return trim("{$code} {$m[1]}");
}
if (preg_match('#<Code>(.*?)</Code>#s', $body, $c)) {
return $c[1];
}
}
return $res['error'];
}
}
+194
View File
@@ -0,0 +1,194 @@
<?php
// ============================================
// 文件: lib/storage/qiniu.php
// 说明: 七牛云 Kodo 驱动
// 鉴权:AccessKey / SecretKey 计算上传凭证(HMAC-SHA1 + URL 安全 Base64)
// 注意:七牛不提供云主机元数据鉴权,必须使用密钥;且访问需要绑定域名。
// ============================================
class StorageQiniu {
private $cfg;
public function __construct(array $cfg) {
$this->cfg = $cfg;
}
public function id() { return 'qiniu'; }
public function label() { return '七牛云 Kodo'; }
// ---------- 工具 ----------
// URL 安全 Base64(去掉填充、+→-、/→_)
private function urlsafeB64($data) {
return str_replace(['+', '/'], ['-', '_'], rtrim(base64_encode($data), '='));
}
private function uploadHost() {
$map = [
'z0' => 'upload.qiniup.com',
'z1' => 'upload-z1.qiniup.com',
'z2' => 'upload-z2.qiniup.com',
'na0' => 'upload-na0.qiniup.com',
'as0' => 'upload-as0.qiniup.com',
];
$region = (string)($this->cfg['region'] ?? 'z0');
return $map[$region] ?? $map['z0'];
}
private function scheme() {
return ($this->cfg['https'] ?? '1') === '1' ? 'https' : 'http';
}
// 给对象键加上「对象前缀」(桶内目录)。库中始终存不带前缀的相对键,
// 前缀只在驱动层拼接,因此改前缀不影响数据库里的历史记录。
private function objectKey($key) {
$key = ltrim((string)$key, '/');
$prefix = trim((string)($this->cfg['prefix'] ?? ''), '/');
return $prefix === '' ? $key : $prefix . '/' . $key;
}
private function credentials() {
$ak = trim((string)($this->cfg['access_key'] ?? ''));
$sk = trim((string)($this->cfg['secret_key'] ?? ''));
if ($ak === '' || $sk === '') {
return ['ok' => false, 'error' => '未填写 AccessKey / SecretKey'];
}
return ['ok' => true, 'ak' => $ak, 'sk' => $sk];
}
private function validateConfig() {
foreach (['bucket' => 'Bucket 名称'] as $f => $label) {
if (trim((string)($this->cfg[$f] ?? '')) === '') {
return "未填写{$label}";
}
}
return '';
}
// 生成上传凭证
private function uploadToken($key, $cred) {
$policy = [
'scope' => trim((string)$this->cfg['bucket']) . ':' . ltrim((string)$key, '/'),
'deadline' => time() + 3600,
'insertOnly' => 0,
];
$encoded = $this->urlsafeB64(json_encode($policy, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
$sign = $this->urlsafeB64(hash_hmac('sha1', $encoded, $cred['sk'], true));
return $cred['ak'] . ':' . $sign . ':' . $encoded;
}
// 管理凭证(用于删除)
private function managementAuth($path, $cred) {
$sign = $this->urlsafeB64(hash_hmac('sha1', $path . "\n", $cred['sk'], true));
return 'QBox ' . $cred['ak'] . ':' . $sign;
}
// ---------- 对外地址 ----------
public function url($key) {
$key = ltrim((string)$key, '/');
$domain = trim((string)($this->cfg['custom_domain'] ?? ''));
if ($domain === '') {
return '/' . $key; // 未绑定域名时退回相对路径,避免生成半截 URL
}
return storageHostOf($domain, $this->scheme()) . '/' . storageEncodeKey($this->objectKey($key));
}
// ---------- 操作 ----------
public function putFile($srcPath, $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']];
if (!is_file($srcPath)) return ['ok' => false, 'error' => "源文件不存在:{$srcPath}"];
$key = $this->objectKey($key);
$post = [
'token' => $this->uploadToken($key, $cred),
'key' => $key,
'file' => new CURLFile($srcPath, $mime ?: 'application/octet-stream', basename($key)),
];
$res = storageHttp('POST', $this->scheme() . '://' . $this->uploadHost() . '/',
['Expect:'], $post, 90);
return $this->interpretUpload($res);
}
public function putContents($binary, $key, $mime = null) {
$tmp = tempnam(sys_get_temp_dir(), 'qn');
if ($tmp === false || file_put_contents($tmp, $binary) === false) {
return ['ok' => false, 'error' => '无法创建临时文件'];
}
$result = $this->putFile($tmp, $key, $mime);
@unlink($tmp);
return $result;
}
public function delete($key) {
$cred = $this->credentials();
if (empty($cred['ok'])) return ['ok' => false, 'error' => $cred['error']];
$entry = $this->urlsafeB64(trim((string)$this->cfg['bucket']) . ':' . $this->objectKey($key));
$path = '/delete/' . $entry;
$res = storageHttp('POST', $this->scheme() . '://rs.qiniup.com' . $path,
['Authorization: ' . $this->managementAuth($path, $cred)], null, 30);
if (!$res['ok'] && $res['status'] !== 612) { // 612 = 资源不存在
return ['ok' => false, 'error' => '删除七牛对象失败:' . $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']];
if (trim((string)($this->cfg['custom_domain'] ?? '')) === '') {
return ['ok' => false, 'error' => '未填写绑定域名——七牛云必须绑定域名后才能对外访问图片'];
}
$key = '.movielog-probe/' . date('YmdHis') . '-' . bin2hex(random_bytes(4)) . '.txt';
$tmp = tempnam(sys_get_temp_dir(), 'qn');
file_put_contents($tmp, 'movielog storage probe ' . date('c'));
$up = $this->putFile($tmp, $key, 'text/plain');
@unlink($tmp);
if (empty($up['ok'])) return $up;
$del = $this->delete($key);
$prefix = trim((string)($this->cfg['prefix'] ?? ''), '/');
return [
'ok' => true,
'error' => '',
'message' => "连接成功(AccessKey/SecretKey)。空间 {$this->cfg['bucket']} 可上传,"
. ($prefix !== '' ? "前缀 {$prefix}/," : '')
. '测试对象已清理。' . ($del['ok'] ? '' : '(注意:测试对象删除失败,请检查删除权限)'),
];
}
// ---------- 响应解析 ----------
private function interpretUpload($res) {
$json = json_decode((string)$res['body'], true);
if (is_array($json) && !empty($json['key'])) {
return ['ok' => true, 'error' => ''];
}
if (!$res['ok'] || (is_array($json) && isset($json['error']))) {
return ['ok' => false, 'error' => '上传到七牛失败:' . $this->describe($res)];
}
return ['ok' => false, 'error' => '上传到七牛失败:响应异常'];
}
private function describe($res) {
$json = json_decode((string)$res['body'], true);
if (is_array($json) && !empty($json['error'])) {
return (string)$json['error'];
}
return $res['error'];
}
}