Files
Sdf1_login/lsky.php
T
ypsdf1 f94e155208 @
15m44j img.json 新格式 + 懒重载 + 修 API 挂起/删图不让提交

用户定调: img.json 格式调整(嵌套 api.baseurl/key + 图像/附件支持.最大图片数量/.最大大小/.后缀格式),
代码读新格式; img.json 懒重载(每次新建工单时增量读); 先取消假定未更改推仓库; 删图后能正常提交。

根因 3 个:
1. API 挂起: 生产 img.json 还是旧格式(baseurl/key 顶层), loadImgJson 按旧路径读 → 但
   easyUploadFile 用新格式路径 api.baseurl 拿不到 → curl 挂起 60s。
2. 删图不让提交: removeTicketImg 用 files.splice 删了数组但 ticketState.files 引用没同步
   (旧代码 splice 后没重新赋值), 提交时 ticketState.files 还残留已删元素。
3. 硬编码 3/2048K/png|jpg: 前端 uploadTicketImage 写死, 后端 uploadTicketFiles 也写死,
   与 img.json 配置不同步。

修 5 处:
1. img.json 本地改新格式(api.baseurl/api.key + 图像/附件支持嵌套), 取消假定未更改, 入库。
2. lsky.php loadImgJson(): 改读新格式 api.baseurl/key + 图像/附件支持.附件支持/.最大图片数量/
   .最大大小/.后缀格式, 兼容旧格式(顶层 baseurl/key + 图像/附件支持布尔); 每次调用重新读文件
   (懒重载, 不缓存); 返回统一结构含 max_images/max_size_mb/allowed_exts/attach_enabled。
3. api/ticket.php: 新增 ticketMaxImages() 读 loadImgJson().max_images; uploadTicketFiles 开头
   调 loadImgJson 懒重载, 按 attach_enabled 决定是否接文件, 按 max_images/max_size_mb/
   allowed_exts 校验; 真实格式(getimagesize)必须在 img.json 允许后缀里。
4. 新增 api/img_cfg.php: 前端 fetch 端点, 返回 {max_images, max_size_mb, allowed_exts,
   attach_enabled} (无 token 校验, 配置非敏感), 每次请求重新读 img.json。
5. player.php: 新增 loadTicketImgCfg() fetch img_cfg.php, uploadTicketImage 前懒重载;
   校验改 ticketImgCfg.max_images/max_size_mb/allowed_exts(不再硬编码 3/2048K);
   removeTicketImg 修 splice 后重新赋值 ticketState.files(同步清数组引用), 删占位符,
   提示"已移除 图片N(剩 M 张可提交)"。

部署清单: img.json(新格式) + lsky.php + api/ticket.php + player.php + api/img_cfg.php(新)。
生产 FTP 推 img.json 新格式(baseurl/key 改 api. 嵌套) + opcache_invalidate.php。
2026-11-24 21:57:56 +08:00

331 lines
15 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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(本期不做)
*
* 返回结构(统一):
* ['type','baseurl','key','easy',
* 'attach_enabled','max_images','max_size_mb','allowed_exts']
* 文件缺失/解析失败 → 全默认值(调用方按"未配置"兜底)。
*/
function loadImgJson() {
// 默认值(文件缺失/解析失败时用)
$cfg = [
'type' => '',
'baseurl' => '',
'key' => '',
'easy' => false,
'attach_enabled' => true,
'max_images' => 3,
'max_size_mb' => 2,
'allowed_exts' => ['jpg', 'jpeg', 'png'],
];
$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(type 非 GitHub 且有 baseurl+key 且附件支持开)
$cfg['easy'] = ($cfg['type'] !== 'GitHub' && $cfg['baseurl'] !== '' && $cfg['key'] !== '' && $cfg['attach_enabled']);
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 无效或已过期)'];
}