369 lines
17 KiB
PHP
369 lines
17 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)。
|
||
*/
|
||
/**
|
||
* 加载 img.json(15m44j 改读新格式 + 每次调用重新读文件=懒重载, 不缓存)。
|
||
*
|
||
* 新格式(用户 2026-11-24 定调):
|
||
* api.baseurl / api.key — EasyImages2.0 图床地址+密钥
|
||
* 图像/附件支持.附件支持 — 总开关(false 时整段禁用图片上传)
|
||
* 图像/附件支持.最大图片数量 — 单工单最多几张(默认 3)
|
||
* 图像/附件支持.最大大小 — 单张大小上限, 单位 MB(默认 2)
|
||
* 图像/附件支持.后缀格式 — 允许的后缀数组(默认 ["jpg","jpeg","png"])
|
||
* 模式.type — 留空=图床, GitHub=issue
|
||
* repo.url / Client ID / Client secrets — GitHub OAuth App(issue 集成)
|
||
* webhook_secret — GitHub Webhook 签名密钥(X-Hub-Signature-256)
|
||
*
|
||
* 返回结构(统一):
|
||
* ['type','baseurl','key','easy',
|
||
* 'attach_enabled','max_images','max_size_mb','allowed_exts',
|
||
* 'gh_enabled','gh_repo','gh_client_id','gh_client_secret','gh_webhook_secret']
|
||
* 文件缺失/解析失败 → 全默认值(调用方按"未配置"兜底)。
|
||
*/
|
||
function loadImgJson() {
|
||
// 默认值(文件缺失/解析失败时用)
|
||
$cfg = [
|
||
'type' => '',
|
||
'baseurl' => '',
|
||
'key' => '',
|
||
'easy' => false,
|
||
'attach_enabled' => true,
|
||
'max_images' => 3,
|
||
'max_size_mb' => 2,
|
||
'allowed_exts' => ['jpg', 'jpeg', 'png'],
|
||
// GitHub issue 集成(15m44l 第二批)
|
||
'gh_enabled' => false,
|
||
'gh_repo' => '', // "ypsdf1/caoyuanwiki"
|
||
'gh_client_id' => '',
|
||
'gh_client_secret' => '',
|
||
'gh_webhook_secret' => '',
|
||
];
|
||
$file = __DIR__ . '/img.json';
|
||
if (!is_readable($file)) return $cfg;
|
||
$j = json_decode((string)@file_get_contents($file), true);
|
||
if (!is_array($j)) return $cfg;
|
||
|
||
// 模式.type
|
||
$cfg['type'] = isset($j['模式']['type']) ? trim((string)$j['模式']['type']) : '';
|
||
|
||
// api.baseurl / api.key(新格式:嵌套在 api 对象下;兼容旧格式:顶层 baseurl/key)
|
||
if (isset($j['api']) && is_array($j['api'])) {
|
||
$cfg['baseurl'] = isset($j['api']['baseurl']) ? trim((string)$j['api']['baseurl']) : '';
|
||
$cfg['key'] = isset($j['api']['key']) ? trim((string)$j['api']['key']) : '';
|
||
} else {
|
||
// 兼容旧格式(生产 img.json 还没同步时)
|
||
$cfg['baseurl'] = isset($j['baseurl']) ? trim((string)$j['baseurl']) : '';
|
||
$cfg['key'] = isset($j['key']) ? trim((string)$j['key']) : '';
|
||
}
|
||
|
||
// 图像/附件支持 嵌套对象(新格式);兼容旧格式:顶层布尔
|
||
$attach = $j['图像/附件支持'] ?? null;
|
||
if (is_array($attach)) {
|
||
$cfg['attach_enabled'] = !empty($attach['附件支持']);
|
||
$cfg['max_images'] = isset($attach['最大图片数量']) && is_numeric($attach['最大图片数量']) ? (int)$attach['最大图片数量'] : 3;
|
||
$cfg['max_size_mb'] = isset($attach['最大大小']) && is_numeric($attach['最大大小']) ? (int)$attach['最大大小'] : 2;
|
||
if (isset($attach['后缀格式']) && is_array($attach['后缀格式'])) {
|
||
$cfg['allowed_exts'] = array_map(function($e) { return strtolower(trim((string)$e)); }, $attach['后缀格式']);
|
||
}
|
||
} elseif (is_bool($attach)) {
|
||
// 旧格式:顶层布尔(true/false)
|
||
$cfg['attach_enabled'] = $attach;
|
||
}
|
||
|
||
// easy = 走 EasyImages2.0(有 baseurl+key 且附件支持开)
|
||
// 15m44m 修正:不再被 模式.type=GitHub 压制。type=GitHub 时图床与 issue 同步并存——
|
||
// 图片照走 EasyImages 图床,工单/回复【额外】同步 GitHub issue(用户 2026-11-25 实测反馈:
|
||
// type=GitHub 仍走内置工单不跳授权 → 根因是 easy 被压 + 前端根本没接授权按钮)。
|
||
$cfg['easy'] = ($cfg['baseurl'] !== '' && $cfg['key'] !== '' && $cfg['attach_enabled']);
|
||
|
||
// GitHub issue 集成(15m44m 修正):
|
||
// webhook_secret 挪进 repo 段(用户明令:仓库 img.json 模板里 webhook_secret 塞进 repo 值,
|
||
// 顶层不再放敏感值)。优先读 repo.webhook_secret,兜底读顶层 webhook_secret(兼容旧生产文件)。
|
||
if (isset($j['repo']) && is_array($j['repo'])) {
|
||
$url = isset($j['repo']['url']) ? trim((string)$j['repo']['url']) : '';
|
||
// 从 https://github.com/ypsdf1/caoyuanwiki 提取 owner/name(去掉协议+域名+尾斜杠)
|
||
$repoPath = $url;
|
||
$repoPath = preg_replace('#^https?://#i', '', $repoPath);
|
||
$repoPath = preg_replace('#^github\.com/#i', '', $repoPath);
|
||
$repoPath = trim($repoPath, '/');
|
||
$cfg['gh_repo'] = ($repoPath !== '' && strpos($repoPath, '/') !== false) ? $repoPath : '';
|
||
$cfg['gh_client_id'] = isset($j['repo']['Client ID']) ? trim((string)$j['repo']['Client ID']) : '';
|
||
$cfg['gh_client_secret'] = isset($j['repo']['Client secrets']) ? trim((string)$j['repo']['Client secrets']) : '';
|
||
if (isset($j['repo']['webhook_secret'])) {
|
||
$cfg['gh_webhook_secret'] = trim((string)$j['repo']['webhook_secret']);
|
||
}
|
||
}
|
||
if (!isset($j['repo']['webhook_secret'])) {
|
||
// 兼容旧顶层 webhook_secret(已部署的生产 img.json 可能是旧结构)
|
||
$cfg['gh_webhook_secret'] = isset($j['webhook_secret']) ? trim((string)$j['webhook_secret']) : '';
|
||
}
|
||
// gh_enabled = 模式.type 显式填 GitHub(不再看 repo 段是否填全——模板值/占位值也算已填,
|
||
// 真正缺配置时 gh_* 为空会让 ghSyncCreate 自动跳过,不影响内置工单入库)。
|
||
// 用户手动把 模式.type 改成 GitHub 即启用 issue 同步 + 前端授权按钮。
|
||
$cfg['gh_enabled'] = ($cfg['type'] === 'GitHub');
|
||
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 无效或已过期)'];
|
||
}
|