Files
Sdf1_login/lsky.php
T
ypsdf1 0ccaaeecbc 15m44x 图床上传 HTTP/2 PROTOCOL_ERROR 根治: 全仓 curl 强制 HTTP/1.1 + 断流重试
切回图床后报 cURL错误: HTTP/2 stream 1 was not closed cleanly: PROTOCOL_ERROR (err 1)。
根因: PHP cURL 默认 HTTP/2, 经 Cloudflare 边缘节点与 PHP 的 h2 实现偶发互不兼容,
流没干净关闭。
修: ① 全仓 curl(lsky.php 图床上传+通用HTTP / gh_api.php / gh_oauth.php)加
   CURLOPT_HTTP_VERSION=CURL_HTTP_VERSION_1_1 降级 HTTP/1.1 根治; ② 仍断流则
   curl_exec 重试(最多3次)兜底。
2026-11-25 21:44:07 +08:00

465 lines
24 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
* 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' => '',
// 15m44s: GitHub issue label(tag)映射,动作→label 名(可在 img.json repo.tag 配置)
'gh_label_map' => [
'正常关单' => '已完成',
'驳回' => '已驳回',
'已回复' => '已回复',
'撤销' => '已撤销',
'处理中' => '处理中',
],
// ★ 15m44w: GitHub 图片仓(imgrepo)配置——附件走 git 推图仓拿 raw URL,省服务器内存
// (用户定调:GitHub 模式本就是为省内存才做的,附件不走图床 API 而走 git 推仓)
'imgrepo_mode' => 'gh', // 'gh'=git仓模式 | 'img'=图床模式(归一化后)
'imgrepo_owner' => '', // 用户名(owner)
'imgrepo_full' => '', // owner/repo(从仓库地址提取)
'imgrepo_branch' => 'main', // 分支
'imgrepo_token' => '', // key/登录密码(当 PAT 用)
];
$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
// ★ 15m44u 归一化:gh / GH / GitHub / github(含 github-issue 等变体)一律算 GitHub。
// 判定:去掉首尾空格 + 小写后,等于 'github' 或以 'github' 开头,或本身就是 'gh'。
$typeRaw = isset($j['模式']['type']) ? trim((string)$j['模式']['type']) : '';
$typeNorm = strtolower($typeRaw);
$typeNorm = str_replace([' ', '-', '_'], '', $typeNorm); // github-issue / github_issue → githubissue
$cfg['type'] = $typeRaw;
$isGhType = ($typeNorm === 'gh' || $typeNorm === 'github' || strpos($typeNorm, 'github') === 0);
// 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 图床。★ 互斥二选一(用户 2026-11-25 定调):
// - type 留空 → 内置工单 + 附件走图床(easy=true)
// - type=GitHub → 附件全走 GitHub issue,图床关闭(easy=false)
// 两者不并存:选 GitHub 后图床彻底不碰,附件由 ghSyncCreate/ghSyncReply 塞进 issue body。
// ★ 15m44u: 用归一化 $isGhType 判断(gh/GH/GitHub/github 全算),不硬比 'GitHub'。
$cfg['easy'] = (!$isGhType && $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']);
}
// 15m44s: 读 repo.tag(动作→label 名 映射),中文键值。有则覆盖默认。
if (isset($j['repo']['tag']) && is_array($j['repo']['tag'])) {
foreach ($j['repo']['tag'] as $k => $v) {
$k = trim((string)$k);
if ($k !== '') $cfg['gh_label_map'][$k] = trim((string)$v);
}
}
// ★ 15m44w: 读 repo.imgrepo(GitHub 图片仓)—— 附件走 git 推图仓拿 raw URL,省服务器内存。
// 归一化判断 模式 字段:true / gh / GH / GitHub / github / GitHub-issue(不区分大小写)
// → git仓模式(imgrepo_mode='gh');false / img / 图床 / tuchuang → 图床模式('img')。
if (isset($j['repo']['imgrepo']) && is_array($j['repo']['imgrepo'])) {
$ir = $j['repo']['imgrepo'];
$modeRaw = $ir['模式'] ?? null;
// 归一化:布尔 true→'gh',false→'img';字符串去空格/小写/去 -_[],
// 含 github/gh 或等于 gh 算 git仓;含 img/图床/tuchuang/lan/lsky 算图床;缺省按 true 处理
$modeNorm = '';
if (is_bool($modeRaw)) {
$modeNorm = $modeRaw ? 'gh' : 'img';
} else {
$modeNorm = strtolower(trim((string)$modeRaw));
$modeNorm = str_replace([' ', '-', '_', '[', ']'], '', $modeNorm);
}
if ($modeNorm === 'gh' || $modeNorm === 'github' || strpos($modeNorm, 'github') === 0 || $modeNorm === 'true') {
$cfg['imgrepo_mode'] = 'gh';
} elseif ($modeNorm === 'img' || $modeNorm === '图床' || $modeNorm === 'tuchuang' || $modeNorm === 'lan' || $modeNorm === 'lsky' || $modeNorm === 'false' || $modeNorm === '') {
$cfg['imgrepo_mode'] = 'img';
} else {
// 未知值按 git仓模式(用户填 GitHub 变体多)
$cfg['imgrepo_mode'] = 'gh';
}
$cfg['imgrepo_owner'] = trim((string)($ir['用户名'] ?? ''));
$cfg['imgrepo_token'] = trim((string)($ir['key/登录密码'] ?? ''));
$cfg['imgrepo_branch'] = trim((string)($ir['分支'] ?? 'main'));
if ($cfg['imgrepo_branch'] === '') $cfg['imgrepo_branch'] = 'main';
// 仓库地址 https://github.com/owner/name[.git] → 提取 owner/name
$irUrl = trim((string)($ir['仓库地址'] ?? ''));
$irPath = preg_replace('#^https?://#i', '', $irUrl);
$irPath = preg_replace('#^github\.com/#i', '', $irPath);
$irPath = preg_replace('#\.git$#i', '', $irPath);
$irPath = trim($irPath, '/');
$cfg['imgrepo_full'] = (strpos($irPath, '/') !== false) ? $irPath : '';
// 仓库地址有但 owner 没填 → 从仓库地址补 owner
if ($cfg['imgrepo_owner'] === '' && $cfg['imgrepo_full'] !== '') {
$parts = explode('/', $cfg['imgrepo_full']);
$cfg['imgrepo_owner'] = $parts[0];
}
}
}
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(gh/GH/GitHub/github 全算,15m44u)。
// 不再看 repo 段是否填全——模板值/占位值也算已填,真正缺配置时 gh_* 为空会让
// ghSyncCreate 自动跳过,不影响内置工单入库。用户把 模式.type 改成任意 GitHub 写法即启用。
$cfg['gh_type'] = $isGhType;
$cfg['gh_enabled'] = $cfg['gh_type'];
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']);
// ★ 15m44x:强制 HTTP/1.1 + PROTOCOL_ERROR 重试。
// PHP cURL 默认走 HTTP/2,经 Cloudflare 边缘偶发 "HTTP/2 stream 1 was not closed
// cleanly: PROTOCOL_ERROR (err 1)"(CF 与 PHP cURL 的 h2 实现互不兼容)。降级 HTTP/1.1
// 根治;仍偶发则再跑一次(最多 3 次)。
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$body = curl_exec($ch);
$errno = curl_errno($ch);
$err = curl_error($ch);
for ($attempt = 1; $errno !== 0 && $attempt < 3; $attempt++) {
$body = curl_exec($ch);
$errno = curl_errno($ch);
$err = curl_error($ch);
}
$status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
// 15m44w 续5c:删 curl_close(PHP8.5 deprecation 污染响应体), $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();
// 15m44v: 图床可用(baseurl+key 配了真值)就传图床拿真实 URL —— 无论是否 GitHub 模式。
// 旧版(15m44n 互斥铁律)GitHub 模式附件全走 issue 不走图床(easy=false 直接报"图床未配置"),
// 导致 PHP 后台 + GitHub 都只显示文件名。用户 2026-11-25 定调"附件要显示实际图片",
// 故 GitHub 模式附件【也走图床】:传 EasyImages2.0 拿真实 URL,ghSyncCreate 把 URL 用
// markdown 图片语法 ![](url) 嵌进 issue body(GitHub 会把外链图片转存到自家 CDN 正常显示)。
// 只要 baseurl+key 配了(图床可用)就传图床;图床没配才走兜底/报错。
if ($cfg['easy']) {
return easyUploadFile($tmpPath, $origName);
}
// easy=false 但 baseurl/key 配了(GitHub 模式 + 图床可用):也传图床拿 URL
// (loadImgJson 的 easy 在 gh_type 时被置 false,但图床真值仍可传 —— 15m44v 放开)
if ($cfg['baseurl'] !== '' && $cfg['key'] !== '' && $cfg['attach_enabled']) {
return easyUploadFile($tmpPath, $origName);
}
// easy 未配置且非 GitHub(含 gh/GH/GitHub/github 任意写法):兜底旧兰空图床(lsky_keys.php 还在时)
if (!$cfg['gh_type'] && $cfg['type'] === '') {
return lskyUploadFile($tmpPath, $origName);
}
return ['ok' => false, 'msg' => '图床未配置:img.json 的 baseurl/key 缺失(GitHub 模式附件走图床拿 URL 嵌 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);
// ★ 15m44x:强制 HTTP/1.1 + PROTOCOL_ERROR 重试(同上传段,CF h2 互不兼容)
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$body = curl_exec($ch);
$errno = curl_errno($ch);
$err = curl_error($ch);
for ($attempt = 1; $errno !== 0 && $attempt < 3; $attempt++) {
$body = curl_exec($ch);
$errno = curl_errno($ch);
$err = curl_error($ch);
}
$status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
// 15m44w 续5c:删 curl_close(PHP8.5 deprecation 污染响应体)
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 无效或已过期)'];
}