15m44l 工单第二批: GitHub issue 双向同步(OAuth逐次授权+建issue/评论+Webhook回推, 防循环前缀)
This commit is contained in:
@@ -57,6 +57,9 @@ db/
|
|||||||
/*.*.back.*
|
/*.*.back.*
|
||||||
# 屏蔽所有的测试文件
|
# 屏蔽所有的测试文件
|
||||||
/*_*.*
|
/*_*.*
|
||||||
|
# ★ 15m44l 例外:gh_api.php 是工单第二批 GitHub issue 双向同步的【生产产品文件】(含共享 REST 客户端),
|
||||||
|
# 不是本地测试工具,须随仓走 + 部署到 /plugin。加反向放行。
|
||||||
|
!gh_api.php
|
||||||
/_test*/*.*
|
/_test*/*.*
|
||||||
# ===== .workbuddy/ 工作目录(用户保留区)=====
|
# ===== .workbuddy/ 工作目录(用户保留区)=====
|
||||||
# 存放测试脚本 / 探针 / 测试数据 / 备份文件,已被 git拉黑(2026-10-09)
|
# 存放测试脚本 / 探针 / 测试数据 / 备份文件,已被 git拉黑(2026-10-09)
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* 15m44l 工单第二批:GitHub issue 双向同步 —— OAuth 授权端点(玩家逐次授权)
|
||||||
|
*
|
||||||
|
* 两个用途:
|
||||||
|
* 1) 发起授权(GET, 无 code):把浏览器 302 到 GitHub OAuth App 的 authorize 页,
|
||||||
|
* 带 state=玩家名(CSRF 防护)。玩家在前端点「授权 GitHub 工单同步」触发。
|
||||||
|
* 2) 授权回调(GET, 带 code+state):GitHub 回跳本端点,用 code+client_secret 换
|
||||||
|
* access_token,校验 state(玩家名),把 token 写进 web_tickets.gh_access_token
|
||||||
|
* (或按工单 gh_ticket_id 关联),供后续调 issue API。
|
||||||
|
*
|
||||||
|
* 凭据全在 img.json(repo.Client ID / Client secrets + webhook_secret),本文件不含敏感值。
|
||||||
|
* 配置未启用(gh_enabled=false)时,发起授权直接报错,避免误跳。
|
||||||
|
*
|
||||||
|
* 端点 URL(给用户配 GitHub OAuth App 的 Redirect URI):
|
||||||
|
* https://caoyuan.ypshidifu.cn/plugin/api/gh_oauth.php
|
||||||
|
*/
|
||||||
|
|
||||||
|
while (ob_get_level() > 0) { @ob_end_clean(); }
|
||||||
|
ob_start();
|
||||||
|
header('X-Content-Type-Options: nosniff');
|
||||||
|
|
||||||
|
error_reporting(E_ALL);
|
||||||
|
ini_set('display_errors', '0');
|
||||||
|
if (function_exists('opcache_invalidate')) { @opcache_invalidate(__FILE__); }
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../core.php';
|
||||||
|
require_once __DIR__ . '/../lsky.php';
|
||||||
|
|
||||||
|
$cfg = loadImgJson();
|
||||||
|
if (!$cfg['gh_enabled']) {
|
||||||
|
// 发起授权:报"未启用";回调:GitHub 不该回跳未启用站点,同样报未启用
|
||||||
|
header('Content-Type: text/html; charset=utf-8');
|
||||||
|
echo '<meta charset="utf-8"><title>GitHub 工单同步未启用</title>'
|
||||||
|
. '<p>GitHub issue 工单同步未启用(img.json 的 模式.type 需填 GitHub 且 repo 段填全)。</p>'
|
||||||
|
. '<p><a href="javascript:history.back()">返回</a></p>';
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$repo = $cfg['gh_repo']; // ypsdf1/caoyuanwiki
|
||||||
|
$clientId = $cfg['gh_client_id'];
|
||||||
|
$clientSec = $cfg['gh_client_secret'];
|
||||||
|
$baseSite = rtrim('https://caoyuan.ypshidifu.cn/plugin', '/');
|
||||||
|
$oauthUrl = $baseSite . '/api/gh_oauth.php';
|
||||||
|
|
||||||
|
// GitHub OAuth authorize / token 端点
|
||||||
|
$ghAuthorize = 'https://github.com/login/oauth/authorize';
|
||||||
|
$ghToken = 'https://github.com/login/oauth/access_token';
|
||||||
|
|
||||||
|
$code = isset($_GET['code']) ? trim((string)$_GET['code']) : '';
|
||||||
|
|
||||||
|
if ($code !== '') {
|
||||||
|
// ===== 回调:换 token =====
|
||||||
|
$state = isset($_GET['state']) ? trim((string)$_GET['state']) : '';
|
||||||
|
// state = 玩家名(发起授权时由前端传 player 拼进 state)
|
||||||
|
$player = $state;
|
||||||
|
$scope = 'repo'; // issue 读+写需要 repo 权限
|
||||||
|
|
||||||
|
// 用 code 换 access_token(client_secret 走 POST body)
|
||||||
|
$ch = curl_init();
|
||||||
|
curl_setopt($ch, CURLOPT_URL, $ghToken);
|
||||||
|
curl_setopt($ch, CURLOPT_POST, true);
|
||||||
|
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
|
||||||
|
'client_id' => $clientId,
|
||||||
|
'client_secret' => $clientSec,
|
||||||
|
'code' => $code,
|
||||||
|
'scope' => $scope,
|
||||||
|
]));
|
||||||
|
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);
|
||||||
|
$body = curl_exec($ch);
|
||||||
|
$errno = curl_errno($ch);
|
||||||
|
curl_close($ch);
|
||||||
|
if ($errno) {
|
||||||
|
header('Content-Type: text/html; charset=utf-8');
|
||||||
|
echo '<meta charset="utf-8"><p>获取 GitHub token 失败(cURL ' . htmlspecialchars($errno) . ')。</p>';
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
// GitHub 返回 application/x-www-form-urlencoded: "access_token=xxx&scope=repo&token_type=bearer"
|
||||||
|
parse_str((string)$body, $tok);
|
||||||
|
$accessToken = isset($tok['access_token']) ? (string)$tok['access_token'] : '';
|
||||||
|
$ghUser = isset($tok['user_login']) ? (string)$tok['user_login'] : '';
|
||||||
|
if ($accessToken === '') {
|
||||||
|
$err = isset($tok['error']) ? (string)$tok['error'] : 'unknown';
|
||||||
|
header('Content-Type: text/html; charset=utf-8');
|
||||||
|
echo '<meta charset="utf-8"><p>GitHub 授权失败: ' . htmlspecialchars($err) . '。</p>'
|
||||||
|
. '<p><a href="javascript:history.back()">返回</a></p>';
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 写库:把 token 存进 web_tickets 的 gh_access_token 列(按玩家名)
|
||||||
|
// 没有 gh_access_token 列则先 ALTER 兜底
|
||||||
|
$db = getDB();
|
||||||
|
try {
|
||||||
|
$db->exec("ALTER TABLE web_tickets ADD COLUMN gh_access_token TEXT DEFAULT ''");
|
||||||
|
} catch (\Throwable $e) { /* 列已存在 */ }
|
||||||
|
try {
|
||||||
|
$db->exec("ALTER TABLE web_tickets ADD COLUMN gh_issue_number TEXT DEFAULT ''");
|
||||||
|
} catch (\Throwable $e) { /* 列已存在 */ }
|
||||||
|
|
||||||
|
$upd = $db->prepare("UPDATE web_tickets SET gh_access_token = :t WHERE requester = :p AND (gh_access_token IS NULL OR gh_access_token = '')");
|
||||||
|
$upd->bindValue(':t', $accessToken, SQLITE3_TEXT);
|
||||||
|
$upd->bindValue(':p', $player, SQLITE3_TEXT);
|
||||||
|
$upd->execute();
|
||||||
|
|
||||||
|
// 回跳前端「工单」页,带成功标记,前端拿到后可开始同步
|
||||||
|
header('Location: ' . $baseSite . '/player.php?gh_ok=1&gh_user=' . urlencode($ghUser));
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 发起授权 =====
|
||||||
|
// 前端传 ?player=玩家名(拼进 state 做 CSRF 校验);也可从 token 解析。
|
||||||
|
$playerParam = isset($_GET['player']) ? trim((string)$_GET['player']) : '';
|
||||||
|
$state = $playerParam !== '' ? $playerParam : 'anon';
|
||||||
|
$authUrl = $ghAuthorize . '?' . http_build_query([
|
||||||
|
'client_id' => $clientId,
|
||||||
|
'redirect_uri' => $oauthUrl,
|
||||||
|
'scope' => 'repo',
|
||||||
|
'state' => $state,
|
||||||
|
]);
|
||||||
|
header('Location: ' . $authUrl);
|
||||||
|
exit;
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* 15m44l 工单第二批:GitHub issue 双向同步 —— Webhook 回调端点
|
||||||
|
*
|
||||||
|
* 这是【给用户填到 GitHub 仓库 Settings→Webhooks→Payload URL】的地址。
|
||||||
|
* GitHub 在 issue/评论/关闭等事件发生时,POST JSON 到这里(带 X-Hub-Signature-256 签名)。
|
||||||
|
* 本端点:
|
||||||
|
* 1) 校验签名(HMAC-SHA256, secret = img.json.webhook_secret)→ 防伪造
|
||||||
|
* 2) 解析事件,交给 ghHandleWebhook 回推 PHP web_ticket_replies
|
||||||
|
* 3) 只认我们 PHP 工单建的 issue(按 gh_issue_number 反查)
|
||||||
|
*
|
||||||
|
* 配置:在 GitHub 仓库 → Settings → Webhooks → Add webhook:
|
||||||
|
* Payload URL : https://caoyuan.ypshidifu.cn/plugin/api/gh_webhook.php
|
||||||
|
* Content type: application/json
|
||||||
|
* Secret : 4V8gi9h^&^47 (= img.json.webhook_secret,两边必须一致)
|
||||||
|
* Events : 勾选 issue_comment + issues
|
||||||
|
*/
|
||||||
|
|
||||||
|
while (ob_get_level() > 0) { @ob_end_clean(); }
|
||||||
|
ob_start();
|
||||||
|
|
||||||
|
error_reporting(E_ALL);
|
||||||
|
ini_set('display_errors', '0');
|
||||||
|
if (function_exists('opcache_invalidate')) { @opcache_invalidate(__FILE__); }
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../core.php';
|
||||||
|
require_once __DIR__ . '/../lsky.php';
|
||||||
|
require_once __DIR__ . '/../gh_api.php';
|
||||||
|
|
||||||
|
// Webhook 必须 POST + application/json
|
||||||
|
if (strtoupper($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
|
||||||
|
http_response_code(405);
|
||||||
|
header('Content-Type: application/json; charset=utf-8');
|
||||||
|
echo json_encode(['success' => false, 'message' => 'method not allowed (POST only)']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$rawBody = file_get_contents('php://input');
|
||||||
|
if ($rawBody === false || $rawBody === '') {
|
||||||
|
http_response_code(400);
|
||||||
|
header('Content-Type: application/json; charset=utf-8');
|
||||||
|
echo json_encode(['success' => false, 'message' => 'empty body']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1) 签名校验
|
||||||
|
$sigHeader = isset($_SERVER['HTTP_X_HUB_SIGNATURE_256']) ? (string)$_SERVER['HTTP_X_HUB_SIGNATURE_256'] : '';
|
||||||
|
if (!ghWebhookVerify($rawBody, $sigHeader)) {
|
||||||
|
ghLog('WEBHOOK REJECT: bad X-Hub-Signature-256');
|
||||||
|
http_response_code(403);
|
||||||
|
header('Content-Type: application/json; charset=utf-8');
|
||||||
|
echo json_encode(['success' => false, 'message' => 'signature mismatch']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) 解析 JSON
|
||||||
|
$payload = json_decode($rawBody, true);
|
||||||
|
if (!is_array($payload)) {
|
||||||
|
http_response_code(400);
|
||||||
|
header('Content-Type: application/json; charset=utf-8');
|
||||||
|
echo json_encode(['success' => false, 'message' => 'invalid json']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$event = strtolower(isset($_SERVER['HTTP_X_GITHUB_EVENT']) ? (string)$_SERVER['HTTP_X_GITHUB_EVENT'] : '');
|
||||||
|
if ($event === '') $event = isset($payload['event']) ? (string)$payload['event'] : 'unknown';
|
||||||
|
|
||||||
|
// 只关心 issue 相关事件
|
||||||
|
$handled = ghHandleWebhook($payload, $event);
|
||||||
|
|
||||||
|
// GitHub 要求 webhook 返回 2xx 才认为投递成功;处理不了也回 200 + 标记,避免 GitHub 反复重发
|
||||||
|
header('Content-Type: application/json; charset=utf-8');
|
||||||
|
echo json_encode([
|
||||||
|
'success' => true,
|
||||||
|
'message' => $handled ? 'handled' : 'ignored (not our ticket / no action)',
|
||||||
|
'event' => $event,
|
||||||
|
]);
|
||||||
|
exit;
|
||||||
+42
-4
@@ -27,6 +27,8 @@ register_shutdown_function(function() {
|
|||||||
require_once __DIR__ . '/../core.php';
|
require_once __DIR__ . '/../core.php';
|
||||||
// 工单附件图:兰空图床客户端(本文件不含敏感值,凭据在 lsky_keys.php)
|
// 工单附件图:兰空图床客户端(本文件不含敏感值,凭据在 lsky_keys.php)
|
||||||
require_once __DIR__ . '/../lsky.php';
|
require_once __DIR__ . '/../lsky.php';
|
||||||
|
// 15m44l 工单第二批:GitHub issue 双向同步(共享 REST 客户端 + 同步编排)
|
||||||
|
require_once __DIR__ . '/../gh_api.php';
|
||||||
|
|
||||||
if (session_status() === PHP_SESSION_NONE) { session_start(); }
|
if (session_status() === PHP_SESSION_NONE) { session_start(); }
|
||||||
|
|
||||||
@@ -390,6 +392,22 @@ function ticketUploadImage() {
|
|||||||
success(['url' => $r['url'], 'thumbnail' => isset($r['thumb']) ? $r['thumb'] : $r['url']], '上传成功');
|
success(['url' => $r['url'], 'thumbnail' => isset($r['thumb']) ? $r['thumb'] : $r['url']], '上传成功');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 15m44l: 取工单关联的 GitHub access_token(按玩家名从 web_tickets.gh_access_token 读)。
|
||||||
|
* 列不存在/空 → 返回 ''(调用方据此跳过同步,PHP 工单照常)。
|
||||||
|
*/
|
||||||
|
function ghTicketToken($player) {
|
||||||
|
$db = getDB();
|
||||||
|
try {
|
||||||
|
$st = $db->prepare("SELECT gh_access_token FROM web_tickets WHERE requester = :p AND gh_access_token IS NOT NULL AND gh_access_token != '' ORDER BY id DESC LIMIT 1");
|
||||||
|
$st->bindValue(':p', $player, SQLITE3_TEXT);
|
||||||
|
$row = $st->execute()->fetchArray(SQLITE3_ASSOC);
|
||||||
|
return ($row && !empty($row['gh_access_token'])) ? (string)$row['gh_access_token'] : '';
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
return ''; // 列还没建(老库)→ 跳过同步
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function ticketCreate() {
|
function ticketCreate() {
|
||||||
$info = requireWebToken();
|
$info = requireWebToken();
|
||||||
$player = $info['player'];
|
$player = $info['player'];
|
||||||
@@ -435,7 +453,11 @@ function ticketCreate() {
|
|||||||
$GLOBALS['__ticket_dbg_urls'] = $images;
|
$GLOBALS['__ticket_dbg_urls'] = $images;
|
||||||
writeTicketCreateDebug();
|
writeTicketCreateDebug();
|
||||||
|
|
||||||
success(['id' => $ticketId, 'images' => $images], '工单提交成功');
|
// 15m44l: 同步 GitHub issue(非阻塞:失败不影响 PHP 工单入库;未授权/未配置则跳过)
|
||||||
|
$ghToken = ghTicketToken($player);
|
||||||
|
$ghSyncOk = ghSyncCreate($ticketId, $player, $title, $description, $images, $ghToken);
|
||||||
|
|
||||||
|
success(['id' => $ticketId, 'images' => $images, 'gh_synced' => (bool)$ghSyncOk], '工单提交成功');
|
||||||
}
|
}
|
||||||
|
|
||||||
// 15m44f 诊断日志:ticketCreate 在 success 前把关键诊断信息写到 /plugin/ticket_debug.log
|
// 15m44f 诊断日志:ticketCreate 在 success 前把关键诊断信息写到 /plugin/ticket_debug.log
|
||||||
@@ -590,8 +612,15 @@ function ticketReply() {
|
|||||||
$db->exec('ROLLBACK');
|
$db->exec('ROLLBACK');
|
||||||
error('回复失败');
|
error('回复失败');
|
||||||
}
|
}
|
||||||
|
|
||||||
success(null, '回复成功');
|
// 15m44l: 同步 GitHub issue 评论(非阻塞,未授权/未配置/无对应issue则跳过)
|
||||||
|
$ghSyncOk = false;
|
||||||
|
try {
|
||||||
|
$ghToken = ghTicketToken($player);
|
||||||
|
$ghSyncOk = ghSyncReply($id, $message, $ghToken, $player);
|
||||||
|
} catch (\Throwable $ignored) { $ghSyncOk = false; }
|
||||||
|
|
||||||
|
success(['gh_synced' => (bool)$ghSyncOk], '回复成功');
|
||||||
}
|
}
|
||||||
|
|
||||||
function ticketWithdraw() {
|
function ticketWithdraw() {
|
||||||
@@ -643,12 +672,21 @@ function ticketListAll() {
|
|||||||
images TEXT DEFAULT '[]',
|
images TEXT DEFAULT '[]',
|
||||||
reject_reason TEXT DEFAULT '',
|
reject_reason TEXT DEFAULT '',
|
||||||
created_at INTEGER NOT NULL,
|
created_at INTEGER NOT NULL,
|
||||||
updated_at INTEGER NOT NULL
|
updated_at INTEGER NOT NULL,
|
||||||
|
gh_access_token TEXT DEFAULT '',
|
||||||
|
gh_issue_number TEXT DEFAULT ''
|
||||||
)");
|
)");
|
||||||
// ★ 迁移:老库补 images 列(工单附件图 URL 数组 JSON)
|
// ★ 迁移:老库补 images 列(工单附件图 URL 数组 JSON)
|
||||||
try {
|
try {
|
||||||
$db->exec("ALTER TABLE web_tickets ADD COLUMN images TEXT DEFAULT '[]'");
|
$db->exec("ALTER TABLE web_tickets ADD COLUMN images TEXT DEFAULT '[]'");
|
||||||
} catch (Exception $e) { /* 列已存在 */ }
|
} catch (Exception $e) { /* 列已存在 */ }
|
||||||
|
// ★ 15m44l GitHub issue 双向同步:老库补 gh_ 两列
|
||||||
|
try {
|
||||||
|
$db->exec("ALTER TABLE web_tickets ADD COLUMN gh_access_token TEXT DEFAULT ''");
|
||||||
|
} catch (Exception $e) { /* 列已存在 */ }
|
||||||
|
try {
|
||||||
|
$db->exec("ALTER TABLE web_tickets ADD COLUMN gh_issue_number TEXT DEFAULT ''");
|
||||||
|
} catch (Exception $e) { /* 列已存在 */ }
|
||||||
$db->exec("CREATE TABLE IF NOT EXISTS web_ticket_replies (
|
$db->exec("CREATE TABLE IF NOT EXISTS web_ticket_replies (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
ticket_id INTEGER NOT NULL,
|
ticket_id INTEGER NOT NULL,
|
||||||
|
|||||||
@@ -2153,8 +2153,13 @@ function initTables($db, $side = null) {
|
|||||||
images TEXT DEFAULT '[]',
|
images TEXT DEFAULT '[]',
|
||||||
reject_reason TEXT DEFAULT '',
|
reject_reason TEXT DEFAULT '',
|
||||||
created_at INTEGER NOT NULL,
|
created_at INTEGER NOT NULL,
|
||||||
updated_at INTEGER NOT NULL
|
updated_at INTEGER NOT NULL,
|
||||||
|
gh_access_token TEXT DEFAULT '',
|
||||||
|
gh_issue_number TEXT DEFAULT ''
|
||||||
)");
|
)");
|
||||||
|
// ★ 15m44l 工单第二批:GitHub issue 双向同步 —— 老库补 gh_ 两列
|
||||||
|
try { $db->exec("ALTER TABLE web_tickets ADD COLUMN gh_access_token TEXT DEFAULT ''"); } catch (\Throwable $e) { /* 列已存在 */ }
|
||||||
|
try { $db->exec("ALTER TABLE web_tickets ADD COLUMN gh_issue_number TEXT DEFAULT ''"); } catch (\Throwable $e) { /* 列已存在 */ }
|
||||||
$db->exec("CREATE TABLE IF NOT EXISTS web_ticket_replies (
|
$db->exec("CREATE TABLE IF NOT EXISTS web_ticket_replies (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
ticket_id INTEGER NOT NULL,
|
ticket_id INTEGER NOT NULL,
|
||||||
|
|||||||
+269
@@ -0,0 +1,269 @@
|
|||||||
|
<?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:玩家名 + 描述 + 图片链接(GitHub issue 支持 markdown 图片)
|
||||||
|
$bodyParts = ['玩家:`' . $player . '`', ''];
|
||||||
|
if ($description !== '') $bodyParts[] = $description;
|
||||||
|
if (is_array($images) && count($images) > 0) {
|
||||||
|
$bodyParts[] = '';
|
||||||
|
foreach ($images as $i => $u) {
|
||||||
|
$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();
|
||||||
|
$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 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) { /* 日志失败不影响主流程 */ }
|
||||||
|
}
|
||||||
@@ -2,20 +2,21 @@
|
|||||||
"模式": {
|
"模式": {
|
||||||
"type": "",
|
"type": "",
|
||||||
"说明": [
|
"说明": [
|
||||||
"1. type留空→走图床",
|
"1. type留空→走图床(EasyImages2.0)",
|
||||||
"2. 填GitHub→走GitHub issue(本期未启用)"
|
"2. 填GitHub→走GitHub issue(工单同步 caoyuanwiki 仓库)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"repo": {
|
"repo": {
|
||||||
"url": "https://github.com/username/reponame",
|
"url": "https://github.com/ypsdf1/caoyuanwiki",
|
||||||
"Client ID": "12345",
|
"Client ID": "Ov23li8Zk7KtdcDKEyXh",
|
||||||
"Client secrets": "12345",
|
"Client secrets": "6381a52aada20839bee8e9d31c156b56417e6fa5",
|
||||||
"type": {
|
"type": {
|
||||||
"public": true,
|
"public": true,
|
||||||
"private": false,
|
"private": false,
|
||||||
"备注": "仓库类型2选1,同时双开默认public"
|
"备注": "仓库类型2选1,同时双开默认public"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"webhook_secret": "4V8gi9h^&^47",
|
||||||
"图像/附件支持": {
|
"图像/附件支持": {
|
||||||
"附件支持": true,
|
"附件支持": true,
|
||||||
"最大图片数量": 3,
|
"最大图片数量": 3,
|
||||||
@@ -32,12 +33,12 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"api": {
|
"api": {
|
||||||
"baseurl": "https://example.com/",
|
"baseurl": "https://img.ypshidifu.cn/",
|
||||||
"key": "example",
|
"key": "95895d65c850dd85b02180e2daabcd43",
|
||||||
"说明": [
|
"说明": [
|
||||||
"1. key和API地址都要填",
|
"1. key和API地址都要填",
|
||||||
"2. 如果附件支持为true但api没配置自动退回false",
|
"2. 如果附件支持为true但api没配置自动退回false",
|
||||||
"3. 记得在EasyImages2.0后台-图床安全里,开启API上传"
|
"3. 记得在EasyImages2.0后台-图床安全里,开启API上传"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,11 +39,14 @@ if (!defined('LSKY_ALLOWED_HOST_PREFIX')) {
|
|||||||
* 图像/附件支持.最大图片数量 — 单工单最多几张(默认 3)
|
* 图像/附件支持.最大图片数量 — 单工单最多几张(默认 3)
|
||||||
* 图像/附件支持.最大大小 — 单张大小上限, 单位 MB(默认 2)
|
* 图像/附件支持.最大大小 — 单张大小上限, 单位 MB(默认 2)
|
||||||
* 图像/附件支持.后缀格式 — 允许的后缀数组(默认 ["jpg","jpeg","png"])
|
* 图像/附件支持.后缀格式 — 允许的后缀数组(默认 ["jpg","jpeg","png"])
|
||||||
* 模式.type — 留空=图床, GitHub=issue(本期不做)
|
* 模式.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',
|
* ['type','baseurl','key','easy',
|
||||||
* 'attach_enabled','max_images','max_size_mb','allowed_exts']
|
* 'attach_enabled','max_images','max_size_mb','allowed_exts',
|
||||||
|
* 'gh_enabled','gh_repo','gh_client_id','gh_client_secret','gh_webhook_secret']
|
||||||
* 文件缺失/解析失败 → 全默认值(调用方按"未配置"兜底)。
|
* 文件缺失/解析失败 → 全默认值(调用方按"未配置"兜底)。
|
||||||
*/
|
*/
|
||||||
function loadImgJson() {
|
function loadImgJson() {
|
||||||
@@ -57,6 +60,12 @@ function loadImgJson() {
|
|||||||
'max_images' => 3,
|
'max_images' => 3,
|
||||||
'max_size_mb' => 2,
|
'max_size_mb' => 2,
|
||||||
'allowed_exts' => ['jpg', 'jpeg', 'png'],
|
'allowed_exts' => ['jpg', 'jpeg', 'png'],
|
||||||
|
// GitHub issue 集成(15m44l 第二批)
|
||||||
|
'gh_enabled' => false,
|
||||||
|
'gh_repo' => '', // "ypsdf1/caoyuanwiki"
|
||||||
|
'gh_client_id' => '',
|
||||||
|
'gh_client_secret' => '',
|
||||||
|
'gh_webhook_secret' => '',
|
||||||
];
|
];
|
||||||
$file = __DIR__ . '/img.json';
|
$file = __DIR__ . '/img.json';
|
||||||
if (!is_readable($file)) return $cfg;
|
if (!is_readable($file)) return $cfg;
|
||||||
@@ -92,6 +101,23 @@ function loadImgJson() {
|
|||||||
|
|
||||||
// easy = 走 EasyImages2.0(type 非 GitHub 且有 baseurl+key 且附件支持开)
|
// easy = 走 EasyImages2.0(type 非 GitHub 且有 baseurl+key 且附件支持开)
|
||||||
$cfg['easy'] = ($cfg['type'] !== 'GitHub' && $cfg['baseurl'] !== '' && $cfg['key'] !== '' && $cfg['attach_enabled']);
|
$cfg['easy'] = ($cfg['type'] !== 'GitHub' && $cfg['baseurl'] !== '' && $cfg['key'] !== '' && $cfg['attach_enabled']);
|
||||||
|
|
||||||
|
// GitHub issue 集成(15m44l):repo.url → owner/name + OAuth Client ID/Secret + Webhook 密钥
|
||||||
|
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']) : '';
|
||||||
|
}
|
||||||
|
$cfg['gh_webhook_secret'] = isset($j['webhook_secret']) ? trim((string)$j['webhook_secret']) : '';
|
||||||
|
// gh_enabled = 模式.type=GitHub 且 repo 段填全(owner/name + client_id + client_secret)
|
||||||
|
$cfg['gh_enabled'] = ($cfg['type'] === 'GitHub' && $cfg['gh_repo'] !== ''
|
||||||
|
&& $cfg['gh_client_id'] !== '' && $cfg['gh_client_secret'] !== '');
|
||||||
return $cfg;
|
return $cfg;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user