Feat(bugs): notifications Discord, invitations et comptes

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.
This commit is contained in:
BlackAngelTV committed 2026-09-07 13:47:59 +02:00
1 parent f7605ae6f0
commit f94e6e1f15
7 files changed
+885 -7

No files matched your search

+35 -4
View File
@@ -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;
/* ──────────────────────────────────────────── */
+36
View File
@@ -0,0 +1,36 @@
<?php
/**
* FWS Linux — configuration locale des notifications Discord.
*
* Copie ce fichier en « config.local.php » et remplis-le :
*
* cp config.local.php.example config.local.php
*
* 1) webhook_url (obligatoire) : webhook du canal FORUM
* Discord → canal forum → Paramètres → Intégrations → Webhooks → Copier.
* L'URL ressemble à : https://discord.com/api/webhooks/<id>/<token>
*
* 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' => '',
],
];
+99
View File
@@ -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).
*/
+357
View File
@@ -0,0 +1,357 @@
<?php
/**
* FWS Linux — notification Discord des signalements de bugs (canal FORUM).
*
* Chaque signalement crée un NOUVEAU POST dans le canal forum via le webhook
* (thread_name), avec le tag du statut appliqué, puis le résumé + les logs.
* Quand un admin change le statut sur le site, un message est posté dans le
* fil Discord (et le tag est mis à jour si un bot_token est configuré).
*
* Configuration : api/bugs/config.local.php
* - webhook_url : webhook du canal FORUM (obligatoire)
* - bot_token : token d'un bot Discord (optionnel)
* Avec bot → les tags « Nouveau / En cours / Résolu / Ignoré » sont
* créés automatiquement et mis à jour quand le statut
* change sur le site.
* Sans bot → crée les tags dans l'UI Discord et renseigne leurs IDs
* dans le tableau « tags » du fichier de config.
*/
declare(strict_types=1);
const FWS_BUGS_STATUS_LABELS = [
'nouveau' => '🆕 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/<id>/<token>', $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<string,string> [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']
);
}
}
}