Files
Sdf1_login/gh_api.php
T

313 lines
14 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);
$json = json_encode($payload === null ? new stdClass() : $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));
}
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 工单照常)
return false;
}
$repo = $cfg['gh_repo'];
$ghTitle = GH_TICKET_PREFIX . $ticketId . '] ' . $title;
// issue body:玩家名 + 描述 + 附件
// - @gh: 开头 = GitHub 模式占位附件(只记文件名,不走图床)→ 显示为「📎 附件:文件名」
// - http(s) = 真实图床外链 → 用 markdown 图片语法
$bodyParts = ['玩家:`' . $player . '`', ''];
if ($description !== '') $bodyParts[] = $description;
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 === '') return false;
$issueNo = ghTicketIssueNumber($ticketId);
if ($issueNo === '') return false; // 该工单没对应 issue(未同步过)
$repo = $cfg['gh_repo'];
$closeComment = ($kind === 'completed')
? GH_TICKET_PREFIX . $ticketId . '][' . $sender . '] ✅ 工单已完结'
: GH_TICKET_PREFIX . $ticketId . '][' . $sender . '] 🚫 工单已驳回';
// 先评论(留痕)再关 issue
ghApiRequest('POST', '/repos/' . $repo . '/issues/' . $issueNo . '/comments', ['body' => $closeComment], $token);
$r = ghApiRequest('POST', '/repos/' . $repo . '/issues/' . $issueNo . '/close', ['state' => 'closed'], $token);
if (!$r['ok']) ghLog('close issue #' . $issueNo . ' failed: ' . $r['msg']);
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 → PHP 标记 completed(若仍开放)
if ($event === 'issues' && isset($issue['state']) && $issue['state'] === 'closed') {
$now = time();
$closeMsg = '🔒 GitHub issue #' . $issueNo . ' 已关闭';
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 = 'completed', 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 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) { /* 日志失败不影响主流程 */ }
}