Files
Sdf1_login/gh_api.php
T
ypsdf1 08f85284ee 15m44s 工单 GitHub 三项:token继承+label打标+webhook联动关单
需求1(token继承): 玩家授权过且 access_token 仍有效→gh_oauth.php 发起授权前
  先查 gh_auth_tokens 调 /user 验活,有效则 302 回 player.php?gh_inherit=1 直接继承
  不弹 GitHub;真失效才重新走 OAuth。不再一股脑报'无效要重新授权'。

需求2(label打标): 撤单/用户回/管理回/驳回/完结 5 个动作调 ghSyncLabel,按
  img.json repo.tag 映射(正常关单→已完成/驳回→已驳回/已回复/撤销)给对应 issue
  打 label,并摘掉互斥状态类 label。gh_label_map 可配置,缺省中文兜底。

需求3(webhook联动关单): ghHandleWebhook issue 关闭事件按 state_reason 联动 PHP:
  completed(done)→已完结;not_planned→已驳回;缺省 done。

附件占位符 [图片N] 未替换根因=历史单(OPcache 跑旧编译)+漏清 OPcache,本轮部署
后会清 OPcache,新建单正常替换。
2026-11-25 15:06:11 +08:00

428 lines
20 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 + "] "
}
/** 取 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',
];
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] 只标记"此处有附件"不重复展示文件名。
$desc = (string)$description;
$hasAttach = false;
foreach ((is_array($images) ? $images : []) as $u) {
if (is_string($u)) { $hasAttach = true; break; }
}
if ($hasAttach) {
$desc = preg_replace('/\[图片(\d+)\]/u', '\U📎 附件\1\E', $desc);
}
$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:文件名.png → 取冒号后的文件名展示
$label = str_replace('@gh:', '', $u);
$bodyParts[] = '📎 附件' . ($i + 1) . ':`' . $label . '`(需在 GitHub issue 上传原图)';
} 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;
}
/** 写诊断日志(1 天自动清理) */
function ghLog($msg) {
try {
$dir = dirname(__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) { /* 日志失败不影响主流程 */ }
}