Files
Sdf1_login/gh_api.php
T
ypsdf1 626aa72264 15m44w 续2: git 推图改 shell_exec(服务端禁 proc_open 但 exec/shell_exec 可用)
- 用户解封 exec/shell_exec 后, ghImgRepoPushViaGit 原用 proc_open(仍被禁)会失败
- runGit 改 shell_exec: PAT 拼认证 URL, 命令 2>&1 合流+末尾 echo __EXIT__$? 判退出码
- 修闭包内层变量 $full 与外层仓库全名 $full 命名冲突(改 $fullCmd)
- ghGitAvailable(exec git --version) 现 Web PHP exec 已可用→git 分支生效, 不再只靠 Contents API 兜底
2026-11-25 18:03:08 +08:00

627 lines
33 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
/**
* 15m44l 工单第二批:GitHub issue 双向同步 —— 共享 GitHub REST API 客户端 + 同步编排
*
* 职责(本文件不含敏感凭据,全读 img.json):
* - ghApiRequest() : 调 GitHub REST(access_token 走 Authorization: Bearer)
* - ghSyncCreate() : PHP 建工单 → GitHub 建 issue(带 [工单#id] 前缀防循环)
* - ghSyncReply() : PHP 回复工单 → GitHub issue 评论
* - ghHandleWebhook(): GitHub Webhook 事件 → 校验签名 + 识别前缀 + 回推 PHP
*
* 防循环标记:
* - PHP→GitHub 的 issue 标题/评论一律带 "[工单#<id>]" 前缀。
* - GitHub→PHP 的 Webhook 评论若含该前缀 = 我们 PHP 自己推过去的,直接跳过(不回写),
* 避免无限循环;不含前缀 = GitHub 侧真人/机器人评论,回写 web_ticket_replies。
*/
// 防循环前缀(写库/写 GitHub 都用它)
if (!defined('GH_TICKET_PREFIX')) {
define('GH_TICKET_PREFIX', '[工单#'); // 后接 id + "] "
}
// ★ 15m44v: 库文件自失效 —— 每次被 require 时 invalidate 自身 OPcache 副本。
// 部署 gh_api.php 后,只要任一入口(ticket.php/gh_oauth.php)再 require 一次,
// 就强制重读磁盘新版,避免旧版常驻 OPcache 导致新逻辑(占位符替换/ghLog 路径/
// Cache-Control 头)不生效。入口顶部已有 opcache_invalidate(__FILE__),但库文件
// 需自失效自身路径,双保险。
if (function_exists('opcache_invalidate')) { @opcache_invalidate(__FILE__, true); }
/** 取 img.json 的 GitHub 配置(懒重载) */
function ghGetCfg() {
return loadImgJson();
}
/**
* GitHub REST 底层请求。
* @return ['ok'=>bool,'status'=>int,'msg'=>string,'data'=>mixed]
*/
function ghApiRequest($method, $path, $payload = null, $token = null) {
$repo = ghGetCfg()['gh_repo'];
if ($repo === '') return ['ok' => false, 'status' => 0, 'msg' => 'GitHub 仓库未配置(img.json repo.url)', 'data' => null];
$url = 'https://api.github.com' . $path;
if (!function_exists('curl_init')) return ['ok' => false, 'status' => 0, 'msg' => '服务器缺 curl 扩展', 'data' => null];
$ch = curl_init();
$headers = [
'Accept: application/vnd.github+json',
'X-GitHub-Api-Version: 2022-11-28',
'User-Agent: caoyuan-ticket-bot',
// ★ 15m44v: 验活/读操作禁缓存 —— 防止 Cloudflare 边缘缓存 /user 等响应导致
// token 验真误判(失效 token 被 CF 吐旧 200 缓存)。写操作(POST 建单/评论)带
// no-store 无害。
'Cache-Control: no-store',
];
if ($token !== null && $token !== '') $headers[] = 'Authorization: Bearer ' . $token;
if (strtoupper($method) === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
if ($payload !== null) {
$json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$headers[] = 'Content-Type: application/json';
}
} else {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
// ★ 15m44r: 非 POST(PATCH/DELETE 等)若带 payload 也要发 JSON body,
// 旧版只设 CUSTOMREQUEST 不写 PREFEREDFIELDS → PATCH 关单空 body 必 400。
if ($payload !== null) {
$json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$headers[] = 'Content-Type: application/json';
}
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
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 ' . $errno . ': ' . $err, 'data' => null];
$j = json_decode((string)$body, true);
$msg = (is_array($j) && isset($j['message']) && $j['message'] !== '')
? (string)$j['message']
: ('HTTP ' . $status . ' ' . substr((string)$body, 0, 200));
return [
'ok' => ($status >= 200 && $status < 300),
'status' => $status,
'msg' => $msg,
'data' => is_array($j) ? $j : null,
];
}
/** 从 img.json 的 webhook_secret 生成期望的 X-Hub-Signature-256 */
function ghWebhookExpectedSig($rawBody) {
$secret = ghGetCfg()['gh_webhook_secret'];
if ($secret === '') return '';
return 'sha256=' . hash_hmac('sha256', $rawBody, $secret);
}
/** 校验 Webhook 签名(恒时比较防时序攻击)。无 secret 时放行(开发环境)。 */
function ghWebhookVerify($rawBody, $signatureHeader) {
$secret = ghGetCfg()['gh_webhook_secret'];
if ($secret === '') return true; // 未配密钥(开发)放行
$expected = ghWebhookExpectedSig($rawBody);
return hash_equals($expected, (string)$signatureHeader);
}
/**
* PHP 建工单 → GitHub 建 issue。
* 返回 true 成功 / false 失败(调用方非阻塞:失败不影响 PHP 工单入库)。
* issue 标题带前缀 [工单#id] 供 Webhook 识别。
*/
function ghSyncCreate($ticketId, $player, $title, $description, $images = [], $token = '') {
$cfg = ghGetCfg();
if (!$cfg['gh_enabled']) return false;
if ($token === '') {
// 没拿到 access_token(玩家未授权)→ 跳过同步(PHP 工单照常)
ghLog('create issue skipped: no gh token for player ' . $player);
return false;
}
$repo = $cfg['gh_repo'];
$ghTitle = GH_TICKET_PREFIX . $ticketId . '] ' . $title;
// issue body:玩家名 + 描述 + 附件
// - @gh: 开头 = GitHub 模式占位附件(只记文件名,不走图床)→ 显示为「📎 附件:文件名」
// - http(s) = 真实图床外链 → 用 markdown 图片语法
// ★ 15m44q: 服务端把描述里的 [图片N] 占位符就地替换成「📎 附件N」。
// 占位符是前端暂存附件时插进描述的(提交后才在客户端替换),服务端拿到的 description
// 仍带着 [图片N]。旧版 ghSyncCreate 直接把原始描述塞进 issue body,导致 GitHub 上
// 显示「abc[图片1]」占位符没被替换(用户实测附件不对根因)。附件名统一在末尾集中
// 展示一次,描述里的 [图片N] 只标记"此处有附件"不重复展示文件名。
// ★ 15m44v 修:替换串几经踩坑——
// 初版 '\U📎 附件\1\E':\U..\E 是 PCRE【大小写转换开关】(\U=全大写\E=恢复),夹在 emoji 后误转 CJK。
// 二版 '\u📎 附件\1':PHP 单引号里 \u 是【字面 反斜杠+u】(单引号只认 \' 和 \\),
// 传给 PCRE 替换串的 \u = "下个字符转大写"指令,对 emoji 无效→吐出字面 u(issue body 出现 "u 📎 附件1")。
// 终版:替换串不含任何大小写/转义指令,emoji 直接写字面值,只留 \1 反向引用(数字组号)。
// PCRE 替换串里 \1 = 引用捕获组 1(占位符里的数字 N),emoji「📎」直接是普通字符,无副作用。
$desc = (string)$description;
$hasAttach = false;
foreach ((is_array($images) ? $images : []) as $u) {
if (is_string($u)) { $hasAttach = true; break; }
}
if ($hasAttach) {
// ★ 15m44v 终版:替换串用【单引号】'📎 附件\1'。
// - PHP 单引号里 \1 = 字面 反斜杠+1 → 正确传给 PCRE 作反向引用(引用捕获组1=数字N)。
// - 若用双引号 "\U0001F4CE 附件\1":\1 会被 PHP 解析成八进制 0x01 控制字符,
// 且 \U0001F4CE 在 PHP 双引号才是 emoji(单引号不认 \U 转义)——两种引号各有坑。
// - 单引号 + 直接写字面 emoji(文件本身 UTF-8 存 📎)= 最干净,无大小写指令、无八进制误读。
$desc = preg_replace('/\[图片(\d+)\]/u', '📎 附件\1', $desc);
}
// ★ 15m44v: 建单诊断日志(写 /plugin/gh_sync.log),记录替换后描述 + 附件,定位占位符未替换。
ghLog('create ticket=' . $ticketId . ' has_attach=' . ($hasAttach ? 'y' : 'n')
. ' desc_len=' . mb_strlen($desc)
. ' desc_head=' . mb_substr($desc, 0, 80)
. ' imgs=' . json_encode($images, JSON_UNESCAPED_UNICODE));
$bodyParts = ['玩家:`' . $player . '`', ''];
if ($desc !== '') $bodyParts[] = $desc;
if (is_array($images) && count($images) > 0) {
$bodyParts[] = '';
foreach ($images as $i => $u) {
if (is_string($u) && strpos($u, '@gh:') === 0) {
// @gh:附件图N:文件名(图床没配时的回退占位)→ 只显示文件名,让玩家去 GitHub 传原图
$label = str_replace('@gh:', '', $u);
$bodyParts[] = '📎 附件' . ($i + 1) . ':`' . $label . '`(需在 GitHub issue 上传原图)';
} elseif (is_string($u) && (strpos($u, 'http://') === 0 || strpos($u, 'https://') === 0)) {
// ★ 15m44v: 真实图床 URL → markdown 图片语法嵌进 issue body。
// GitHub 会把 ![](外链) 的图片自动转存到 user-images.githubusercontent.com CDN,
// issue 页正常显示实际图片(不再只是文件名)。
$bodyParts[] = '附件' . ($i + 1) . ':' . "\n" . '![' . $u . '](' . $u . ')';
} else {
$bodyParts[] = '附件图' . ($i + 1) . ':' . $u;
}
}
}
$payload = ['title' => mb_substr($ghTitle, 0, 100), 'body' => implode("\n", $bodyParts)];
$r = ghApiRequest('POST', '/repos/' . $repo . '/issues', $payload, $token);
if (!$r['ok'] || !is_array($r['data']) || empty($r['data']['number'])) {
ghLog('create issue failed: ' . $r['msg']);
return false;
}
$issueNo = (string)$r['data']['number'];
// 回写 gh_issue_number(老库先确保列存在)
try {
$db = getDB();
try { $db->exec("ALTER TABLE web_tickets ADD COLUMN gh_issue_number TEXT DEFAULT ''"); } catch (\Throwable $e) { /* 列已存在 */ }
$st = $db->prepare("UPDATE web_tickets SET gh_issue_number = :n WHERE id = :id");
$st->bindValue(':n', $issueNo, SQLITE3_TEXT);
$st->bindValue(':id', $ticketId, SQLITE3_INTEGER);
$st->execute();
} catch (\Throwable $e) { ghLog('write gh_issue_number: ' . $e->getMessage()); }
return true;
}
/**
* PHP 回复工单 → GitHub issue 评论。
* 评论正文带前缀 [工单#id] 防 Webhook 回推循环。
*/
function ghSyncReply($ticketId, $message, $token, $sender) {
$cfg = ghGetCfg();
if (!$cfg['gh_enabled']) return false;
if ($token === '') return false;
$repo = $cfg['gh_repo'];
// 先查 gh_issue_number
try {
$db = getDB();
$st = $db->prepare("SELECT gh_issue_number FROM web_tickets WHERE id = :id");
$st->bindValue(':id', $ticketId, SQLITE3_INTEGER);
$row = $st->execute()->fetchArray(SQLITE3_ASSOC);
if (!$row || empty($row['gh_issue_number'])) {
// 该工单没对应 GitHub issue(未同步)→ 不评论
return false;
}
$issueNo = (string)$row['gh_issue_number'];
} catch (\Throwable $e) {
ghLog('read gh_issue_number: ' . $e->getMessage());
return false;
}
// 评论带前缀 + 角色标记(Webhook 识别前缀跳过;角色标记供 UI 区分 玩家/管理/服务商)
$body = GH_TICKET_PREFIX . $ticketId . '][' . $sender . '] ' . $message;
$r = ghApiRequest('POST', '/repos/' . $repo . '/issues/' . $issueNo . '/comments', ['body' => $body], $token);
if (!$r['ok']) ghLog('issue comment failed: ' . $r['msg']);
return $r['ok'];
}
/** 取工单对应的 GitHub issue 号(无则返回 '') */
function ghTicketIssueNumber($ticketId) {
try {
$db = getDB();
$st = $db->prepare("SELECT gh_issue_number FROM web_tickets WHERE id = :id");
$st->bindValue(':id', (int)$ticketId, SQLITE3_INTEGER);
$row = $st->execute()->fetchArray(SQLITE3_ASSOC);
return ($row && !empty($row['gh_issue_number'])) ? (string)$row['gh_issue_number'] : '';
} catch (\Throwable $e) {
return '';
}
}
/**
* 15m44o: PHP 完结/驳回 → GitHub 关 issue(+ 一条状态说明评论)。
* $kind: 'completed'(完结)| 'rejected'(驳回)。带前缀防 Webhook 循环。
*/
function ghSyncClose($ticketId, $kind, $token, $sender = 'admin') {
$cfg = ghGetCfg();
if (!$cfg['gh_enabled']) return false;
if ($token === '') {
ghLog('close skipped: no token (未授权/无提报玩家 token) ticket=' . $ticketId);
return false;
}
$issueNo = ghTicketIssueNumber($ticketId);
if ($issueNo === '') {
ghLog('close skipped: empty gh_issue_number ticket=' . $ticketId);
return false;
}
$repo = $cfg['gh_repo'];
// ★ 15m44r: 关单不再重复贴「工单已驳回」评论(驳回原因评论已由 ticketReject 的
// ghSyncReply 贴出,完结场景也没有单独原因评论可贴,再贴一条纯属噪音)。
// ★ 15m44p/15m44r: 关 issue 带 state_reason —— 完结→completed(done)/驳回→not_planned。
$stateReason = ($kind === 'rejected') ? 'not_planned' : 'completed';
// 首选专用 /close 路由;若失败(部分新版 OAuth token 该子路由 404/405),
// 退回 canonical PATCH /issues/{n}(state=closed),这是 GitHub 官方推荐的主路径。
$r = ghApiRequest('POST', '/repos/' . $repo . '/issues/' . $issueNo . '/close',
['state' => 'closed', 'state_reason' => $stateReason], $token);
if (!$r['ok']) {
$r2 = ghApiRequest('PATCH', '/repos/' . $repo . '/issues/' . $issueNo,
['state' => 'closed', 'state_reason' => $stateReason], $token);
$via = 'patch';
$r = $r2;
if (!$r2['ok']) {
ghLog('close issue #' . $issueNo . ' FAILED close=' . $r['msg'] . ' patch=' . $r2['msg']);
} else {
ghLog('close issue #' . $issueNo . ' ok via=' . $via . ' kind=' . $kind . ' reason=' . $stateReason . ' status=' . $r['status']);
}
} else {
ghLog('close issue #' . $issueNo . ' ok kind=' . $kind . ' reason=' . $stateReason . ' status=' . $r['status']);
}
return $r['ok'];
}
/**
* 15m44s 新功能:按工单动作给对应 GitHub issue 打 label(从 repo 实际 label 列表取,保证名字存在)。
* $action: 'withdraw'→已撤销 | 'user_reply'→已回复 | 'admin_reply'→处理中
* | 'rejected'→已驳回 | 'completed'→已完成
* 逻辑:拉 /labels 拿 repo 现有 label;命中目标中文名则加;同时把互斥的状态类 label 摘掉
* (例如完结时摘掉 已驳回/已撤销/已回复/处理中,避免一个 issue 挂着多个终态)。
* 非阻塞:失败只 ghLog 不影响主流程。返回 bool(是否成功打上目标 label)。
*/
function ghSyncLabel($ticketId, $action, $token) {
$cfg = ghGetCfg();
if (!$cfg['gh_enabled']) return false;
if ($token === '') { ghLog('label skipped: no token action=' . $action . ' ticket=' . $ticketId); return false; }
$issueNo = ghTicketIssueNumber($ticketId);
if ($issueNo === '') { ghLog('label skipped: empty issue action=' . $action); return false; }
$repo = $cfg['gh_repo'];
// ★ 15m44s: 目标 label 名从 img.json 的 gh_label_map 读(repo.tag 可配),动作→中文 label 名。
// $action: 'withdraw'→撤销 | 'user_reply'→已回复 | 'admin_reply'→处理中
// | 'rejected'→驳回 | 'completed'→正常关单
$map = (isset($cfg['gh_label_map']) && is_array($cfg['gh_label_map'])) ? $cfg['gh_label_map'] : [];
$actionKeyMap = [
'withdraw' => '撤销',
'user_reply' => '已回复',
'admin_reply' => '处理中',
'rejected' => '驳回',
'completed' => '正常关单',
];
$key = isset($actionKeyMap[$action]) ? $actionKeyMap[$action] : '';
$target = (isset($map[$key]) && $map[$key] !== '') ? $map[$key] : '';
if ($target === '') {
// 未配置该动作映射 → 用默认中文 label 名兜底
$defaultMap = ['撤销'=>'已撤销','已回复'=>'已回复','处理中'=>'处理中','驳回'=>'已驳回','正常关单'=>'已完成'];
$target = isset($defaultMap[$key]) ? $defaultMap[$key] : '';
}
if ($target === '') return false;
// 互斥组:状态类 label(打某个时摘掉同组其它),非状态类(如 申诉状)保留
$stateLabels = ['待处理', '处理中', '已回复', '已完成', '已驳回', '已撤销'];
// 拉 repo 现有 label,确认目标 label 存在(不存在则跳过,避免 422)
$lr = ghApiRequest('GET', '/repos/' . $repo . '/labels', null, $token);
$existingNames = [];
if (!empty($lr['ok']) && is_array($lr['data'])) {
foreach ($lr['data'] as $lb) { if (isset($lb['name'])) $existingNames[] = (string)$lb['name']; }
}
if (!in_array($target, $existingNames, true)) {
ghLog('label skipped: target "' . $target . '" not in repo labels action=' . $action);
return false;
}
// 1) 摘掉同组其它 label(先摘后加)
foreach ($stateLabels as $sl) {
if ($sl === $target) continue;
if (in_array($sl, $existingNames, true)) {
ghApiRequest('DELETE', '/repos/' . $repo . '/issues/' . $issueNo . '/labels/' . rawurlencode($sl), null, $token);
}
}
// 2) 加目标 label
$r = ghApiRequest('POST', '/repos/' . $repo . '/issues/' . $issueNo . '/labels', ['labels' => [$target]], $token);
if (!$r['ok']) {
ghLog('label add failed action=' . $action . ' target=' . $target . ': ' . $r['msg']);
} else {
ghLog('label ok action=' . $action . ' target=' . $target . ' issue=' . $issueNo);
}
return $r['ok'];
}
/**
* 处理 GitHub Webhook 事件(gh_webhook.php 调用)。
* 只关心 issue 的 评论 / 关闭 / 重新打开;识别 [工单#id] 前缀定位 PHP 工单,回推 web_ticket_replies。
*/
function ghHandleWebhook($payload, $event) {
$cfg = ghGetCfg();
if (!is_array($payload) || !isset($payload['issue'])) return false;
$issue = $payload['issue'];
$issueNo = isset($issue['number']) ? (int)$issue['number'] : 0;
if ($issueNo <= 0) return false;
// 1) 找 PHP 工单(按 gh_issue_number)
$db = getDB();
try {
$st = $db->prepare("SELECT id, status, requester FROM web_tickets WHERE gh_issue_number = :n LIMIT 1");
$st->bindValue(':n', (string)$issueNo, SQLITE3_TEXT);
$row = $st->execute()->fetchArray(SQLITE3_ASSOC);
} catch (\Throwable $e) {
// 列可能还没建
ghLog('webhook: no gh_issue_number column yet: ' . $e->getMessage());
return false;
}
if (!$row) {
// 这个 issue 不是我们 PHP 工单建的(GitHub 侧独立 issue)→ 不处理
return false;
}
$ticketId = (int)$row['id'];
$status = (string)$row['status'];
// 已关闭的 PHP 工单不再回写
if (in_array($status, ['completed', 'withdrawn', 'rejected'], true)) {
// 但「关闭」事件可以提示:GitHub 侧也关了
if ($event === 'issues' && isset($issue['state']) && $issue['state'] === 'closed') {
ghLog('issue closed on GH for closed ticket #' . $ticketId);
}
return false;
}
if ($event === 'issue_comment' && isset($payload['comment']) && is_array($payload['comment'])) {
$comment = $payload['comment'];
$text = isset($comment['body']) ? (string)$comment['body'] : '';
$author = isset($comment['user']['login']) ? (string)$comment['user']['login'] : 'gh_user';
// 防循环:带 [工单# 前缀 = PHP 推过去的,跳过
if (strpos($text, GH_TICKET_PREFIX) === 0) {
ghLog('skip self-pushed comment on ticket #' . $ticketId);
return false;
}
$now = time();
try {
$ins = $db->prepare("INSERT INTO web_ticket_replies (ticket_id, sender, role, message, created_at) VALUES (:tid, :sender, 'admin', :msg, :now)");
$ins->bindValue(':tid', $ticketId, SQLITE3_INTEGER);
$ins->bindValue(':sender', 'gh:' . $author, SQLITE3_TEXT); // gh: 前缀=GitHub 侧回推
$ins->bindValue(':msg', $text, SQLITE3_TEXT);
$ins->bindValue(':now', $now, SQLITE3_INTEGER);
$ins->execute();
$upd = $db->prepare("UPDATE web_tickets SET status = 'replied', updated_at = :now WHERE id = :id");
$upd->bindValue(':now', $now, SQLITE3_INTEGER);
$upd->bindValue(':id', $ticketId, SQLITE3_INTEGER);
$upd->execute();
} catch (\Throwable $e) {
ghLog('webhook insert reply: ' . $e->getMessage());
return false;
}
return true;
}
// issue 关闭事件:GitHub 侧关闭 issue → 按 state_reason 联动 PHP 状态
// 15m44s 新功能:closed-done(completed) → PHP 已完结;closed-not planned(not_planned) → PHP 已驳回。
if ($event === 'issues' && isset($issue['state']) && $issue['state'] === 'closed') {
$reason = isset($issue['state_reason']) ? (string)$issue['state_reason'] : '';
// 用户定调:done(completed)=已完结;not planned(not_planned)=已驳回;其它/无 reason 默认已完结
$phpStatus = ($reason === 'not_planned') ? 'rejected' : 'completed';
$now = time();
$closeMsg = ($phpStatus === 'rejected')
? '🔒 GitHub issue #' . $issueNo . ' 已关闭(not planned)→ 工单标记为已驳回'
: '🔒 GitHub issue #' . $issueNo . ' 已关闭(done)→ 工单标记为已完结';
try {
$ins = $db->prepare("INSERT INTO web_ticket_replies (ticket_id, sender, role, message, created_at) VALUES (:tid, 'gh:issue', 'admin', :msg, :now)");
$ins->bindValue(':tid', $ticketId, SQLITE3_INTEGER);
$ins->bindValue(':msg', $closeMsg, SQLITE3_TEXT);
$ins->bindValue(':now', $now, SQLITE3_INTEGER);
$ins->execute();
$upd = $db->prepare("UPDATE web_tickets SET status = :status, updated_at = :now WHERE id = :id");
$upd->bindValue(':status', $phpStatus, SQLITE3_TEXT);
$upd->bindValue(':now', $now, SQLITE3_INTEGER);
$upd->bindValue(':id', $ticketId, SQLITE3_INTEGER);
$upd->execute();
ghLog('webhook issue#'. $issueNo . ' closed reason=' . $reason . ' → php status=' . $phpStatus . ' ticket=' . $ticketId);
} catch (\Throwable $e) {
ghLog('webhook close issue: ' . $e->getMessage());
return false;
}
return true;
}
return false;
}
/**
* ★ 15m44w: 把工单附件图推到 GitHub 图片仓(imgrepo = issueimg),拿 raw 链接。
* 用户定调:GitHub 模式本就是为省服务器内存,附件不走图床 API,改成 git 推图仓。
* - 运行时先检测 git 环境:有 git → 走 git commit+push(账号/key 用【img.json 的 PAT】拼认证 URL);
* 无 git → 走 GitHub Contents API(token 也从 img.json 读)。
* - 文件路径:{玩家名}/{工单号}_{YYYYMMDD}_{工单标题}/{原文件名}(每玩家一个文件夹)
* - raw 链接:raw.githubusercontent.com/{owner}/{repo}/{branch}/{path}
* 失败返回 ['ok'=>false,'msg'=>..],调用方回退 @gh: 占位。
*/
/** 服务端是否装了 git(git --version 能跑) */
function ghGitAvailable() {
static $cached = null;
if ($cached !== null) return $cached;
$cached = false;
if (function_exists('exec')) {
$o = []; $ret = 0;
@exec('git --version 2>NUL', $o, $ret); // Windows: 2>NUL 吞错误
if ($ret !== 0) @exec('git --version 2>/dev/null', $o, $ret); // Linux
$cached = ($ret === 0 && !empty($o));
}
return $cached;
}
function ghImgRepoPush($player, $ticketId, $title, $tmpPath, $origName) {
$cfg = ghGetCfg();
$full = isset($cfg['imgrepo_full']) ? $cfg['imgrepo_full'] : '';
$owner = isset($cfg['imgrepo_owner']) ? $cfg['imgrepo_owner'] : '';
$branch = (isset($cfg['imgrepo_branch']) && $cfg['imgrepo_branch'] !== '') ? $cfg['imgrepo_branch'] : 'main';
$token = isset($cfg['imgrepo_token']) ? $cfg['imgrepo_token'] : ''; // ★ 15m44w:账号/key 走 img.json(真值在 .workbuddy,不进 git)
if ($full === '' || strpos($full, '/') === false) {
return ['ok' => false, 'url' => '', 'path' => '', 'msg' => 'imgrepo 仓库地址未配置(img.json repo.imgrepo.仓库地址)'];
}
if ($owner === '') $owner = explode('/', $full)[0];
// 仓内相对路径:{玩家名}/{工单号}_{YYYYMMDD}_{清洗标题}/{原文件名}
$safeTitle = preg_replace('/[^A-Za-z0-9_\x{4E00}-\x{9FFF}]/u', '_', mb_substr($title, 0, 30));
if ($safeTitle === '') $safeTitle = 'untitled';
$safePlayer = preg_replace('/[^A-Za-z0-9_]/', '_', $player);
// 原文件名也清洗(防上传图名含空格/特殊字符;保留 .png/.jpg 等扩展名与中文)
$safeOrig = preg_replace('/[^A-Za-z0-9_.\x{4E00}-\x{9FFF}]/u', '_', $origName);
if (strpos($safeOrig, '.') === false) $safeOrig = $safeOrig . '.png'; // 兜底扩展名
$relPath = $safePlayer . '/' . ((int)$ticketId) . '_' . date('Ymd') . '_' . $safeTitle . '/' . $safeOrig;
// ★ 15m44w 修:raw URL 中文/特殊字符必须 percent-encode(每段编码保留 / 分隔),
// 否则 GitHub 渲染 issue body 里的 ![](url) 图片会因未编码中文 raw URL 加载失败
$rawUrl = 'https://raw.githubusercontent.com/' . $full . '/' . $branch . '/'
. implode('/', array_map('rawurlencode', explode('/', $relPath)));
// ===== 分支1:有 git 环境 → git commit + push(账号/key 用 img.json 的 PAT 拼认证 URL)=====
if (ghGitAvailable()) {
$commitMsg = 'ticket#' . $ticketId . ': ' . mb_substr($title, 0, 40);
$r = ghImgRepoPushViaGit($full, $owner, $branch, $relPath, $tmpPath, $token, $commitMsg);
if (!empty($r['ok'])) {
ghLog('imgrepo push(via git) ok ticket=' . $ticketId . ' path=' . $relPath);
return ['ok' => true, 'url' => $rawUrl, 'path' => $relPath, 'msg' => 'ok'];
}
// git 失败 → 记日志,落 Contents API 兜底(git 可能没配全局 credential)
ghLog('imgrepo git push failed ticket=' . $ticketId . ': ' . $r['msg'] . ' → fallback Contents API');
}
// ===== 分支2:无 git(或 git 失败)→ GitHub Contents API(token 来自 img.json)=====
if ($token === '') {
return ['ok' => false, 'url' => '', 'path' => '', 'msg' => 'img.json repo.imgrepo 的 key/登录密码 未配置(git 与 Contents API 都需要 PAT)'];
}
$r2 = ghImgRepoPushViaContents($full, $branch, $relPath, $tmpPath, $token, 'ticket#' . $ticketId . ': ' . mb_substr($title, 0, 40));
if (!empty($r2['ok'])) {
ghLog('imgrepo push(via Contents API) ok ticket=' . $ticketId . ' path=' . $relPath);
return ['ok' => true, 'url' => $rawUrl, 'path' => $relPath, 'msg' => 'ok'];
}
ghLog('imgrepo contents api failed ticket=' . $ticketId . ': ' . $r2['msg']);
return ['ok' => false, 'url' => '', 'path' => '', 'msg' => $r2['msg']];
}
/** git 方式推图(★ 15m44w:账号/key 走 img.json 的 PAT,拼进认证 URL,不依赖服务端全局 git 缓存)
* ★ 15m44w 续:服务端 PHP disable_functions 禁了 proc_open/popen,但 exec/shell_exec 可用
* → runGit 从 proc_open 改 shell_exec(PAT 直接拼认证 URL,不靠 env 注入 GIT_CONFIG)。
* shell_exec 用 2>&1 合流 stderr,末尾 echo 退出码判成功。 */
function ghImgRepoPushViaGit($full, $owner, $branch, $relPath, $tmpPath, $token, $commitMsg) {
$workRoot = __DIR__ . '/db/gh_imgrepo_work';
if (!is_dir($workRoot)) @mkdir($workRoot, 0755, true);
$repoDir = $workRoot . '/' . preg_replace('/[^A-Za-z0-9_.-]/', '_', $full);
// ★ shell_exec 跑 git:PAT 拼认证 URL,命令 2>&1 合流 + 末尾 echo 退出码判成功
// 参数转义:非 [A-Za-z0-9_. /=:@-] 字符或含空格/中文 → 单引号包(shell 内 ' 转义为 '\')
$q = function($a) {
if ($a === '' || preg_match('/[^\x20-\x7E]/', $a) || strpos($a, ' ') !== false) {
return "'" . str_replace("'", "'\\''", $a) . "'";
}
return $a;
};
$runGit = function($args, $cwd, $q, $timeout = 60) {
$cmd = implode(' ', array_map($q, $args));
// 2>&1 合流 stderr;GIT_TERMINAL_PROMPT=0 禁交互(避免卡死);echo 退出码
$fullCmd = 'cd ' . $q($cwd) . ' && GIT_TERMINAL_PROMPT=0 ' . $cmd . ' 2>&1; echo __EXIT__$?';
$out = @shell_exec($fullCmd);
$out = (string)$out;
if (substr_count($out, '__EXIT__') === 0) {
return ['ok' => false, 'msg' => 'shell_exec 不可用/未返回(可能仍被禁): ' . mb_substr($out, 0, 120)];
}
$exitStr = substr($out, strrpos($out, '__EXIT__'));
preg_match('/__EXIT__(\d+)/', $exitStr, $mm);
$code = isset($mm[1]) ? (int)$mm[1] : 1;
$msg = trim(str_replace('__EXIT__' . $mm[1], '', $out));
return ['ok' => ($code === 0), 'msg' => $msg];
};
$cloneUrl = ($token !== '')
? ('https://' . $owner . ':' . $token . '@github.com/' . $full . '.git') // ★ PAT 拼认证 URL(img.json token)
: ('https://github.com/' . $full . '.git');
try {
// 1) 本地仓(首次 clone,已有则 fetch)
if (is_dir($repoDir . '/.git')) {
$runGit(['fetch', '--all'], $repoDir, 60, $q);
$runGit(['checkout', '-B', $branch, 'origin/' . $branch], $repoDir, 30, $q);
} else {
@mkdir(dirname($repoDir), 0755, true);
$r = $runGit(['clone', '--depth', '1', '--branch', $branch, '--single-branch', $cloneUrl, $repoDir], $workRoot, $q, 120);
if (!$r['ok']) return ['ok' => false, 'msg' => 'clone 失败: ' . mb_substr($r['msg'], 0, 160)];
$runGit(['config', 'user.name', 'caoyuan-ticket-bot'], $repoDir, 10, $q);
$runGit(['config', 'user.email', 'bot@caoyuan.local'], $repoDir, 10, $q);
}
// 2) 写文件到仓内
$target = $repoDir . '/' . $relPath;
@mkdir(dirname($target), 0755, true);
if (!@copy($tmpPath, $target)) return ['ok' => false, 'msg' => '写仓内文件失败'];
// 3) add + commit + push(认证走 img.json PAT:clone URL 已带 owner:token,push 复用 origin)
$runGit(['add', '--', $relPath], $repoDir, 30, $q);
$commit = $runGit(['commit', '-m', $commitMsg, '--allow-empty'], $repoDir, 30, $q);
$rp = $runGit(['push', 'origin', 'HEAD:refs/heads/' . $branch], $repoDir, 90, $q);
if (!$rp['ok']) {
@unlink($target);
return ['ok' => false, 'msg' => 'push 失败: ' . mb_substr($rp['msg'], 0, 200)];
}
return ['ok' => true, 'msg' => 'ok'];
} catch (\Throwable $e) {
return ['ok' => false, 'msg' => 'git 异常: ' . $e->getMessage()];
}
}
/** GitHub Contents API 方式推图(免 git 二进制;token 当 Authorization: Bearer) */
function ghImgRepoPushViaContents($full, $branch, $relPath, $tmpPath, $token, $commitMsg) {
if (!is_file($tmpPath)) return ['ok' => false, 'msg' => '临时文件不存在'];
$content = @file_get_contents($tmpPath);
if ($content === false) return ['ok' => false, 'msg' => '读临时文件失败'];
$encoded = base64_encode($content);
// 路径 URL 编码(每段单独编码,保留 /)
$encPath = implode('/', array_map('rawurlencode', explode('/', $relPath)));
$apiPath = '/repos/' . $full . '/contents/' . $encPath;
// 同名文件已存在?GET 拿 sha(Contents API 更新需带 sha)
$chk = ghApiRequest('GET', $apiPath, null, $token);
$payload = [
'message' => $commitMsg,
'content' => $encoded,
'branch' => $branch,
];
if (!empty($chk['ok']) && is_array($chk['data']) && isset($chk['data']['sha'])) {
$payload['sha'] = $chk['data']['sha'];
}
$r = ghApiRequest('PUT', $apiPath, $payload, $token);
if (!$r['ok']) return ['ok' => false, 'msg' => $r['msg']];
return ['ok' => true, 'msg' => 'ok'];
}
/** 写诊断日志(1 天自动清理) */
function ghLog($msg) {
try {
// ★ 15m44v 修:日志写 __DIR__(= /plugin,gh_api.php 所在目录),与 ticket_debug.log 同目录。
// 旧版用 dirname(__DIR__):gh_api.php 在 /plugin/gh_api.php,__DIR__=/plugin,
// dirname('/') 得到网站根 /,日志被写到网站根而非 /plugin → 用户/我去 /plugin 找
// 永远 NOT FOUND(关键谜团根因)。改 __DIR__ 后落 /plugin/gh_sync.log。
$dir = __DIR__;
$file = $dir . '/gh_sync.log';
$cut = time() - 86400;
if (is_dir($dir)) {
foreach (glob($dir . '/gh_sync_*.log') as $old) {
if (file_exists($old) && filemtime($old) < $cut) @unlink($old);
}
}
@file_put_contents($file, '[' . date('Y-m-d H:i:s') . '] ' . $msg . "\n", FILE_APPEND | LOCK_EX);
} catch (\Throwable $e) { /* 日志失败不影响主流程 */ }
}