From f94e6e1f158736bb55e16f8d8c83bbb68210cd9f Mon Sep 17 00:00:00 2001 From: BlackAngelTVdev Date: Mon, 7 Sep 2026 13:47:59 +0200 Subject: [PATCH] Feat(bugs): notifications Discord, invitations et comptes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Envoie chaque signalement dans un canal forum Discord (post avec résumé + logs par morceaux), met à jour le post quand le statut change côté admin, et ajoute l'inscription par code d'invitation à usage unique + changement de mot de passe dans le panneau. --- admin/bugs/index.php | 197 +++++++++++++++++ admin/bugs/init.php | 7 +- admin/bugs/register.php | 157 +++++++++++++ api/bugs.php | 39 +++- api/bugs/config.local.php.example | 36 +++ api/bugs/db.php | 99 +++++++++ api/bugs/discord.php | 357 ++++++++++++++++++++++++++++++ 7 files changed, 885 insertions(+), 7 deletions(-) create mode 100644 admin/bugs/register.php create mode 100644 api/bugs/config.local.php.example create mode 100644 api/bugs/discord.php diff --git a/admin/bugs/index.php b/admin/bugs/index.php index 953ba89..f011276 100644 --- a/admin/bugs/index.php +++ b/admin/bugs/index.php @@ -11,6 +11,7 @@ declare(strict_types=1); require __DIR__ . '/../../api/bugs/db.php'; +require_once __DIR__ . '/../../api/bugs/discord.php'; session_set_cookie_params([ 'httponly' => true, @@ -84,6 +85,7 @@ function excerpt(string $s, int $len = 140): string $error = null; $notice = null; +$freshInvite = ''; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $action = $_POST['action'] ?? ''; @@ -123,9 +125,27 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { $error = 'Statut inconnu.'; } else { $pdo = fws_bugs_db(); + $st = $pdo->prepare('SELECT status, discord_thread_id FROM bug_reports WHERE id = :id'); + $st->execute([':id' => $id]); + $row = $st->fetch(); $st = $pdo->prepare('UPDATE bug_reports SET status = :s WHERE id = :id'); $st->execute([':s' => $status, ':id' => $id]); $notice = "Signalement #$id marqué « " . $STATUSES[$status] . " »."; + + /* Prévenir Discord (best-effort) */ + if ($row !== false && !empty($row['discord_thread_id'])) { + try { + $actor = current_user()['name'] ?? ''; + fws_bugs_discord_status_change([ + 'thread_id' => (string) $row['discord_thread_id'], + 'old_status' => (string) ($row['status'] ?? ''), + 'new_status' => $status, + 'actor' => (string) $actor, + ]); + } catch (Throwable $e) { + error_log('[fws-bugs] discord statut : ' . $e->getMessage()); + } + } header('Location: index.php?id=' . $id); exit; } @@ -137,6 +157,46 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { $notice = "Signalement #$id supprimé."; header('Location: index.php'); exit; + } elseif ($action === 'gen_invite') { + $days = (int) ($_POST['days'] ?? 7); + if (!in_array($days, [0, 1, 7, 30, 90], true)) { + $days = 7; + } + $pdo = fws_bugs_db(); + try { + $freshInvite = fws_bugs_create_invite($pdo, (string) (current_user()['name'] ?? ''), $days); + $notice = 'Code d\'invitation généré.'; + } catch (Throwable $e) { + $error = 'Erreur : ' . $e->getMessage(); + } + } elseif ($action === 'revoke_invite') { + $inviteId = (int) ($_POST['invite_id'] ?? 0); + $pdo = fws_bugs_db(); + $st = $pdo->prepare("UPDATE invite_codes SET revoked_at = datetime('now') WHERE id = :id AND used_by IS NULL AND revoked_at IS NULL"); + $st->execute([':id' => $inviteId]); + $notice = $st->rowCount() > 0 + ? 'Code d\'invitation révoqué : il ne fonctionnera plus.' + : 'Impossible de révoquer ce code (déjà utilisé ou déjà révoqué).'; + } elseif ($action === 'change_password') { + $cur = (string) ($_POST['current_password'] ?? ''); + $new = (string) ($_POST['new_password'] ?? ''); + $confirm = (string) ($_POST['confirm_password'] ?? ''); + $uid = (int) current_user()['id']; + $pdo = fws_bugs_db(); + $st = $pdo->prepare('SELECT password_hash FROM admin_users WHERE id = :id'); + $st->execute([':id' => $uid]); + $row = $st->fetch(); + if ($row === false || !password_verify($cur, $row['password_hash'])) { + $error = 'Mot de passe actuel incorrect.'; + } elseif (strlen($new) < 8) { + $error = 'Nouveau mot de passe trop court (8 caractères minimum).'; + } elseif ($new !== $confirm) { + $error = 'Les deux nouveaux mots de passe ne correspondent pas.'; + } else { + $up = $pdo->prepare('UPDATE admin_users SET password_hash = :h WHERE id = :id'); + $up->execute([':h' => password_hash($new, PASSWORD_DEFAULT), ':id' => $uid]); + $notice = 'Mot de passe modifié avec succès.'; + } } } } @@ -153,6 +213,7 @@ try { } $view_id = (int) ($_GET['id'] ?? 0); +$view_invites = ($_GET['view'] ?? '') === 'invites' && $view_id === 0; /* Compteurs pour les filtres */ $counts = ['tous' => 0]; @@ -239,6 +300,18 @@ input[type=text], input[type=password] { label { font-size: .85rem; color: #cbd5e1; } .back { margin-bottom: 12px; display: inline-block; } .pager { display: flex; gap: 8px; margin-top: 16px; } +.navtabs { display: flex; gap: 8px; margin: 0 0 16px; } +.navtabs a { border: 1px solid #334155; padding: 5px 14px; border-radius: 99px; font-size: .85rem; text-decoration: none; color: #cbd5e1; } +.navtabs a.active { background: #0284c7; border-color: #0284c7; color: #fff; } +.invite-form { display: flex; gap: 10px; align-items: end; flex-wrap: wrap; margin-top: 10px; } +.invite-form label { margin: 0; } +.invite-form select { background: #0b1120; color: #e2e8f0; border: 1px solid #334155; border-radius: 8px; padding: 9px 11px; font-size: .9rem; } +.invite-box { margin-top: 14px; padding: 14px; border: 1px dashed #38bdf8; border-radius: 10px; background: #0c1a2b; display: flex; align-items: center; gap: 12px; flex-wrap: wrap; font-size: .9rem; } +.invite-code { font-size: 1.2rem; letter-spacing: .08em; font-weight: 700; color: #7dd3fc; font-family: ui-monospace, Consolas, monospace; } +table.list { width: 100%; border-collapse: collapse; font-size: .88rem; } +table.list th, table.list td { text-align: left; padding: 7px 8px; border-bottom: 1px solid #1e293b; vertical-align: middle; } +table.list th { color: #94a3b8; font-size: .72rem; text-transform: uppercase; letter-spacing: .05em; } +.login-register { text-align: center; margin-top: 14px; font-size: .85rem; } @@ -249,6 +322,7 @@ label { font-size: .85rem; color: #cbd5e1; }

🔒 Panneau des signalements

+
✅ Compte créé ! Connectez-vous avec vos identifiants.

@@ -264,6 +338,7 @@ label { font-size: .85rem; color: #cbd5e1; } +

@@ -281,6 +356,11 @@ label { font-size: .85rem; color: #cbd5e1; } + +
@@ -319,6 +399,11 @@ label { font-size: .85rem; color: #cbd5e1; } IP User-agent + + DiscordVoir le post dans le forum ↗ + + Discordpost créé (lien indisponible) + @@ -351,6 +436,118 @@ label { font-size: .85rem; color: #cbd5e1; } +query('SELECT * FROM invite_codes ORDER BY id DESC LIMIT 200')->fetchAll(); + $users = $pdo->query('SELECT id, username, created_at FROM admin_users ORDER BY id')->fetchAll(); + $userNames = []; + foreach ($users as $u) { + $userNames[(int) $u['id']] = (string) $u['username']; + } + $now = date('Y-m-d H:i:s'); +?> + +
+

🎟️ Générer un code d'invitation

+

Le code est à usage unique : donnez-le à la personne, elle l'utilise sur la page + admin/bugs/register.php pour créer son compte (nom + mot de passe).

+
+ + + + + +
+ +
+ 🎉 Nouveau code à donner : + + +
+ +
+ +
+

Codes générés ()

+ +

Aucun code pour l'instant.

+ + + + + + + + + + + + + +
CodeCrééExpireStatutUtilisé par
+ +
+ + + + +
+ +
+ +
+ +
+

👥 Comptes existants ()

+

Tous les comptes peuvent consulter et traiter les signalements. Chacun peut modifier son propre mot de passe ci-dessous.

+ +

Aucun compte.

+ + + + + + + + + +
NomCréé le
+ +
+ +
+

🔑 Mon mot de passe

+

Connecté en tant que . Le nouveau mot de passe doit faire au moins 8 caractères.

+
+ + + + + + + + + +
+
+ execute([':h' => $hash, ':id' => $existing['id']]); echo "✅ Mot de passe de « $user » réinitialisé.\n"; } else { - $ins = $pdo->prepare('INSERT INTO admin_users (username, password_hash) VALUES (:u, :h)'); - $ins->execute([':u' => $user, ':h' => $hash]); - echo "✅ Utilisateur « $user » créé.\n"; + $uid = fws_bugs_next_id($pdo, 'admin_users'); + $ins = $pdo->prepare('INSERT INTO admin_users (id, username, password_hash) VALUES (:id, :u, :h)'); + $ins->execute([':id' => $uid, ':u' => $user, ':h' => $hash]); + echo "✅ Utilisateur « $user » créé (id $uid).\n"; } echo "\nPanneau : https://fwslinux.fr/admin/bugs/\n"; diff --git a/admin/bugs/register.php b/admin/bugs/register.php new file mode 100644 index 0000000..1a2706a --- /dev/null +++ b/admin/bugs/register.php @@ -0,0 +1,157 @@ +beginTransaction(); + try { + $hash = password_hash($password, PASSWORD_DEFAULT); + $uid = fws_bugs_next_id($pdo, 'admin_users'); + $ins = $pdo->prepare('INSERT INTO admin_users (id, username, password_hash) VALUES (:id, :u, :h)'); + $ins->execute([':id' => $uid, ':u' => $username, ':h' => $hash]); + + $claim = $pdo->prepare("UPDATE invite_codes SET used_by = :uid, used_at = datetime('now') WHERE id = :id AND used_by IS NULL"); + $claim->execute([':uid' => $uid, ':id' => (int) $invite['id']]); + if ($claim->rowCount() !== 1) { + throw new RuntimeException('Code déjà utilisé entre-temps.'); + } + $pdo->commit(); + $ok = true; + } catch (Throwable $e) { + $pdo->rollBack(); + if ($pdo->errorInfo()[1] === 19 && strpos((string) $e->getMessage(), 'UNIQUE') !== false) { + $error = 'Ce nom d\'utilisateur est déjà pris. Choisissez-en un autre.'; + } else { + error_log('[fws-bugs] inscription : ' . $e->getMessage()); + $error = 'Erreur interne lors de l\'inscription. Réessayez.'; + } + } + } + } catch (Throwable $e) { + $error = 'Erreur base de données : ' . h($e->getMessage()); + } +} + +/* Succès → retour à la page de connexion avec un message */ +if ($ok) { + header('Location: index.php?registered=1'); + exit; +} + +$baseUrl = 'https://' . ($_SERVER['HTTP_HOST'] ?? 'fwslinux.fr'); +$codeValue = $submitted ? $code : ''; +$userValue = $submitted ? $username : ''; +?> + + + + + +Créer un compte — Signalements FWS + + + +
+
+

🎟️ Créer un compte

+

Tu as reçu un code d'invitation à usage unique de l'équipe FWS. + Saisis-le ci-dessous puis choisis ton nom d'utilisateur et ton mot de passe.

+ +
+ +
+ + + + + +
2 à 32 caractères : lettres, chiffres, . _ -
+ + + + + + + + + +
+ + ← Retour à la connexion +
+
+ + diff --git a/api/bugs.php b/api/bugs.php index 9434abf..f6a3791 100644 --- a/api/bugs.php +++ b/api/bugs.php @@ -12,6 +12,7 @@ declare(strict_types=1); require __DIR__ . '/bugs/db.php'; +require __DIR__ . '/bugs/discord.php'; /* Jamais d'avertissements/stack traces PHP visibles côté client */ ini_set('display_errors', '0'); @@ -116,15 +117,17 @@ if (fws_bugs_count_recent_for_ip($pdo, $ip) >= 25) { exit; } -/* Insertion */ +/* Insertion — l'id repart de 1 et saute ceux déjà pris */ try { + $bugId = fws_bugs_next_id($pdo, 'bug_reports'); $stmt = $pdo->prepare( 'INSERT INTO bug_reports - (app, version, type, title, description, email, system_info, logs, ip, user_agent) + (id, app, version, type, title, description, email, system_info, logs, ip, user_agent) VALUES - (:app, :version, :type, :title, :description, :email, :system_info, :logs, :ip, :ua)' + (:id, :app, :version, :type, :title, :description, :email, :system_info, :logs, :ip, :ua)' ); $stmt->execute([ + ':id' => $bugId, ':app' => $app, ':version' => $version, ':type' => $type !== '' ? $type : 'bug', @@ -146,9 +149,37 @@ try { http_response_code(201); echo json_encode([ 'ok' => true, - 'id' => (int) $pdo->lastInsertId(), + 'id' => $bugId, 'message' => 'Signalement enregistré. Merci !', ], JSON_UNESCAPED_UNICODE); + +/* Envoie la réponse au client tout de suite ; la notif Discord suit en arrière-plan. */ +if (function_exists('fastcgi_finish_request')) { + fastcgi_finish_request(); +} else { + flush(); +} + +/* Notification Discord (best-effort : n'affecte jamais la réponse de l'API) */ +try { + $discord = fws_bugs_discord_notify([ + 'id' => $bugId, + 'app' => $app, + 'version' => $version, + 'type' => $type !== '' ? $type : 'bug', + 'title' => $title, + 'description' => $description, + 'email' => $email, + 'system_info' => $systemInfo, + 'logs' => $logs, + 'status' => 'nouveau', + ]); + if (is_array($discord) && !empty($discord['thread_id'])) { + fws_bugs_save_discord_info($pdo, $bugId, (string) $discord['thread_id'], (string) ($discord['post_url'] ?? '')); + } +} catch (Throwable $e) { + error_log('[fws-bugs] discord : ' . $e->getMessage()); +} exit; /* ──────────────────────────────────────────── */ diff --git a/api/bugs/config.local.php.example b/api/bugs/config.local.php.example new file mode 100644 index 0000000..0fed076 --- /dev/null +++ b/api/bugs/config.local.php.example @@ -0,0 +1,36 @@ +/ + * + * 2) bot_token (optionnel mais recommandé) : token d'un bot Discord + * https://discord.com/developers/applications → New Application → Bot → + * Reset Token → invite-le dans ton serveur avec les permissions + * « Manage Threads » et « Manage Tags ». + * Avec un bot, les tags « Nouveau / En cours / Résolu / Ignoré » sont + * créés automatiquement et mis à jour quand le statut change sur le site. + * + * 3) tags (optionnel si bot) : IDs des tags créés à la main dans Discord. + * Sans bot : crée les tags dans le canal forum puis colle ici leurs IDs + * (Activer le mode développeur Discord → réseau du navigateur, ou via un + * outil type Discord API avec le bot). + * + * config.local.php n'est PAS commité (secret) — il est dans .gitignore. + */ +return [ + 'webhook_url' => 'https://discord.com/api/webhooks/REMPLACE_PAR_ID/REMPLACE_PAR_TOKEN', + 'bot_token' => '', + 'tags' => [ + 'nouveau' => '', + 'en_cours' => '', + 'resolu' => '', + 'ignore' => '', + ], +]; \ No newline at end of file diff --git a/api/bugs/db.php b/api/bugs/db.php index 5261c43..867f594 100644 --- a/api/bugs/db.php +++ b/api/bugs/db.php @@ -60,6 +60,21 @@ function fws_bugs_schema(PDO $pdo): void $pdo->exec('CREATE INDEX IF NOT EXISTS idx_reports_created ON bug_reports(created_at DESC)'); $pdo->exec('CREATE INDEX IF NOT EXISTS idx_reports_status ON bug_reports(status)'); + /* Migration : colonnes Discord (ajoutées sur les bases déjà existantes) */ + $cols = $pdo->query('PRAGMA table_info(bug_reports)')->fetchAll(); + $hasThread = false; + $hasUrl = false; + foreach ($cols as $c) { + if (($c['name'] ?? '') === 'discord_thread_id') $hasThread = true; + if (($c['name'] ?? '') === 'discord_post_url') $hasUrl = true; + } + if (!$hasThread) { + $pdo->exec("ALTER TABLE bug_reports ADD COLUMN discord_thread_id TEXT NOT NULL DEFAULT ''"); + } + if (!$hasUrl) { + $pdo->exec("ALTER TABLE bug_reports ADD COLUMN discord_post_url TEXT NOT NULL DEFAULT ''"); + } + $pdo->exec( 'CREATE TABLE IF NOT EXISTS admin_users ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -69,10 +84,94 @@ function fws_bugs_schema(PDO $pdo): void )' ); + /* Codes d'invitation à usage unique pour créer des comptes */ + $pdo->exec( + 'CREATE TABLE IF NOT EXISTS invite_codes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + code TEXT NOT NULL UNIQUE, + created_by TEXT NOT NULL DEFAULT \'\', + created_at TEXT NOT NULL DEFAULT (datetime(\'now\')), + expires_at TEXT, + used_by INTEGER, + used_at TEXT, + revoked_at TEXT + )' + ); + /* Schéma (re)créé : s'assurer que le fichier reste inscriptible par Apache */ @chmod(__DIR__ . '/data/fws_bugs.sqlite', 0666); } +/** + * Prochain identifiant libre pour une table, en repartant de 1 : + * si l'id 1 est déjà pris, on saute au plus petit id inutilisé. + */ +function fws_bugs_next_id(PDO $pdo, string $table): int +{ + if (!in_array($table, ['bug_reports', 'admin_users', 'invite_codes'], true)) { + throw new InvalidArgumentException('Table inconnue : ' . $table); + } + $used = []; + foreach ($pdo->query('SELECT id FROM ' . $table . ' ORDER BY id') as $row) { + $used[(int) $row['id']] = true; + } + $id = 1; + while (isset($used[$id])) { + $id++; + } + return $id; +} + +/** + * Génère un code d'invitation à usage unique (ex. « K7QM-2H4D-X9BP »). + * Alphabet sans caractères ambigus (pas de I/O/0/1). + */ +function fws_bugs_create_invite(PDO $pdo, string $createdBy, int $days): string +{ + $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; + for ($attempt = 0; $attempt < 5; $attempt++) { + $raw = ''; + for ($i = 0; $i < 12; $i++) { + $raw .= $alphabet[random_int(0, strlen($alphabet) - 1)]; + } + $code = substr($raw, 0, 4) . '-' . substr($raw, 4, 4) . '-' . substr($raw, 8, 4); + $expires = $days > 0 ? date('Y-m-d H:i:s', time() + $days * 86400) : null; + try { + $id = fws_bugs_next_id($pdo, 'invite_codes'); + $st = $pdo->prepare('INSERT INTO invite_codes (id, code, created_by, expires_at) VALUES (:id, :c, :b, :e)'); + $st->execute([':id' => $id, ':c' => $code, ':b' => $createdBy, ':e' => $expires]); + return $code; + } catch (Throwable $e) { + /* collision ultra improbable → on régénère */ + } + } + throw new RuntimeException('Impossible de générer un code d\'invitation.'); +} + +/** + * Cherche un code d'invitation (insensible à la casse et aux tirets). + */ +function fws_bugs_find_invite(PDO $pdo, string $code): ?array +{ + $norm = strtoupper(str_replace(['-', ' '], '', $code)); + if ($norm === '') { + return null; + } + $st = $pdo->prepare("SELECT * FROM invite_codes WHERE REPLACE(UPPER(code), '-', '') = :c LIMIT 1"); + $st->execute([':c' => $norm]); + $row = $st->fetch(); + return $row === false ? null : $row; +} + +/** + * Enregistre le lien du post Discord créé pour un signalement. + */ +function fws_bugs_save_discord_info(PDO $pdo, int $id, string $threadId, string $postUrl): void +{ + $st = $pdo->prepare('UPDATE bug_reports SET discord_thread_id = :t, discord_post_url = :u WHERE id = :id'); + $st->execute([':t' => $threadId, ':u' => $postUrl, ':id' => $id]); +} + /** * Nombre de signalements pour une IP sur la dernière heure (anti-flood). */ diff --git a/api/bugs/discord.php b/api/bugs/discord.php new file mode 100644 index 0000000..37ebb55 --- /dev/null +++ b/api/bugs/discord.php @@ -0,0 +1,357 @@ + '🆕 Nouveau', + 'en_cours' => '🔧 En cours', + 'resolu' => '✅ Résolu', + 'ignore' => '🙈 Ignoré', +]; + +/** + * Configuration lue depuis config.local.php (jamais commité). + * Accepte soit une simple chaîne (URL du webhook), soit un tableau : + * [ 'webhook_url' => ..., 'bot_token' => ..., 'tags' => [status => tagId] ] + */ +function fws_bugs_discord_config(): array +{ + static $cfg = null; + if ($cfg !== null) { + return $cfg; + } + $cfg = ['webhook' => '', 'bot_token' => '', 'tags' => []]; + $local = __DIR__ . '/config.local.php'; + if (is_file($local)) { + $v = require $local; + if (is_string($v)) { + $cfg['webhook'] = $v; + } elseif (is_array($v)) { + $cfg['webhook'] = (string) ($v['webhook_url'] ?? $v['webhook'] ?? ''); + $cfg['bot_token'] = (string) ($v['bot_token'] ?? ''); + $cfg['tags'] = is_array($v['tags'] ?? null) ? $v['tags'] : []; + } + } + $cfg['webhook'] = trim($cfg['webhook']); + if (strpos($cfg['webhook'], 'REMPLACE_PAR') !== false || strpos($cfg['webhook'], 'COLLE_ICI') !== false) { + $cfg['webhook'] = ''; + } + $cfg['bot_token'] = trim($cfg['bot_token']); + return $cfg; +} + +function fws_bugs_discord_enabled(): bool +{ + return fws_bugs_discord_config()['webhook'] !== ''; +} + +/** + * Appel API Discord générique (webhook ou endpoint canal avec bot). + * $auth = 'Bot xxx' pour les endpoints de canaux, '' pour le webhook. + * Retourne le JSON décodé, ou null en cas d'échec (erreur loggée). + */ +function fws_bugs_discord_api(string $method, string $url, array $payload = [], string $auth = ''): ?array +{ + $ch = curl_init($url); + $headers = [ + 'Content-Type: application/json', + 'User-Agent: FWS-Bugs/1.0 (https://fwslinux.fr)', + ]; + if ($auth !== '') { + $headers[] = 'Authorization: ' . $auth; + } + curl_setopt_array($ch, [ + CURLOPT_RETURNTRANSFER => true, + CURLOPT_HTTPHEADER => $headers, + CURLOPT_CONNECTTIMEOUT => 4, + CURLOPT_TIMEOUT => 8, + CURLOPT_SSL_VERIFYPEER => true, + ]); + if ($method === 'GET') { + curl_setopt($ch, CURLOPT_HTTPGET, true); + } else { + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); + } + $body = curl_exec($ch); + $code = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); + $err = curl_error($ch); + curl_close($ch); + + if ($code < 200 || $code >= 300 || $body === false) { + error_log(sprintf( + '[fws-bugs] discord %s %s : HTTP %d %s', + $method, + preg_replace('#//[^/]+/webhooks/\d+/[^/?]+#', '//discord.com/api/webhooks//', $url) ?? $url, + $code, + $err !== '' ? $err : substr((string) $body, 0, 250) + )); + return null; + } + $decoded = json_decode((string) $body, true); + if (is_array($decoded)) { + return $decoded; + } + /* 2xx sans corps JSON (ex : 204 No Content des POST sans wait=true) = + succès : on renvoie [] pour ne pas être confondu avec un échec. */ + return []; +} + +/** + * Infos du webhook (channel_id, guild_id) via GET /webhooks/{id}/{token}. + */ +function fws_bugs_discord_webhook_info(): ?array +{ + static $info = false; + if ($info !== false) { + return $info; + } + $info = null; + $hook = fws_bugs_discord_config()['webhook']; + if ($hook === '') { + return null; + } + if (!preg_match('#/webhooks/(\d+)/([^/?]+)#', $hook, $m)) { + return null; + } + $res = fws_bugs_discord_api('GET', 'https://discord.com/api/webhooks/' . $m[1] . '/' . $m[2]); + if (is_array($res) && !empty($res['channel_id'])) { + $info = $res; + } + return $info; +} + +/** + * IDs des tags Discord pour chaque statut du site. + * Sans bot : utilise les IDs renseignés dans config.local.php. + * Avec bot : les récupère depuis le canal et les crée s'ils manquent. + * + * @return array [statut => tagId] + */ +function fws_bugs_discord_ensure_tags(): array +{ + static $tags = null; + if ($tags !== null) { + return $tags; + } + $cfg = fws_bugs_discord_config(); + + $tags = []; + foreach (($cfg['tags'] ?? []) as $k => $v) { + if (isset(FWS_BUGS_STATUS_LABELS[$k]) && is_string($v) && trim($v) !== '') { + $tags[$k] = trim($v); + } + } + if ($cfg['bot_token'] === '') { + return $tags; + } + + $info = fws_bugs_discord_webhook_info(); + $channelId = is_array($info) ? (string) ($info['channel_id'] ?? '') : ''; + if ($channelId === '') { + return $tags; + } + $bot = 'Bot ' . $cfg['bot_token']; + $channelUrl = 'https://discord.com/api/channels/' . $channelId; + + $channel = fws_bugs_discord_api('GET', $channelUrl, [], $bot); + $available = is_array($channel) ? ($channel['available_tags'] ?? []) : []; + $byName = []; + foreach ($available as $t) { + if (is_array($t) && !empty($t['name']) && !empty($t['id'])) { + $byName[(string) $t['name']] = (string) $t['id']; + } + } + + $defs = [ + 'nouveau' => ['Nouveau', '🆕'], + 'en_cours' => ['En cours', '🔧'], + 'resolu' => ['Résolu', '✅'], + 'ignore' => ['Ignoré', '🙈'], + ]; + foreach ($defs as $status => [$tagName, $emoji]) { + if (isset($tags[$status])) { + continue; + } + $tagId = $byName[$tagName] ?? ''; + if ($tagId === '') { + $created = fws_bugs_discord_api( + 'POST', + $channelUrl . '/tags', + ['name' => $tagName, 'emoji_name' => $emoji, 'moderated' => false], + $bot + ); + $tagId = is_array($created) ? (string) ($created['id'] ?? '') : ''; + } + if ($tagId !== '') { + $tags[$status] = $tagId; + } + } + return $tags; +} + +/** + * Crée le post dans le canal forum et y envoie le résumé + les logs. + * Best-effort : ne renvoie jamais d'erreur. + * + * @param array $bug colonnes du signalement (app, version, type, title, + * description, email, system_info, logs, status) + * @return array|null ['thread_id' => ..., 'post_url' => ...] ou null en échec + */ +function fws_bugs_discord_notify(array $bug): ?array +{ + $cfg = fws_bugs_discord_config(); + if ($cfg['webhook'] === '') { + return null; + } + $base = rtrim($cfg['webhook'], '/'); + + $title = trim((string) ($bug['title'] ?? '')); + if ($title === '') { + $title = 'Signalement de bug'; + } + $name = mb_substr($title, 0, 95); // 100 max côté Discord + + $desc = trim((string) ($bug['description'] ?? '')); + $sys = trim((string) ($bug['system_info'] ?? '')); + $email = trim((string) ($bug['email'] ?? '')); + $status = isset(FWS_BUGS_STATUS_LABELS[$bug['status'] ?? '']) ? (string) $bug['status'] : 'nouveau'; + + $lines = []; + $lines[] = '**App :** ' . ($bug['app'] !== '' ? $bug['app'] : '—') + . ' · **Version :** ' . ($bug['version'] !== '' ? $bug['version'] : '—') + . ' · **Type :** ' . ($bug['type'] !== '' ? $bug['type'] : 'bug'); + if ($desc !== '') { + $lines[] = ''; + $lines[] = $desc; + } + if ($sys !== '') { + $lines[] = ''; + $lines[] = '**Système / matériel :**'; + $lines[] = $sys; + } + if ($email !== '') { + $lines[] = ''; + $lines[] = '**Contact :** ' . $email; + } + $summary = mb_substr(implode("\n", $lines), 0, 1800); + + /* Créer le post : le webhook doit être sur un canal FORUM. Discord crée + le post dès qu'on passe thread_name (+ tag via applied_tags), et + renvoie le message (wait=true) dont channel_id est l'id du post. */ + $payload = [ + 'content' => $summary, + 'thread_name' => $name, + ]; + $tags = fws_bugs_discord_ensure_tags(); + if (isset($tags[$status])) { + $payload['applied_tags'] = [$tags[$status]]; + } + + $first = fws_bugs_discord_api('POST', $base . '?wait=true', $payload); + $threadId = is_array($first) ? (string) ($first['channel_id'] ?? '') : ''; + if ($threadId === '') { + error_log('[fws-bugs] discord : échec création du post « ' . $name . ' »'); + return null; + } + + /* URL du post pour l'admin (guild_id via les infos du webhook) */ + $postUrl = ''; + $info = fws_bugs_discord_webhook_info(); + if (is_array($info) && !empty($info['guild_id'])) { + $postUrl = 'https://discord.com/channels/' . $info['guild_id'] . '/' . $threadId; + } + + /* ── Logs par morceaux (1900 car. max, 12 messages max) ── */ + $logs = trim((string) ($bug['logs'] ?? '')); + if ($logs !== '') { + $chunks = []; + $cur = ''; + foreach (preg_split('/\r?\n/', $logs) as $line) { + if ($cur !== '' && mb_strlen($cur) + mb_strlen($line) + 1 > 1850) { + $chunks[] = $cur; + $cur = ''; + } + $cur .= ($cur === '' ? '' : "\n") . $line; + } + if ($cur !== '') { + $chunks[] = $cur; + } + + $msgUrl = $base . '?thread_id=' . $threadId; + $maxMsgs = 12; + foreach (array_slice($chunks, 0, $maxMsgs) as $chunk) { + /* Pas d'en-tête « Logs (N/M) » : chaque message aligne la suite + des logs, ce qui donne un fil continu dans le post. */ + $body = str_contains($chunk, '```') + ? $chunk + : "```\n" . $chunk . "\n```"; + if (mb_strlen($body) > 1990) { + $body = mb_substr($body, 0, 1990); + } + if (fws_bugs_discord_api('POST', $msgUrl, ['content' => $body]) === null) { + break; // Discord refuse → on s'arrête proprement + } + } + } + + return ['thread_id' => $threadId, 'post_url' => $postUrl]; +} + +/** + * Préviens Discord quand le statut d'un signalement change sur le site. + * Poste un message dans le fil, et met à jour le tag si un bot est configuré. + * + * @param array $bug id, thread_id, old_status, new_status, actor + */ +function fws_bugs_discord_status_change(array $bug): void +{ + $cfg = fws_bugs_discord_config(); + $threadId = trim((string) ($bug['thread_id'] ?? '')); + if ($cfg['webhook'] === '' || $threadId === '') { + return; + } + + $old = isset(FWS_BUGS_STATUS_LABELS[$bug['old_status'] ?? '']) ? FWS_BUGS_STATUS_LABELS[$bug['old_status']] : (string) ($bug['old_status'] ?? '?'); + $new = isset(FWS_BUGS_STATUS_LABELS[$bug['new_status'] ?? '']) ? FWS_BUGS_STATUS_LABELS[$bug['new_status']] : (string) ($bug['new_status'] ?? '?'); + $actor = trim((string) ($bug['actor'] ?? '')); + + $msg = '📌 **Statut mis à jour** : ' . $old . ' → **' . $new . '**'; + if ($actor !== '') { + $msg .= "\nPar : " . $actor; + } + fws_bugs_discord_api('POST', $cfg['webhook'] . '?thread_id=' . $threadId, ['content' => mb_substr($msg, 0, 1900)]); + + /* Mise à jour du tag : possible seulement avec un bot (MANAGE_THREADS) */ + if ($cfg['bot_token'] !== '') { + $info = fws_bugs_discord_webhook_info(); + $channelId = is_array($info) ? (string) ($info['channel_id'] ?? '') : ''; + $tags = fws_bugs_discord_ensure_tags(); + $newStatus = (string) ($bug['new_status'] ?? ''); + if ($channelId !== '' && isset($tags[$newStatus])) { + fws_bugs_discord_api( + 'PUT', + 'https://discord.com/api/channels/' . $channelId . '/threads/' . $threadId . '/applied-tags', + ['applied_tags' => [$tags[$newStatus]]], + 'Bot ' . $cfg['bot_token'] + ); + } + } +} \ No newline at end of file