Files
FWS-Website/api/bugs/db.php
T
BlackAngelTV 82168e2678 Masquer toutes les erreurs : 404 doux, API blindée, aucune fuite PHP
- /api/bugs/ et tout chemin inconnu sous /api/ : 404 JSON propre
- 403/404 Apache : ErrorDocument vers page.php, sans page Apache brute
- fichiers internes (inc/, corps de pages, db.php, init.php...) : 404
- erreurs PHP : display_errors off, handlers exception/fatal, réponses
  JSON ou HTML discrètes, journalisation locale gitignorée
2026-09-16 11:40:43 +02:00

413 lines
15 KiB
PHP

<?php
/**
* FWS Linux — base de données des signalements de bugs.
* SQLite, fichier stocké dans api/bugs/data/ (répertoire protégé par .htaccess).
*/
declare(strict_types=1);
/* Filet de sécurité : aucune erreur PHP ne fuit jamais côté client
* (JSON sous /api/, page HTML discrète sinon). */
require_once dirname(__DIR__, 2) . '/inc/errors.php';
/* ───────────── UTF-8 (partagé avec inc/site.php, gardes function_exists) ── */
if (!function_exists('fws_utf8_str')) {
/** UTF-8 valide obligatoire : les octets invalides (Windows-1252…) sont
* convertis, sinon json_encode échoue et casse tout l'appelant. */
function fws_utf8_str(string $s): string
{
if (mb_check_encoding($s, 'UTF-8')) {
return $s;
}
$conv = @mb_convert_encoding($s, 'UTF-8', 'Windows-1252');
return is_string($conv) ? $conv : (string) mb_convert_encoding($s, 'UTF-8', 'UTF-8');
}
function fws_utf8_arr(array $a): array
{
$out = [];
foreach ($a as $k => $v) {
if (is_array($v)) {
$out[$k] = fws_utf8_arr($v);
} elseif (is_string($v)) {
$out[$k] = fws_utf8_str($v);
} else {
$out[$k] = $v;
}
}
return $out;
}
}
function fws_bugs_db(): PDO
{
static $pdo = null;
if ($pdo instanceof PDO) {
return $pdo;
}
$dir = __DIR__ . '/data';
if (!is_dir($dir)) {
mkdir($dir, 0775, true);
}
$pdo = new PDO('sqlite:' . $dir . '/fws_bugs.sqlite');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
/* Sur un bind-mount Docker Desktop, tout appartient à root : on rend le
fichier DB inscriptible par Apache (www-data) quoi qu'il arrive. */
@chmod($dir . '/fws_bugs.sqlite', 0666);
@chmod($dir, 0777);
/* Pas de WAL : sur un bind-mount Docker Desktop, les fichiers -wal/-shm
créés tantôt par root (CLI) tantôt par www-data (Apache) se marchent
dessus. Le mode journal classique + fichier 666 est plus fiable. */
$pdo->exec('PRAGMA journal_mode = DELETE');
$pdo->exec('PRAGMA busy_timeout = 5000');
fws_bugs_schema($pdo);
@chmod($dir . '/fws_bugs.sqlite', 0666);
return $pdo;
}
function fws_bugs_schema(PDO $pdo): void
{
$pdo->exec(
'CREATE TABLE IF NOT EXISTS bug_reports (
id INTEGER PRIMARY KEY AUTOINCREMENT,
app TEXT NOT NULL DEFAULT \'\',
version TEXT NOT NULL DEFAULT \'\',
type TEXT NOT NULL DEFAULT \'bug\',
title TEXT NOT NULL DEFAULT \'\',
description TEXT NOT NULL DEFAULT \'\',
email TEXT NOT NULL DEFAULT \'\',
system_info TEXT NOT NULL DEFAULT \'\',
logs TEXT NOT NULL DEFAULT \'\',
ip TEXT NOT NULL DEFAULT \'\',
user_agent TEXT NOT NULL DEFAULT \'\',
status TEXT NOT NULL DEFAULT \'nouveau\',
created_at TEXT NOT NULL DEFAULT (datetime(\'now\'))
)'
);
$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,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime(\'now\'))
)'
);
/* 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
)'
);
/* Paquets du site (données gérées depuis le panneau admin) */
$pdo->exec(
'CREATE TABLE IF NOT EXISTS packages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
slug TEXT NOT NULL DEFAULT \'\',
name TEXT NOT NULL DEFAULT \'\',
tagline TEXT NOT NULL DEFAULT \'\',
description TEXT NOT NULL DEFAULT \'\',
since TEXT,
since_label TEXT NOT NULL DEFAULT \'FWS\',
latest_name TEXT NOT NULL DEFAULT \'\',
latest_date TEXT,
links TEXT NOT NULL DEFAULT \'[]\',
screens TEXT NOT NULL DEFAULT \'[]\',
changelog TEXT NOT NULL DEFAULT \'[]\',
updated_at TEXT NOT NULL DEFAULT (datetime(\'now\'))
)'
);
/* 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', 'packages'], 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).
*/
function fws_bugs_count_recent_for_ip(PDO $pdo, string $ip): int
{
$st = $pdo->prepare(
"SELECT COUNT(*) FROM bug_reports
WHERE ip = :ip AND created_at > datetime('now', '-1 hour')"
);
$st->execute([':ip' => $ip]);
return (int) $st->fetchColumn();
}
/**
* IP réelle en tenant compte du proxy (X-Forwarded-For).
*/
function fws_bugs_client_ip(): string
{
$xff = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '';
if ($xff !== '') {
$parts = explode(',', $xff);
$ip = trim($parts[0]);
if ($ip !== '') {
return substr($ip, 0, 64);
}
}
return substr((string) ($_SERVER['REMOTE_ADDR'] ?? ''), 0, 64);
}
/**
* Comptes autorisés à lancer un build ISO (onglet « Build ISO » du panneau).
* Le build pilote le moteur Docker : à n'accorder qu'aux comptes de confiance.
*/
function fws_bugs_can_build(string $username): bool
{
return in_array(strtolower(trim($username)), ['admin'], true);
}
/* ───────────────────────── paquets du site ───────────────────────── */
/**
* Convertit une ligne brute de la table `packages` au format JSON
* utilisé par le site (identique à l'ancien packages.json).
*/
function fws_packages_row_to_json(array $r): array
{
$latest = null;
if ((string) ($r['latest_name'] ?? '') !== '') {
$latest = [
'name' => fws_utf8_str((string) $r['latest_name']),
'date' => ($r['latest_date'] ?? null) !== null ? fws_utf8_str((string) $r['latest_date']) : null,
];
}
return fws_utf8_arr([
'id' => (string) $r['slug'],
'name' => (string) $r['name'],
'tagline' => (string) $r['tagline'],
'description' => (string) $r['description'],
'since' => ($r['since'] ?? null) !== null ? (string) $r['since'] : null,
'sinceLabel' => (string) ($r['since_label'] ?? 'FWS'),
'latest' => $latest,
'links' => json_decode((string) $r['links'], true) ?: [],
'screens' => json_decode((string) $r['screens'], true) ?: [],
'changelog' => json_decode((string) $r['changelog'], true) ?: [],
]);
}
/**
* Tous les paquets, ordonnés par id (l'ordre = la position sur le site,
* ex : /?p/paquets/1/ est l'id 1).
*/
function fws_packages_all(PDO $pdo): array
{
$out = [];
foreach ($pdo->query('SELECT * FROM packages ORDER BY id ASC') as $r) {
$out[] = fws_packages_row_to_json($r);
}
return $out;
}
/**
* Enregistre un paquet (insert si id = 0, sinon update).
* Les colonnes JSON (links, screens, changelog) sont passées en tableaux PHP.
*/
function fws_packages_save(PDO $pdo, array $d): int
{
$id = (int) ($d['id'] ?? 0);
$slug = trim((string) ($d['slug'] ?? ''));
if ($slug === '') {
$slug = trim(preg_replace('/[^a-zA-Z0-9]+/', '-', (string) ($d['name'] ?? '')) ?? '', '-');
}
$sinceLabel = trim((string) ($d['since_label'] ?? ''));
if ($sinceLabel === '') {
$sinceLabel = 'FWS';
}
$data = [
':slug' => fws_utf8_str($slug),
':name' => fws_utf8_str(trim((string) ($d['name'] ?? ''))),
':tagline' => fws_utf8_str(trim((string) ($d['tagline'] ?? ''))),
':description' => fws_utf8_str(trim((string) ($d['description'] ?? ''))),
':since' => ($d['since'] ?? '') !== '' ? (string) $d['since'] : null,
':since_label' => fws_utf8_str($sinceLabel),
':latest_name' => fws_utf8_str(trim((string) ($d['latest_name'] ?? ''))),
':latest_date' => ($d['latest_date'] ?? '') !== '' ? (string) $d['latest_date'] : null,
':links' => (string) json_encode(fws_utf8_arr((array) ($d['links'] ?? [])), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
/* 5 captures maximum par paquet (gardée de force côté serveur). */
':screens' => (string) json_encode(array_slice(fws_utf8_arr((array) ($d['screens'] ?? [])), 0, 5), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
':changelog' => (string) json_encode(fws_utf8_arr((array) ($d['changelog'] ?? [])), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
];
if ($id > 0) {
$data[':id'] = $id;
$st = $pdo->prepare(
'UPDATE packages SET slug = :slug, name = :name, tagline = :tagline,
description = :description, since = :since, since_label = :since_label,
latest_name = :latest_name, latest_date = :latest_date,
links = :links, screens = :screens, changelog = :changelog,
updated_at = datetime(\'now\') WHERE id = :id'
);
$st->execute($data);
return $id;
}
$id = fws_bugs_next_id($pdo, 'packages');
$data[':id'] = $id;
$st = $pdo->prepare(
'INSERT INTO packages (id, slug, name, tagline, description, since, since_label,
latest_name, latest_date, links, screens, changelog)
VALUES (:id, :slug, :name, :tagline, :description, :since, :since_label,
:latest_name, :latest_date, :links, :screens, :changelog)'
);
$st->execute($data);
return $id;
}
/**
* Supprime un paquet (l'id pourra être réutilisé ensuite).
*/
function fws_packages_delete(PDO $pdo, int $id): void
{
$st = $pdo->prepare('DELETE FROM packages WHERE id = :id');
$st->execute([':id' => $id]);
}
/**
* Import initial : si la table `packages` est vide et que l'ancien
* packages.json existe toujours, on l'importe une seule fois.
*/
function fws_packages_seed_if_empty(PDO $pdo): int
{
$count = (int) $pdo->query('SELECT COUNT(*) FROM packages')->fetchColumn();
if ($count > 0) {
return 0;
}
$file = dirname(__DIR__) . '/../p/paquets/packages.json';
if (!is_file($file)) {
return 0;
}
$data = json_decode((string) file_get_contents($file), true);
if (!is_array($data)) {
return 0;
}
$n = 0;
foreach ($data as $p) {
if (!is_array($p)) {
continue;
}
fws_packages_save($pdo, [
'id' => 0,
'slug' => (string) ($p['id'] ?? ''),
'name' => (string) ($p['name'] ?? ''),
'tagline' => (string) ($p['tagline'] ?? ''),
'description' => (string) ($p['description'] ?? ''),
'since' => (string) ($p['since'] ?? ''),
'since_label' => (string) ($p['sinceLabel'] ?? 'FWS'),
'latest_name' => (string) ($p['latest']['name'] ?? ''),
'latest_date' => (string) ($p['latest']['date'] ?? ''),
'links' => $p['links'] ?? [],
'screens' => $p['screens'] ?? [],
'changelog' => $p['changelog'] ?? [],
]);
$n++;
}
return $n;
}