Files
FWS-Website/api/bugs/discord.php
BlackAngelTV 5a52191599 feat(api): remove size and rate limits from the bug report API
The API is consumed by curl/scripts that need to push full installation
logs, but field truncation (150k chars) and a 25-per-hour IP cap were
rejecting or silently cutting those payloads. Discord log chunks are now
streamed instead of being built in memory, so oversized logs no longer
blow up the notifier.
2026-10-02 20:59:11 +02:00

366 lines
13 KiB
PHP

<?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;
}
/**
* Envoie un morceau de logs dans le fil, encadré pour rester sous la limite
* Discord. Renvoie false si Discord refuse.
*/
function fws_bugs_discord_send_log_chunk(string $msgUrl, string $chunk): bool
{
/* 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);
}
return fws_bugs_discord_api('POST', $msgUrl, ['content' => $body]) !== null;
}
/**
* 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 !== '') {
/* L'API accepte des logs de taille illimitée : on découpe donc à la
volée et on s'arrête dès que le quota de messages est atteint, au
lieu de construire le tableau complet en mémoire. */
$msgUrl = $base . '?thread_id=' . $threadId;
$maxMsgs = 12;
$sent = 0;
$cur = '';
foreach (preg_split('/\r?\n/', $logs) as $line) {
if ($cur !== '' && mb_strlen($cur) + mb_strlen($line) + 1 > 1850) {
if (!fws_bugs_discord_send_log_chunk($msgUrl, $cur)) {
break; // Discord refuse → on s'arrête proprement
}
$cur = '';
if (++$sent >= $maxMsgs) {
break;
}
}
$cur .= ($cur === '' ? '' : "\n") . $line;
}
if ($cur !== '' && $sent < $maxMsgs) {
fws_bugs_discord_send_log_chunk($msgUrl, $cur);
}
}
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']
);
}
}
}