284 lines
12 KiB
PHP
284 lines
12 KiB
PHP
<?php
|
||
/**
|
||
* 兰空图床(Lsky Pro)API 客户端 —— 工单图片上传专用
|
||
*
|
||
* 接口规格(图床官方 API 文档,站点 https://img.ypshidifu.cn/api/v1/):
|
||
* POST /tokens body {email,password} -> {status, data:{token, expires_at}}
|
||
* POST /upload multipart: file(+strategy_id)
|
||
* Header: Authorization: Bearer <token>
|
||
* -> {status, data:{key,links:{url,html,markdown,...},thumbnail_url,...}}
|
||
*
|
||
* 设计要点:
|
||
* - 凭据在 lsky_keys.php(仓库只有空模板,部署脚本永不上传);
|
||
* - token 有有效期 -> 文件缓存 + 提前 60 秒自动续签 + 上传遇 401 自动强刷重签重试 1 次;
|
||
* - 本文件不含任何敏感值,可入库、可批量部署。
|
||
*
|
||
* ★ 依赖 core.php 的 error()/success()(本文件只被 api/ticket.php 引入,core 必然已加载)。
|
||
*/
|
||
|
||
// 图床前缀白名单:写库前校验图片 URL 只能来自自家图床(防存任意 URL)。
|
||
// 15m44 改为动态:优先读 img.json 的 baseurl 生成前缀,未配置时兜底旧值。
|
||
// normalizeTicketImages / ticketImageUpload 都调 ticketImageAllowedPrefix()。
|
||
if (!defined('LSKY_ALLOWED_HOST_PREFIX')) {
|
||
define('LSKY_ALLOWED_HOST_PREFIX', 'https://img.ypshidifu.cn/');
|
||
}
|
||
|
||
/**
|
||
* 读 img.json 的 EasyImages2.0 配置(baseurl + key + 模式.type)。
|
||
* 返回 ['type'=>''|'GitHub', 'baseurl'=>..., 'key'=>..., 'easy'=>bool]。
|
||
* - type 留空 或 未填 GitHub → 走 EasyImages2.0(图床)
|
||
* - type = GitHub → 走 GitHub issue(本期不实现,返回 easy=false)
|
||
* 文件缺失/解析失败 → 全空(调用方按"未配置"兜底 LSKY_ALLOWED_HOST_PREFIX)。
|
||
*/
|
||
function loadImgJson() {
|
||
$cfg = ['type' => '', 'baseurl' => '', 'key' => ''];
|
||
$file = __DIR__ . '/img.json';
|
||
if (is_readable($file)) {
|
||
$j = json_decode((string)@file_get_contents($file), true);
|
||
if (is_array($j)) {
|
||
// 模式.type: 留空=走图床, GitHub=走 issue(本期不做, 仍回退图床)
|
||
$t = isset($j['模式']['type']) ? trim((string)$j['模式']['type']) : '';
|
||
$cfg['type'] = $t;
|
||
$cfg['baseurl'] = isset($j['baseurl']) ? trim((string)$j['baseurl']) : '';
|
||
$cfg['key'] = isset($j['key']) ? trim((string)$j['key']) : '';
|
||
}
|
||
}
|
||
// easy = 走 EasyImages2.0(type 非 GitHub 且有 baseurl+key)
|
||
$cfg['easy'] = ($cfg['type'] !== 'GitHub' && $cfg['baseurl'] !== '' && $cfg['key'] !== '');
|
||
return $cfg;
|
||
}
|
||
|
||
/**
|
||
* 图床 URL 白名单前缀:按 img.json 的 baseurl 动态生成(图床校验跟随配置)。
|
||
* baseurl 形如 https://img.ypshidifu.cn/(带尾斜杠),直接作为前缀。
|
||
* 未配置 baseurl 时兜底 LSKY_ALLOWED_HOST_PREFIX。
|
||
*/
|
||
function ticketImageAllowedPrefix() {
|
||
$cfg = loadImgJson();
|
||
if ($cfg['baseurl'] !== '') {
|
||
$p = $cfg['baseurl'];
|
||
if (substr($p, -1) !== '/') $p .= '/';
|
||
return $p;
|
||
}
|
||
return LSKY_ALLOWED_HOST_PREFIX;
|
||
}
|
||
|
||
/**
|
||
* EasyImages2.0 图床上传(15m44 引入)。
|
||
* 接口规范(icret/EasyImages2.0 API):
|
||
* POST {baseurl}/api/index.php
|
||
* multipart/form-data: image(文件) + token(key)
|
||
* 成功响应: {result:"success", code:200, url, thumb, srcName, del, message}
|
||
* 凭据在 img.json(baseurl+key),本函数不内置敏感值。
|
||
* 返回 ['ok'=>true,'url'=>..,'thumb'=>..] 或 ['ok'=>false,'msg'=>..]
|
||
*/
|
||
function easyUploadFile($tmpPath, $origName) {
|
||
$cfg = loadImgJson();
|
||
if (!$cfg['easy']) {
|
||
return ['ok' => false, 'msg' => '图床未配置:img.json 缺少 baseurl 或 key(模式.type 留空走图床)'];
|
||
}
|
||
$api = rtrim($cfg['baseurl'], '/') . '/api/index.php';
|
||
$mime = 'application/octet-stream';
|
||
$info = @getimagesize($tmpPath);
|
||
if (!empty($info['mime'])) $mime = (string)$info['mime'];
|
||
if (!function_exists('curl_init')) {
|
||
return ['ok' => false, 'msg' => '服务器缺少 PHP curl 扩展'];
|
||
}
|
||
$ch = curl_init();
|
||
$fields = [
|
||
'image' => new CURLFile($tmpPath, $mime, $origName),
|
||
'token' => $cfg['key'],
|
||
];
|
||
curl_setopt($ch, CURLOPT_URL, $api);
|
||
curl_setopt($ch, CURLOPT_POST, true);
|
||
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); // 数组 -> multipart
|
||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
|
||
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
|
||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
|
||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
|
||
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json']);
|
||
$body = curl_exec($ch);
|
||
$errno = curl_errno($ch);
|
||
$err = curl_error($ch);
|
||
$status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
|
||
curl_close($ch);
|
||
if ($errno) return ['ok' => false, 'msg' => 'cURL错误: ' . $err];
|
||
$j = json_decode((string)$body, true);
|
||
// EasyImages2.0 成功: {result:"success", url:..., thumb:...};失败: {result:"failed", message:...} 或 code!=200
|
||
if ($status >= 200 && $status < 300 && is_array($j)
|
||
&& isset($j['url']) && $j['url'] !== ''
|
||
&& (!isset($j['result']) || $j['result'] === 'success')) {
|
||
$url = (string)$j['url'];
|
||
$thumb = isset($j['thumb']) && $j['thumb'] !== '' ? (string)$j['thumb'] : $url;
|
||
return ['ok' => true, 'url' => $url, 'thumb' => $thumb];
|
||
}
|
||
$msg = (is_array($j) && isset($j['message']) && $j['message'] !== '')
|
||
? (string)$j['message']
|
||
: ('图床响应异常 HTTP ' . $status . ' ' . substr((string)$body, 0, 160));
|
||
return ['ok' => false, 'msg' => $msg];
|
||
}
|
||
|
||
/**
|
||
* 工单图片上传路由(15m44):按 img.json 的 模式.type 选图床。
|
||
* - type 留空(或填了其它非 GitHub 值)→ EasyImages2.0(easyUploadFile)
|
||
* - type = GitHub → 本期不实现,回退 EasyImages2.0(loadImgJson.easy 仍为 true 时);
|
||
* 若 easy 未配置则报"图床未配置"。GitHub issue 上传留后续批次。
|
||
* 返回结构对齐 lskyUploadFile: ['ok','url','thumb'(可选)]。
|
||
*/
|
||
function ticketImageUpload($tmpPath, $origName) {
|
||
$cfg = loadImgJson();
|
||
// 本期只做 EasyImages2.0(用户明令 GitHub issue 先不做)
|
||
if ($cfg['easy']) {
|
||
return easyUploadFile($tmpPath, $origName);
|
||
}
|
||
// easy 未配置且 type 非 GitHub:兜底旧兰空图床(lsky_keys.php 还在时)
|
||
if ($cfg['type'] === '') {
|
||
return lskyUploadFile($tmpPath, $origName);
|
||
}
|
||
return ['ok' => false, 'msg' => '图床未配置:img.json 的 baseurl/key 缺失(GitHub issue 本期未启用)'];
|
||
}
|
||
|
||
/** 加载 lsky_keys.php(只加载一次),并检查必填项 */
|
||
function lskyLoadKeys() {
|
||
static $done = false;
|
||
if ($done) return;
|
||
$file = __DIR__ . '/lsky_keys.php';
|
||
if (!file_exists($file)) {
|
||
error('图床配置缺失:服务器上没有 lsky_keys.php(请参照仓库模板放置)', 500);
|
||
}
|
||
require_once $file;
|
||
$done = true;
|
||
if (!defined('LSKY_API_URL') || !defined('LSKY_EMAIL') || !defined('LSKY_PASSWORD')) {
|
||
error('图床配置不完整:LSKY_API_URL / LSKY_EMAIL / LSKY_PASSWORD 必须定义', 500);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 底层 HTTP(curl)。$isMultipart=true 时 $payload 直接作为 CURLOPT_POSTFIELDS 数组
|
||
* (boundary 交给 curl 自动处理,切勿手写 Content-Type)。
|
||
* 返回 ['ok','status','msg','data']。
|
||
*/
|
||
function lskyCurlJson($method, $url, $payload = null, $token = null, $isMultipart = false) {
|
||
if (!function_exists('curl_init')) {
|
||
return ['ok' => false, 'status' => 0, 'msg' => '服务器缺少 PHP curl 扩展', 'data' => null];
|
||
}
|
||
$ch = curl_init();
|
||
curl_setopt($ch, CURLOPT_URL, $url);
|
||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
|
||
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
|
||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
|
||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
|
||
|
||
$headers = ['Accept: application/json'];
|
||
if ($token !== null && $token !== '') $headers[] = 'Authorization: Bearer ' . $token;
|
||
|
||
if ($method === 'POST') {
|
||
curl_setopt($ch, CURLOPT_POST, true);
|
||
if ($isMultipart) {
|
||
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); // 数组 -> multipart
|
||
} else {
|
||
$json = json_encode($payload === null ? new stdClass() : $payload);
|
||
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
|
||
$headers[] = 'Content-Type: application/json';
|
||
}
|
||
} else {
|
||
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
|
||
}
|
||
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
|
||
|
||
$body = curl_exec($ch);
|
||
$errno = curl_errno($ch);
|
||
$err = curl_error($ch);
|
||
$status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
|
||
curl_close($ch);
|
||
|
||
if ($errno) {
|
||
return ['ok' => false, 'status' => 0, 'msg' => 'cURL错误: ' . $err, 'data' => null];
|
||
}
|
||
$j = json_decode((string)$body, true);
|
||
return [
|
||
'ok' => ($status >= 200 && $status < 300),
|
||
'status' => $status,
|
||
'msg' => (is_array($j) && isset($j['message']) && $j['message'] !== '')
|
||
? (string)$j['message']
|
||
: ('HTTP ' . $status . ' ' . substr((string)$body, 0, 160)),
|
||
'data' => (is_array($j) && isset($j['data']) && is_array($j['data'])) ? $j['data'] : null,
|
||
];
|
||
}
|
||
|
||
/**
|
||
* 获取 API token:缓存优先(提前 60 秒过期),失效则 POST /tokens 续签并落盘。
|
||
* 续签失败但缓存里还有旧 token 时返回旧 token(图床临时抖动不至于让上传全挂)。
|
||
*/
|
||
function lskyGetToken($force = false) {
|
||
lskyLoadKeys();
|
||
$cache = defined('LSKY_TOKEN_CACHE') ? LSKY_TOKEN_CACHE : (__DIR__ . '/db/lsky_token.json');
|
||
$cached = null;
|
||
if (!$force && is_readable($cache)) {
|
||
$cached = json_decode((string)@file_get_contents($cache), true);
|
||
if (is_array($cached) && !empty($cached['token'])
|
||
&& isset($cached['expire_at']) && time() < (int)$cached['expire_at'] - 60) {
|
||
return $cached['token'];
|
||
}
|
||
}
|
||
$r = lskyCurlJson('POST', rtrim(LSKY_API_URL, '/') . '/tokens',
|
||
['email' => LSKY_EMAIL, 'password' => LSKY_PASSWORD]);
|
||
if ($r['ok'] && !empty($r['data']['token'])) {
|
||
$token = (string)$r['data']['token'];
|
||
$expire = time() + 3600; // 响应没有 expires_at 时按 1 小时兜底
|
||
if (!empty($r['data']['expires_at'])) {
|
||
$ts = strtotime((string)$r['data']['expires_at']);
|
||
if ($ts !== false && $ts > time()) $expire = $ts;
|
||
}
|
||
$dir = dirname($cache);
|
||
if (!is_dir($dir)) @mkdir($dir, 0755, true);
|
||
@file_put_contents($cache,
|
||
json_encode(['token' => $token, 'expire_at' => $expire, 'cached_at' => time()]),
|
||
LOCK_EX);
|
||
return $token;
|
||
}
|
||
// 续签失败 -> 旧缓存顶着用
|
||
if (is_array($cached) && !empty($cached['token'])) return $cached['token'];
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* 上传一张已通过校验的图片到图床。
|
||
* 401(token 失效)自动强刷 token 重试 1 次。
|
||
* 成功返回 ['ok'=>true,'url'=>..,'thumb'=>..,'key'=>..],失败 ['ok'=>false,'msg'=>..]
|
||
*/
|
||
function lskyUploadFile($tmpPath, $origName) {
|
||
lskyLoadKeys();
|
||
if (!is_uploaded_file($tmpPath)) {
|
||
return ['ok' => false, 'msg' => '非法上传(is_uploaded_file 校验失败)'];
|
||
}
|
||
$mime = 'application/octet-stream';
|
||
$info = @getimagesize($tmpPath);
|
||
if (!empty($info['mime'])) $mime = (string)$info['mime'];
|
||
|
||
for ($try = 0; $try < 2; $try++) {
|
||
$token = lskyGetToken($try > 0);
|
||
if (!$token) {
|
||
return ['ok' => false, 'msg' => '获取图床 token 失败(请检查 lsky_keys.php 的邮箱密码)'];
|
||
}
|
||
$fields = ['file' => new CURLFile($tmpPath, $mime, $origName)];
|
||
if (defined('LSKY_STRATEGY_ID') && (int)LSKY_STRATEGY_ID > 0) {
|
||
$fields['strategy_id'] = (int)LSKY_STRATEGY_ID;
|
||
}
|
||
$r = lskyCurlJson('POST', rtrim(LSKY_API_URL, '/') . '/upload', $fields, $token, true);
|
||
if ($r['ok'] && !empty($r['data']['links']['url'])) {
|
||
$url = (string)$r['data']['links']['url'];
|
||
$thumb = !empty($r['data']['thumbnail_url']) ? (string)$r['data']['thumbnail_url'] : $url;
|
||
return ['ok' => true, 'url' => $url, 'thumb' => $thumb,
|
||
'key' => isset($r['data']['key']) ? (string)$r['data']['key'] : ''];
|
||
}
|
||
if ($r['status'] !== 401) {
|
||
return ['ok' => false, 'msg' => $r['msg']];
|
||
}
|
||
// 401 -> 第 2 轮由 lskyGetToken(true) 强制续签后重试
|
||
}
|
||
return ['ok' => false, 'msg' => '上传失败(token 无效或已过期)'];
|
||
}
|