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

+197
View File
@@ -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; }
</style>
</head>
<body>
@@ -249,6 +322,7 @@ label { font-size: .85rem; color: #cbd5e1; }
<div class="login-box">
<div class="card">
<h1>🔒 Panneau des signalements</h1>
<?php if (($_GET['registered'] ?? '') === '1'): ?><div class="flash ok">✅ Compte créé ! Connectez-vous avec vos identifiants.</div><?php endif; ?>
<?php if ($error): ?><div class="flash err"><?= h($error) ?></div><?php endif; ?>
<?php if ($counts['tous'] === 0): ?>
<p style="font-size:.85rem;color:#94a3b8">
@@ -264,6 +338,7 @@ label { font-size: .85rem; color: #cbd5e1; }
<input type="password" id="password" name="password" required>
<button class="btn primary" type="submit" style="width:100%;padding:10px">Se connecter</button>
</form>
<p class="login-register">Pas encore de compte ? <a href="register.php">S'inscrire avec un code d'invitation</a></p>
</div>
</div>
@@ -281,6 +356,11 @@ label { font-size: .85rem; color: #cbd5e1; }
</form>
</header>
<div class="navtabs">
<a href="index.php" class="<?= $view_invites ? '' : 'active' ?>">🐞 Signalements</a>
<a href="index.php?view=invites" class="<?= $view_invites ? 'active' : '' ?>">👥 Invitations & comptes</a>
</div>
<?php if ($error): ?><div class="flash err"><?= h($error) ?></div><?php endif; ?>
<?php if ($notice): ?><div class="flash ok"><?= h($notice) ?></div><?php endif; ?>
@@ -319,6 +399,11 @@ label { font-size: .85rem; color: #cbd5e1; }
<?php endif; ?>
<tr><td class="k">IP</td><td><?= h($r['ip'] !== '' ? $r['ip'] : '?') ?></td></tr>
<tr><td class="k">User-agent</td><td style="font-size:.78rem;color:#94a3b8"><?= h($r['user_agent']) ?></td></tr>
<?php if (!empty($r['discord_post_url'])): ?>
<tr><td class="k">Discord</td><td><a href="<?= h($r['discord_post_url']) ?>" target="_blank" rel="noopener">Voir le post dans le forum ↗</a></td></tr>
<?php elseif (!empty($r['discord_thread_id'])): ?>
<tr><td class="k">Discord</td><td style="color:#94a3b8">post créé (lien indisponible)</td></tr>
<?php endif; ?>
</table>
<?php if ($r['logs'] !== ''): ?>
@@ -351,6 +436,118 @@ label { font-size: .85rem; color: #cbd5e1; }
</div>
<?php endif; /* fin détail */ ?>
<?php elseif ($view_invites): /* ─────────── INVITATIONS & COMPTES ─────────── */
$invites = $pdo->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');
?>
<div class="card">
<h3>🎟️ Générer un code d'invitation</h3>
<p style="font-size:.85rem;color:#94a3b8">Le code est <strong>à usage unique</strong> : donnez-le à la personne, elle l'utilise sur la page
<a href="register.php" target="_blank" rel="noopener">admin/bugs/register.php</a> pour créer son compte (nom + mot de passe).</p>
<form method="post" class="invite-form">
<input type="hidden" name="action" value="gen_invite">
<input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
<label for="days">Valable</label>
<select name="days" id="days">
<option value="1">1 jour</option>
<option value="7" selected>7 jours</option>
<option value="30">30 jours</option>
<option value="90">90 jours</option>
<option value="0">Sans expiration</option>
</select>
<button class="btn primary" type="submit">Générer le code</button>
</form>
<?php if ($freshInvite !== ''): ?>
<div class="invite-box">
<span>🎉 Nouveau code à donner :</span>
<code class="invite-code" id="freshCode"><?= h($freshInvite) ?></code>
<button class="btn small" type="button"
onclick="var t=document.getElementById('freshCode').textContent.trim();if(navigator.clipboard){navigator.clipboard.writeText(t);}this.textContent='✅ Copié';">📋 Copier</button>
</div>
<?php endif; ?>
</div>
<div class="card">
<h3>Codes générés (<?= count($invites) ?>)</h3>
<?php if (!$invites): ?>
<p class="empty">Aucun code pour l'instant.</p>
<?php else: ?>
<table class="list">
<tr><th>Code</th><th>Créé</th><th>Expire</th><th>Statut</th><th>Utilisé par</th><th></th></tr>
<?php foreach ($invites as $inv):
$isRevoked = $inv['revoked_at'] !== null;
$isUsed = $inv['used_by'] !== null;
$isExpired = !$isUsed && !$isRevoked && $inv['expires_at'] !== null && $inv['expires_at'] < $now;
if ($isRevoked) { $stLabel = 'Révoqué'; $stColor = '#f87171'; }
elseif ($isUsed) { $stLabel = 'Utilisé'; $stColor = '#94a3b8'; }
elseif ($isExpired) { $stLabel = 'Expiré'; $stColor = '#fbbf24'; }
else { $stLabel = 'Actif'; $stColor = '#4ade80'; }
?>
<tr>
<td style="font-family:ui-monospace,Consolas,monospace;letter-spacing:.05em"><?= h($inv['code']) ?></td>
<td><?= h(format_date((string) $inv['created_at'])) ?><?= $inv['created_by'] !== '' ? ' · ' . h($inv['created_by']) : '' ?></td>
<td><?= $inv['expires_at'] !== null ? h(format_date((string) $inv['expires_at'])) : '∞ jamais' ?></td>
<td><span class="badge" style="background:<?= $stColor ?>22;color:<?= $stColor ?>"><?= $stLabel ?></span></td>
<td><?= $inv['used_by'] !== null
? h($userNames[(int) $inv['used_by']] ?? '#'.$inv['used_by']) . ' · ' . h(format_date((string) $inv['used_at']))
: '' ?></td>
<td style="text-align:right">
<?php if (!$isUsed && !$isRevoked && !$isExpired): ?>
<form class="inline" method="post" onsubmit="return confirm('Révoquer ce code ? Il ne fonctionnera plus.')">
<input type="hidden" name="action" value="revoke_invite">
<input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
<input type="hidden" name="invite_id" value="<?= (int) $inv['id'] ?>">
<button class="btn small danger" type="submit">Révoquer</button>
</form>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
</div>
<div class="card">
<h3>👥 Comptes existants (<?= count($users) ?>)</h3>
<p style="font-size:.85rem;color:#94a3b8">Tous les comptes peuvent consulter et traiter les signalements. Chacun peut modifier son propre mot de passe ci-dessous.</p>
<?php if (!$users): ?>
<p class="empty">Aucun compte.</p>
<?php else: ?>
<table class="list">
<tr><th>Nom</th><th>Créé le</th></tr>
<?php foreach ($users as $u): ?>
<tr>
<td><?= h($u['username']) ?></td>
<td><?= h(format_date((string) $u['created_at'])) ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
</div>
<div class="card">
<h3>🔑 Mon mot de passe</h3>
<p style="font-size:.85rem;color:#94a3b8">Connecté en tant que <strong><?= h($user['name']) ?></strong>. Le nouveau mot de passe doit faire au moins 8 caractères.</p>
<form method="post" style="display:grid;gap:2px;max-width:420px">
<input type="hidden" name="action" value="change_password">
<input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
<label for="current_password">Mot de passe actuel</label>
<input type="password" id="current_password" name="current_password" required autocomplete="current-password">
<label for="new_password">Nouveau mot de passe</label>
<input type="password" id="new_password" name="new_password" required minlength="8" autocomplete="new-password">
<label for="confirm_password">Confirmer le nouveau mot de passe</label>
<input type="password" id="confirm_password" name="confirm_password" required minlength="8" autocomplete="new-password">
<button class="btn primary" type="submit" style="justify-self:start;margin-top:4px">Mettre à jour le mot de passe</button>
</form>
</div>
<?php else: /* ─────────── LISTE ─────────── */
$filter = $_GET['status'] ?? 'tous';
+4 -3
View File
@@ -93,9 +93,10 @@ if ($existing !== false) {
$up->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";
+157
View File
@@ -0,0 +1,157 @@
<?php
/**
* FWS Linux — Inscription au panneau des signalements.
*
* La personne reçoit un code d'invitation À USAGE UNIQUE (généré dans le
* panneau admin, onglet « Invitations & comptes »), puis crée ici son
* compte avec un nom d'utilisateur et un mot de passe.
*
* URL : https://fwslinux.fr/admin/bugs/register.php
*/
declare(strict_types=1);
require __DIR__ . '/../../api/bugs/db.php';
function h(?string $s): string
{
return htmlspecialchars((string) $s, ENT_QUOTES, 'UTF-8');
}
$error = null;
$ok = false;
/* Petit anti-spam : champ piège */
$honeypot = trim((string) ($_POST['website'] ?? ''));
$submitted = ($_SERVER['REQUEST_METHOD'] === 'POST') && $honeypot === '';
if ($submitted) {
$code = trim((string) ($_POST['code'] ?? ''));
$username = trim((string) ($_POST['username'] ?? ''));
$password = (string) ($_POST['password'] ?? '');
$confirm = (string) ($_POST['password2'] ?? '');
try {
$pdo = fws_bugs_db();
/* 1) Le code est-il valable ? */
$invite = fws_bugs_find_invite($pdo, $code);
if ($invite === null) {
$error = 'Ce code d\'invitation est inconnu. Vérifiez qu\'il a bien été copié.';
} elseif ($invite['revoked_at'] !== null) {
$error = 'Ce code d\'invitation a été révoqué. Demandez-en un nouveau.';
} elseif ($invite['used_by'] !== null) {
$error = 'Ce code d\'invitation a déjà été utilisé.';
} elseif ($invite['expires_at'] !== null && $invite['expires_at'] < date('Y-m-d H:i:s')) {
$error = 'Ce code d\'invitation a expiré. Demandez-en un nouveau.';
} elseif (!preg_match('/^[A-Za-z0-9_.\-]{2,32}$/', $username)) {
$error = 'Nom d\'utilisateur invalide (2 à 32 caractères : lettres, chiffres, . _ -).';
} elseif (strlen($password) < 8) {
$error = 'Mot de passe trop court (8 caractères minimum).';
} elseif ($password !== $confirm) {
$error = 'Les deux mots de passe ne correspondent pas.';
}
/* 2) Création du compte + consommation du code (transaction) */
if ($error === null) {
$pdo->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 : '';
?>
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Créer un compte — Signalements FWS</title>
<style>
:root { color-scheme: dark; }
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; background: #0f172a; color: #e2e8f0; }
.wrap { max-width: 520px; margin: 0 auto; padding: 40px 16px; }
.card { background: #111c33; border: 1px solid #1e293b; border-radius: 14px; padding: 28px; }
h1 { font-size: 1.25rem; margin-top: 0; }
label { font-size: .85rem; color: #cbd5e1; display: block; margin-top: 14px; }
input[type=text], input[type=password], input[type=code] {
width: 100%; padding: 10px 12px; margin: 6px 0 2px;
background: #0b1120; border: 1px solid #334155; border-radius: 8px; color: #e2e8f0; font-size: .95rem;
}
input.code { font-family: ui-monospace, Consolas, monospace; letter-spacing: .08em; text-transform: uppercase; }
button { margin-top: 20px; padding: 11px 18px; border: 0; border-radius: 8px; background: #0284c7; color: #fff; font-size: 1rem; cursor: pointer; width: 100%; }
button:hover { background: #0369a1; }
.flash { padding: 10px 12px; border-radius: 8px; font-size: .88rem; margin-bottom: 14px; }
.flash.err { background: #3d1414; color: #ffa198; }
.hint { font-size: .8rem; color: #64748b; margin-top: 4px; }
.back { display: inline-block; margin-top: 18px; font-size: .85rem; color: #94a3b8; text-decoration: none; }
.note { font-size: .85rem; color: #94a3b8; background: #0b1120; border: 1px solid #1e293b; border-radius: 8px; padding: 10px 12px; margin-bottom: 16px; line-height: 1.5; }
</style>
</head>
<body>
<div class="wrap">
<div class="card">
<h1>🎟️ Créer un compte</h1>
<p class="note">Tu as reçu un <strong>code d'invitation à usage unique</strong> de l'équipe FWS.
Saisis-le ci-dessous puis choisis ton nom d'utilisateur et ton mot de passe.</p>
<?php if ($error): ?><div class="flash err"><?= h($error) ?></div><?php endif; ?>
<form method="post" autocomplete="on">
<label for="code">Code d'invitation</label>
<input type="text" id="code" name="code" class="code" required autofocus
value="<?= h($codeValue) ?>" placeholder="K7QM-2H4D-X9BP">
<label for="username">Nom d'utilisateur</label>
<input type="text" id="username" name="username" required value="<?= h($userValue) ?>"
placeholder="ex : alice" pattern="[A-Za-z0-9_.\-]{2,32}">
<div class="hint">2 à 32 caractères : lettres, chiffres, . _ -</div>
<label for="password">Mot de passe</label>
<input type="password" id="password" name="password" required minlength="8" placeholder="8 caractères minimum">
<label for="password2">Confirmer le mot de passe</label>
<input type="password" id="password2" name="password2" required minlength="8">
<input name="website" style="display:none" tabindex="-1" autocomplete="off">
<button type="submit">Créer mon compte</button>
</form>
<a class="back" href="index.php">← Retour à la connexion</a>
</div>
</div>
</body>
</html>
+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']
);
}
}
}