Feat(site): rendu serveur PHP — paquets en SQLite, releases Gitea, build ISO

- Front controller page.php + inc/site.php : coquille et pages rendues
  en PHP (accueil, dl, paquets, paquets/N, equipe, contact, 404) ; les
  URLs ne changent pas et l'apparence est conservée.
- Paquets stockés dans la base SQLite partagée (table packages),
  éditables depuis l'onglet 📦 Paquets de /admin/bugs, avec bouton de
  synchronisation des releases depuis l'API Gitea du dépôt lié.
  Repli automatique sur packages.json si la base est vide.
- Releases ISO de la page Téléchargements récupérées côté serveur
  (Gitea FWS/ISO sinon GitHub) avec cache fichier 10 min ; note de
  release rendue en Markdown serveur (Voir plus / Voir moins).
- Suppression du routeur SPA et des chargeurs JS devenus inutiles
  (app.js, packages.js, downloads.js, creators-loader.js, index.html) ;
  restent nav.js, note-toggle.js et hero-carousel.js.
- Panneau admin : onglet Build ISO (git pull sur main, build.sh avec
  repli setup-aur.sh, terminal des logs en direct), durcissement UTF-8
  à l'écriture des paquets (json_encode ne casse plus sur des accents
  mal encodés), 404 réels et gardes d'accès direct sur les corps PHP.
This commit is contained in:
BlackAngelTV committed 2026-09-14 13:19:37 +02:00
1 parent 34b3f1cf3c
commit 1775adceaa
34 files changed
+2799 -1862

No files matched your search

+558
View File
@@ -0,0 +1,558 @@
<?php
/**
* FWS — Onglet « Build ISO » du panneau admin des signalements.
*
* URL : admin/bugs/build.php
*
* Réservé aux comptes autorisés (voir fws_bugs_can_build() dans
* api/bugs/db.php, par défaut : « admin »). Lance le pipeline
* admin/bugs/run-build.sh dans un process détaché (nohup) et expose un
* mini-terminal : les logs sont lus en direct par polling (act=tail) et les
* actions start / stop / clear sont protégées par CSRF comme le reste du
* panneau.
*/
declare(strict_types=1);
require_once __DIR__ . '/../../api/bugs/db.php';
session_set_cookie_params([
'httponly' => true,
'samesite' => 'Lax',
'secure' => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https'),
]);
session_start();
function h_build(string $s): string
{
return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}
function current_user_build(): ?array
{
return isset($_SESSION['admin_user_id']) ? [
'id' => (int) $_SESSION['admin_user_id'],
'name' => (string) $_SESSION['admin_username'],
] : null;
}
function csrf_token_build(): string
{
if (empty($_SESSION['csrf'])) {
$_SESSION['csrf'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf'];
}
function csrf_ok_build(): bool
{
return hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '');
}
/** Lecture du token Gitea stocké localement (api/bugs/data/build/git-auth.env, jamais commité). */
function build_gitea_auth_build(): array
{
global $DATA;
$f = $DATA . '/git-auth.env';
$out = ['username' => '', 'token' => ''];
if (is_file($f)) {
$s = (string) file_get_contents($f);
if (preg_match("/^FWS_GIT_USER='([^']*)'$/m", $s, $m) === 1) {
$out['username'] = $m[1];
}
if (preg_match("/^FWS_GIT_TOKEN='([^']*)'$/m", $s, $m) === 1) {
$out['token'] = $m[1];
}
}
return $out;
}
/** Écriture du token Gitea (token vide → fichier retiré). */
function build_save_gitea_auth_build(string $username, string $token): void
{
global $DATA;
if (!is_dir($DATA)) {
@mkdir($DATA, 0775, true);
}
$f = $DATA . '/git-auth.env';
if ($token === '') {
@unlink($f);
return;
}
$sq = static fn(string $v): string => str_replace(["\\", "'"], ["\\\\", "\\'"], $v);
file_put_contents(
$f,
"FWS_GIT_USER='" . $sq($username !== '' ? $username : 'fws') . "'\n" .
"FWS_GIT_TOKEN='" . $sq($token) . "'\n",
LOCK_EX
);
@chmod($f, 0600);
}
/* ── Chemins (sous api/bugs/data/, jamais commité) ── */
$DATA = __DIR__ . '/../../api/bugs/data/build';
$LOG = $DATA . '/build.log';
$PIDF = $DATA . '/build.pid';
$RUN = __DIR__ . '/run-build.sh';
$user = current_user_build();
/** PID du process de build s'il tourne encore, sinon false. */
function build_running_build(): int|false
{
global $PIDF;
$pid = is_file($PIDF) ? trim((string) file_get_contents($PIDF)) : '';
if ($pid === '' || !ctype_digit($pid)) {
return false;
}
exec('kill -0 ' . (int) $pid . ' 2>/dev/null', $out, $rc);
return $rc === 0 ? (int) $pid : false;
}
/** Dernier code de sortie du pipeline lu dans le log (null si pas encore terminé). */
function build_last_rc_build(): ?int
{
global $LOG;
if (!is_file($LOG) || filesize($LOG) === 0) {
return null;
}
$tail = (string) file_get_contents($LOG, false, null, max(0, filesize($LOG) - 4096));
if (preg_match('/Fin du pipeline \(code (-?\d+)\)/', $tail, $m) === 1) {
return (int) $m[1];
}
return null;
}
/* ───────────────────────── API (act=…) ───────────────────────── */
$act = $_GET['act'] ?? $_POST['act'] ?? '';
$isApi = $act !== '';
if ($isApi) {
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
if ($user === null) {
http_response_code(401);
exit(json_encode(['ok' => false, 'error' => 'Non connecté.']));
}
if (!fws_bugs_can_build($user['name'])) {
http_response_code(403);
exit(json_encode(['ok' => false, 'error' => 'Ce compte n’est pas autorisé à lancer des builds.']));
}
$running = build_running_build();
if ($act === 'state') {
echo json_encode(['ok' => true, 'running' => $running !== false, 'pid' => $running]);
exit;
}
if ($act === 'auth_status') {
$a = build_gitea_auth_build();
echo json_encode(['ok' => true, 'configured' => $a['token'] !== '', 'username' => $a['username']]);
exit;
}
if ($act === 'tail') {
$pos = max(-1, (int) ($_GET['pos'] ?? 0));
$size = is_file($LOG) ? (int) filesize($LOG) : 0;
$start = 0;
if ($pos === -1) {
// Premier chargement : ne ramener que la fin d'un éventuel vieux log.
$start = max(0, $size - 150000);
} elseif ($pos > 0 && $pos <= $size) {
$start = $pos;
}
$text = '';
if ($size > $start) {
$fh = fopen($LOG, 'rb');
if ($fh !== false) {
if ($start > 0) {
fseek($fh, $start);
}
$raw = (string) stream_get_contents($fh);
fclose($fh);
// Nettoyage : codes ANSI retirés, octets invalides ignorés.
$text = (string) preg_replace('/\x1B\[[0-9;?]*[ -\/]*[@-~]/', '', $raw);
$text = (string) preg_replace('/\x1B\][^\x07\x1B]*(\x07|\x1B\\)/', '', $text);
$text = iconv('UTF-8', 'UTF-8//IGNORE', $text);
}
}
$running = build_running_build();
echo json_encode([
'ok' => true,
'running' => $running !== false,
'pos' => (int) $size,
'rc' => build_last_rc_build(),
'text' => $text,
]);
exit;
}
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST' || !csrf_ok_build()) {
http_response_code(403);
exit(json_encode(['ok' => false, 'error' => 'Jeton de sécurité invalide.']));
}
if ($act === 'start') {
if ($running !== false) {
http_response_code(409);
exit(json_encode(['ok' => false, 'error' => 'Un build est déjà en cours.']));
}
exec('timeout 8 docker info >/dev/null 2>&1', $out, $drc);
if ($drc !== 0) {
http_response_code(503);
exit(json_encode(['ok' => false, 'error' => 'Moteur Docker injoignable (Docker Desktop arrêté ?).']));
}
if (!is_dir($DATA) && !@mkdir($DATA, 0775, true)) {
http_response_code(500);
exit(json_encode(['ok' => false, 'error' => 'Impossible de créer ' . $DATA]));
}
@unlink($LOG);
@unlink($PIDF);
$cmd = 'nohup bash ' . escapeshellarg($RUN) . ' </dev/null >> ' . escapeshellarg($LOG) . ' 2>&1 & echo $!';
exec($cmd, $out2, $src);
$pid = (int) ($out2[0] ?? 0);
if ($pid > 0) {
file_put_contents($PIDF, (string) $pid);
}
echo json_encode(['ok' => $src === 0 && $pid > 0, 'pid' => $pid]);
exit;
}
if ($act === 'stop') {
exec('docker rm -f fws-iso-build >/dev/null 2>&1', $o1, $rc1);
$stopped = $running;
if ($running !== false) {
exec('kill ' . $running . ' 2>/dev/null');
@unlink($PIDF);
}
echo json_encode(['ok' => true, 'stopped' => $stopped !== false || $rc1 === 0]);
exit;
}
if ($act === 'clear') {
if ($running !== false) {
http_response_code(409);
exit(json_encode(['ok' => false, 'error' => 'Arrêtez d’abord le build en cours.']));
}
@unlink($LOG);
@unlink($PIDF);
echo json_encode(['ok' => true]);
exit;
}
if ($act === 'save_auth') {
build_save_gitea_auth_build(
trim((string) ($_POST['username'] ?? '')),
trim((string) ($_POST['token'] ?? ''))
);
$a = build_gitea_auth_build();
echo json_encode(['ok' => true, 'configured' => $a['token'] !== '', 'username' => $a['username']]);
exit;
}
http_response_code(400);
exit(json_encode(['ok' => false, 'error' => 'Action inconnue.']));
}
/* ───────────────────────── PAGES ───────────────────────── */
if ($user === null) {
header('Location: index.php');
exit;
}
$allowed = fws_bugs_can_build($user['name']);
header('Content-Type: text/html; charset=utf-8');
?><!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex,nofollow">
<title>Build ISO — FWS Linux</title>
<style>
:root { color-scheme: dark; }
* { box-sizing: border-box; }
body {
margin: 0; font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
background: #0b1120; color: #e2e8f0; line-height: 1.5;
}
.wrap { max-width: 1000px; margin: 0 auto; padding: 24px 16px 80px; }
header.top {
display: flex; align-items: center; justify-content: space-between;
gap: 12px; padding: 14px 0; border-bottom: 1px solid #1e293b; margin-bottom: 20px;
}
header.top h1 { font-size: 1.15rem; margin: 0; }
header.top .sub { font-size: .8rem; color: #94a3b8; }
a { color: #38bdf8; text-decoration: none; }
a:hover { text-decoration: underline; }
.btn {
display: inline-block; border: 1px solid #334155; background: #1e293b; color: #e2e8f0;
padding: 6px 12px; border-radius: 8px; cursor: pointer; font-size: .85rem;
text-decoration: none; line-height: 1.4;
}
.btn:hover { background: #334155; text-decoration: none; }
.btn.primary { background: #0284c7; border-color: #0284c7; color: #fff; }
.btn.danger { background: transparent; border-color: #7f1d1d; color: #f87171; }
.btn.danger:hover { background: #7f1d1d; color: #fff; }
.btn:disabled { opacity: .45; cursor: not-allowed; }
.card {
background: #111a2e; border: 1px solid #1e293b; border-radius: 12px;
padding: 16px; margin-bottom: 12px;
}
.card h3 { margin: 0 0 4px; font-size: 1rem; }
.card .meta { font-size: .78rem; color: #94a3b8; display: flex; flex-wrap: wrap; gap: 6px 14px; margin-bottom: 8px; }
.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; }
.flash { padding: 10px 14px; border-radius: 10px; margin-bottom: 14px; font-size: .9rem; }
.flash.err { background: #450a0a; color: #fca5a5; border: 1px solid #7f1d1d; }
.status-line { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.dot { width: 10px; height: 10px; border-radius: 50%; background: #64748b; flex: none; }
.dot.run { background: #4ade80; animation: pulse 1.2s ease-in-out infinite; }
@keyframes pulse { 50% { opacity: .25; } }
pre.term {
background: #020617; border: 1px solid #1e293b; border-radius: 8px;
padding: 12px; overflow: auto; max-height: 62vh; font-size: .76rem; line-height: 1.45;
white-space: pre-wrap; word-break: break-word; font-family: ui-monospace, Consolas, "Cascadia Mono", monospace;
color: #bae6fd;
}
.actions { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-top: 12px; }
.hint { font-size: .78rem; color: #64748b; margin-top: 10px; }
.hint code { background: #0b1120; border: 1px solid #1e293b; padding: 1px 5px; border-radius: 6px; }
#authForm { display: flex; gap: 10px; flex-wrap: wrap; align-items: end; margin-top: 6px; }
#authForm label { font-size: .78rem; color: #94a3b8; display: block; margin-bottom: 2px; }
#authForm input[type=text], #authForm input[type=password] {
width: 230px; padding: 7px 9px; background: #0b1120; border: 1px solid #334155;
border-radius: 8px; color: #e2e8f0; font-size: .9rem;
}
#authState { font-size: .8rem; }
</style>
</head>
<body>
<div class="wrap">
<header class="top">
<div>
<h1>🔨 Build ISO</h1>
<div class="sub">Connecté : <?= h_build($user['name']) ?> · dépôt : <code>D:\FWS-ISO</code> (branche main)</div>
</div>
<form method="post" action="index.php">
<input type="hidden" name="action" value="logout">
<input type="hidden" name="csrf" value="<?= h_build(csrf_token_build()) ?>">
<button class="btn" type="submit">Déconnexion</button>
</form>
</header>
<div class="navtabs">
<a href="index.php">🐞 Signalements</a>
<a href="index.php?view=invites">👥 Invitations &amp; comptes</a>
<a href="build.php" class="active">🔨 Build ISO</a>
</div>
<?php if (!$allowed): ?>
<div class="card">
<h3>Accès restreint</h3>
<p>Votre compte (<strong><?= h_build($user['name']) ?></strong>) n'est pas autorisé à lancer des builds.
Seul le compte <code>admin</code> le peut (voir <code>fws_bugs_can_build()</code> dans <code>api/bugs/db.php</code>).</p>
<a class="btn" href="index.php">← Retour aux signalements</a>
</div>
<?php else: ?>
<div class="card">
<h3>🔑 Accès Gitea (pour le git pull)</h3>
<p style="font-size:.82rem;color:#cbd5e1;margin:6px 0 2px">
Le dépôt <code>D:\FWS-ISO</code> est privé et le build tourne dans un conteneur sans tes identifiants
Windows : crée un token dans Gitea (<em>Settings → Applications → Generate New Token</em>, lecture du dépôt)
puis enregistre-le ici. Il n'est stocké que sur ce serveur — jamais commité, jamais affiché dans les logs.
</p>
<span id="authState">…</span>
<form id="authForm">
<div>
<label for="gUser">Utilisateur Gitea (défaut : fws)</label>
<input type="text" id="gUser" name="username" autocomplete="off">
</div>
<div>
<label for="gToken">Token</label>
<input type="password" id="gToken" name="token" autocomplete="off" placeholder="token de lecture">
</div>
<button class="btn primary" type="submit">Enregistrer</button>
<button class="btn danger" type="button" id="gClear">Retirer</button>
</form>
</div>
<div class="card">
<h3>🖥️ Terminal du build</h3>
<div class="meta">
<span id="stateLabel">État : inconnu…</span>
<span>· Git Bash lancerait ici : <code style="font-size:.95em">git checkout main &amp;&amp; git pull &amp;&amp; bash build.sh</code></span>
</div>
<pre class="term" id="term">Chargement du terminal…</pre>
<div class="actions">
<button class="btn primary" id="btnStart" type="button">▶ Lancer le build</button>
<button class="btn danger" id="btnStop" type="button">⏹ Arrêter</button>
<button class="btn" id="btnClear" type="button">🗑 Effacer le log</button>
<span id="rcLabel"></span>
</div>
<p class="hint">
Le build se déroule dans un conteneur <code>archlinux</code> jetable (via Docker Desktop, comme
<code>build.sh</code> à la main) : passage sur <code>main</code> → <code>git pull</code> → <code>bash build.sh</code> ;
en cas d'échec de build, <code>bash setup-aur.sh</code> est lancé puis <code>build.sh</code> est relancé.
Si le checkout de <code>main</code> est bloqué par des modifications locales non commitées dans
<code>D:\FWS-ISO</code>, le build s'arrête proprement sans rien toucher. L'ISO sort dans
<code>D:\FWS-ISO\out\</code>. Peut prendre 30 min et plus — laissez l'onglet ouvert, les logs défilent en direct.
</p>
</div>
<?php endif; ?>
</div>
<script>
(() => {
const allowed = <?= $allowed ? 'true' : 'false' ?>;
if (!allowed) return;
const CSRF = <?= json_encode(csrf_token_build()) ?>;
const term = document.getElementById('term');
const btnS = document.getElementById('btnStart');
const btnT = document.getElementById('btnStop');
const btnC = document.getElementById('btnClear');
const stateL = document.getElementById('stateLabel');
const rcL = document.getElementById('rcLabel');
const csrfP = new URLSearchParams();
csrfP.set('csrf', CSRF);
let pos = -1;
let running = null;
let finishedRc = null;
const authState = document.getElementById('authState');
const authForm = document.getElementById('authForm');
const gUser = document.getElementById('gUser');
const gToken = document.getElementById('gToken');
const gClear = document.getElementById('gClear');
async function refreshAuth() {
const r = await api('auth_status');
if (r.json && r.json.ok) {
authState.textContent = r.json.configured
? '✅ Token Gitea enregistré' + (r.json.username ? ' (compte : ' + r.json.username + ')' : '')
: '⚠️ Aucun token Gitea : le git pull échouera (dépôt privé).';
}
}
authForm.addEventListener('submit', async (e) => {
e.preventDefault();
const p = new URLSearchParams(csrfP);
p.set('username', gUser.value.trim());
p.set('token', gToken.value);
const r = await api('save_auth', p);
if (r.json && r.json.ok) {
gUser.value = gToken.value = '';
await refreshAuth();
} else {
alert(r.json && r.json.error ? r.json.error : 'Erreur.');
}
});
gClear.addEventListener('click', async () => {
if (!confirm('Retirer le token Gitea enregistré ?')) return;
const p = new URLSearchParams(csrfP);
p.set('username', '');
p.set('token', '');
const r = await api('save_auth', p);
if (r.json && r.json.ok) await refreshAuth();
});
function stick() {
const near = term.scrollHeight - term.scrollTop - term.clientHeight < 90;
if (near || running !== false) term.scrollTop = term.scrollHeight;
}
function setUI() {
btnS.disabled = running === true;
btnT.disabled = running !== true;
btnC.disabled = running === true;
const dot = document.querySelector('.status-line .dot') ||
(() => { const d = document.createElement('span'); d.className = 'dot'; stateL.prepend(d); return d; })();
dot.className = 'dot' + (running ? ' run' : '');
if (running === true) {
stateL.textContent = 'État : build en cours… ';
} else if (running === false) {
stateL.textContent = 'État : inactif. ';
}
}
async function api(act, body) {
const opt = body
? { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body }
: { method: 'GET' };
const r = await fetch('build.php?act=' + encodeURIComponent(act), opt);
return { status: r.status, json: await r.json().catch(() => null) };
}
async function poll() {
try {
const r = await fetch('build.php?act=tail&pos=' + pos);
const j = await r.json();
if (!j || j.ok !== true) return;
if (j.text && j.text !== '') {
const wasEmpty = term.textContent === 'Chargement du terminal…';
if (wasEmpty) term.textContent = '';
const atEnd = term.scrollHeight - term.scrollTop - term.clientHeight < 90;
term.textContent += j.text;
if (running !== false || atEnd) term.scrollTop = term.scrollHeight;
}
pos = j.pos;
if (j.running !== running) {
running = j.running;
if (!running && j.rc !== null) {
finishedRc = j.rc;
rcL.textContent = 'Code de sortie : ' + j.rc + (j.rc === 0 ? ' ✅' : ' ❌');
}
if (running) { rcL.textContent = ''; finishedRc = null; }
setUI();
}
} catch (e) { /* requête interrompue (navigation…) : on réessaie au prochain tick */ }
}
btnS.addEventListener('click', async () => {
if (running === true) return;
if (!confirm('Lancer le build ISO ?\n\nPassage sur main → git pull → bash build.sh'
+ ' (repli setup-aur.sh en cas d' + '\u2019échec).\nLe dépôt D:\\FWS-ISO ne doit pas être utilisé ailleurs pendant le build.')) return;
const p = new URLSearchParams(csrfP); p.set('act', 'start');
const r = await api('start', p);
if (r.json && r.json.ok) { pos = -1; await poll(); } else { alert(r.json && r.json.error ? r.json.error : 'Erreur au démarrage.'); }
});
btnT.addEventListener('click', async () => {
if (running !== true) return;
if (!confirm('Arrêter le build en cours ?')) return;
const p = new URLSearchParams(csrfP); p.set('act', 'stop');
const r = await api('stop', p);
if (r.json && r.json.ok) { await poll(); } else { alert(r.json && r.json.error ? r.json.error : 'Erreur à l' + '\u2019arrêt.'); }
});
btnC.addEventListener('click', async () => {
if (running === true) return;
const p = new URLSearchParams(csrfP); p.set('act', 'clear');
const r = await api('clear', p);
if (r.json && r.json.ok) { term.textContent = ''; pos = -1; rcL.textContent = ''; } else { alert(r.json && r.json.error ? r.json.error : 'Erreur.'); }
});
setUI();
refreshAuth();
poll();
setInterval(poll, 1000);
})();
</script>
</body>
</html>
+319 -2
View File
@@ -81,11 +81,101 @@ function excerpt(string $s, int $len = 140): string
return mb_substr($s, 0, $len - 1) . '…';
}
/* ── Paquets : parsing / formatage des champs « une ligne par entrée » ── */
function parse_pipe_lines(string $raw, int $fields): array
{
$out = [];
foreach (preg_split('/\r?\n/', $raw) as $line) {
$line = trim($line);
if ($line === '') {
continue;
}
$parts = array_map('trim', explode('|', $line));
$parts = array_pad($parts, $fields, '');
$out[] = array_slice($parts, 0, $fields);
}
return $out;
}
function links_from_lines(string $raw): array
{
$out = [];
foreach (parse_pipe_lines($raw, 2) as $pair) {
[$label, $url] = $pair;
if ($url === '') {
$url = $label;
$label = '';
}
if ($url === '') {
continue;
}
$out[] = ['label' => $label !== '' ? $label : $url, 'url' => $url];
}
return $out;
}
function changelog_from_lines(string $raw): array
{
$out = [];
foreach (parse_pipe_lines($raw, 3) as $parts) {
[$version, $date, $notes] = $parts;
if ($version === '' && $date === '' && $notes === '') {
continue;
}
$out[] = ['version' => $version, 'date' => $date !== '' ? $date : null, 'notes' => $notes];
}
return $out;
}
function screens_from_lines(string $raw): array
{
$out = [];
foreach (parse_pipe_lines($raw, 3) as $parts) {
[$src, $alt, $caption] = $parts;
if ($src === '') {
continue;
}
$out[] = ['src' => $src, 'alt' => $alt !== '' ? $alt : null, 'caption' => $caption !== '' ? $caption : null];
}
return $out;
}
function lines_from_links(array $links): string
{
$lines = [];
foreach ($links as $l) {
$lines[] = ($l['label'] ?? '') . ' | ' . ($l['url'] ?? '');
}
return implode("\n", $lines);
}
function lines_from_changelog(array $cl): string
{
$lines = [];
foreach ($cl as $e) {
$lines[] = ($e['version'] ?? '') . ' | ' . ($e['date'] ?? '') . ' | ' . ($e['notes'] ?? '');
}
return implode("\n", $lines);
}
function lines_from_screens(array $s): string
{
$lines = [];
foreach ($s as $e) {
$lines[] = ($e['src'] ?? '') . ' | ' . ($e['alt'] ?? '') . ' | ' . ($e['caption'] ?? '');
}
return implode("\n", $lines);
}
/* ───────────────────────── actions POST ───────────────────────── */
$error = null;
$notice = null;
$freshInvite = '';
/* Message ponctuel d'une action précédente (stocké en session pour la redirection) */
$flash = $_SESSION['flash'] ?? null;
unset($_SESSION['flash']);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$action = $_POST['action'] ?? '';
@@ -197,12 +287,119 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$up->execute([':h' => password_hash($new, PASSWORD_DEFAULT), ':id' => $uid]);
$notice = 'Mot de passe modifié avec succès.';
}
} elseif ($action === 'pkg_save') {
$name = trim((string) ($_POST['name'] ?? ''));
if ($name === '') {
$error = 'Le nom du paquet est obligatoire.';
} else {
$pdo = fws_bugs_db();
$savedId = fws_packages_save($pdo, [
'id' => (int) ($_POST['pkg_id'] ?? 0),
'slug' => (string) ($_POST['slug'] ?? ''),
'name' => $name,
'tagline' => (string) ($_POST['tagline'] ?? ''),
'description' => (string) ($_POST['description'] ?? ''),
'since' => (string) ($_POST['since'] ?? ''),
'since_label' => (string) ($_POST['since_label'] ?? ''),
'latest_name' => (string) ($_POST['latest_name'] ?? ''),
'latest_date' => (string) ($_POST['latest_date'] ?? ''),
'links' => links_from_lines((string) ($_POST['links'] ?? '')),
'screens' => screens_from_lines((string) ($_POST['screens'] ?? '')),
'changelog' => changelog_from_lines((string) ($_POST['changelog'] ?? '')),
]);
$wasEdit = (int) ($_POST['pkg_id'] ?? 0) > 0;
$_SESSION['flash'] = ['ok' => $wasEdit
? "Paquet « $name » mis à jour."
: "Paquet « $name » créé."];
header('Location: index.php?view=packages');
exit;
}
} elseif ($action === 'pkg_delete') {
$pkgId = (int) ($_POST['pkg_id'] ?? 0);
$pdo = fws_bugs_db();
fws_packages_delete($pdo, $pkgId);
$_SESSION['flash'] = ['ok' => "Paquet #$pkgId supprimé."];
header('Location: index.php?view=packages');
exit;
} elseif ($action === 'pkg_sync_gitea') {
/* Rafraîchit latest + historique d'un paquet depuis l'API Gitea
(le dépôt est déduit de ses liens « Gitea » / « Releases »). */
$pkgId = (int) ($_POST['pkg_id'] ?? 0);
$pdo = fws_bugs_db();
$st = $pdo->prepare('SELECT * FROM packages WHERE id = :id');
$st->execute([':id' => $pkgId]);
$row = $st->fetch();
if ($row === false) {
$_SESSION['flash'] = ['err' => "Paquet #$pkgId introuvable."];
header('Location: index.php?view=packages');
exit;
}
$links = json_decode((string) $row['links'], true) ?: [];
$repo = null;
foreach ($links as $link) {
if (preg_match('~^https?://gitea\.nocode-var\.tech/([^/]+)/([^/]+)/?$~i', (string) ($link['url'] ?? ''), $m)) {
$repo = ['owner' => $m[1], 'name' => $m[2]];
break;
}
}
if ($repo === null) {
$_SESSION['flash'] = ['err' => 'Aucun lien Gitea (gitea.nocode-var.tech) dans ce paquet : synchronisation impossible.'];
header('Location: index.php?view=packages');
exit;
}
require_once __DIR__ . '/../../inc/site.php';
$releases = fws_site_gitea_releases($repo['owner'], $repo['name']);
if ($releases === []) {
$_SESSION['flash'] = ['err' => 'Gitea ne renvoie aucune release pour ' . $repo['owner'] . '/' . $repo['name'] . '.'];
header('Location: index.php?view=packages');
exit;
}
$first = $releases[0];
$changelog = [];
foreach ($releases as $rel) {
$notes = trim(strip_tags((string) fws_markdown((string) ($rel['body'] ?? ''))));
if (mb_strlen($notes) > 200) {
$notes = rtrim(mb_substr($notes, 0, 200)) . '…';
}
$changelog[] = [
'version' => (string) ($rel['tag_name'] ?? ''),
'date' => isset($rel['published_at']) ? substr((string) $rel['published_at'], 0, 10) : null,
'notes' => $notes,
];
}
fws_packages_save($pdo, [
'id' => $pkgId,
'slug' => (string) $row['slug'],
'name' => (string) $row['name'],
'tagline' => (string) $row['tagline'],
'description' => (string) $row['description'],
'since' => (string) ($row['since'] ?? ''),
'since_label' => (string) $row['since_label'],
'latest_name' => (string) ($first['tag_name'] ?? ''),
'latest_date' => isset($first['published_at']) ? substr((string) $first['published_at'], 0, 10) : '',
'links' => $links,
'screens' => json_decode((string) $row['screens'], true) ?: [],
'changelog' => $changelog,
]);
$_SESSION['flash'] = ['ok' => 'Paquet « ' . $row['name'] . ' » synchronisé depuis Gitea (' . count($releases) . ' releases).'];
header('Location: index.php?view=packages');
exit;
}
}
}
$user = current_user();
/* Message ponctuel laissé par une action (après redirection) */
if ($flash !== null) {
if (!empty($flash['err'])) {
$error = (string) $flash['err'];
}
if (!empty($flash['ok'])) {
$notice = (string) $flash['ok'];
}
}
/* ───────────────────────── routage vues ───────────────────────── */
try {
@@ -214,6 +411,8 @@ try {
$view_id = (int) ($_GET['id'] ?? 0);
$view_invites = ($_GET['view'] ?? '') === 'invites' && $view_id === 0;
$view_packages = ($_GET['view'] ?? '') === 'packages' && $view_id === 0;
$edit_pkg_id = $view_packages ? (int) ($_GET['edit'] ?? 0) : 0;
/* Compteurs pour les filtres */
$counts = ['tous' => 0];
@@ -293,10 +492,13 @@ form.inline { display: inline; }
.login-box { max-width: 380px; margin: 12vh auto; }
.login-box .card { padding: 28px; }
.login-box h1 { font-size: 1.25rem; margin-top: 0; }
input[type=text], input[type=password] {
input[type=text], input[type=password], input[type=date], textarea {
width: 100%; padding: 9px 11px; margin: 6px 0 14px;
background: #0b1120; border: 1px solid #334155; border-radius: 8px; color: #e2e8f0; font-size: .95rem;
font-family: inherit;
}
textarea { resize: vertical; min-height: 70px; }
.grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 0 16px; }
label { font-size: .85rem; color: #cbd5e1; }
.back { margin-bottom: 12px; display: inline-block; }
.pager { display: flex; gap: 8px; margin-top: 16px; }
@@ -357,8 +559,10 @@ table.list th { color: #94a3b8; font-size: .72rem; text-transform: uppercase; le
</header>
<div class="navtabs">
<a href="index.php" class="<?= $view_invites ? '' : 'active' ?>">🐞 Signalements</a>
<a href="index.php" class="<?= ($view_invites || $view_packages) ? '' : 'active' ?>">🐞 Signalements</a>
<a href="index.php?view=invites" class="<?= $view_invites ? 'active' : '' ?>">👥 Invitations & comptes</a>
<a href="index.php?view=packages" class="<?= $view_packages ? 'active' : '' ?>">📦 Paquets</a>
<?php if (fws_bugs_can_build($user['name'])): ?><a href="build.php">🔨 Build ISO</a><?php endif; ?>
</div>
<?php if ($error): ?><div class="flash err"><?= h($error) ?></div><?php endif; ?>
@@ -548,6 +752,119 @@ table.list th { color: #94a3b8; font-size: .72rem; text-transform: uppercase; le
</form>
</div>
<?php elseif ($view_packages): /* ─────────── PAQUETS ─────────── */
$pkgRows = $pdo->query('SELECT * FROM packages ORDER BY id ASC')->fetchAll();
$editing = null;
if ($edit_pkg_id > 0) {
foreach ($pkgRows as $pr) {
if ((int) $pr['id'] === $edit_pkg_id) {
$editing = $pr;
break;
}
}
if ($editing === null) {
$edit_pkg_id = 0;
}
}
$form = $editing !== null ? $editing : [
'id' => 0, 'slug' => '', 'name' => '', 'tagline' => '', 'description' => '',
'since' => null, 'since_label' => 'FWS', 'latest_name' => '', 'latest_date' => null,
'links' => '[]', 'screens' => '[]', 'changelog' => '[]',
];
$fLinks = lines_from_links((array) (json_decode((string) $form['links'], true) ?: []));
$fScreens = lines_from_screens((array) (json_decode((string) $form['screens'], true) ?: []));
$fChangelog = lines_from_changelog((array) (json_decode((string) $form['changelog'], true) ?: []));
?>
<div class="card">
<h3><?= $editing !== null ? '✏️ Modifier « ' . h($editing['name']) . ' »' : '➕ Nouveau paquet' ?></h3>
<?php if ($editing !== null): ?><p style="font-size:.85rem;color:#94a3b8"><a href="index.php?view=packages">← Annuler la modification</a></p><?php endif; ?>
<p style="font-size:.85rem;color:#94a3b8">Les champs « une ligne par entrée » utilisent le format <code>Label | URL</code> (liens),
<code>Version | Date | Notes</code> (historique) et <code>src | alt | légende</code> (captures).</p>
<form method="post" style="display:grid;gap:2px;max-width:680px">
<input type="hidden" name="action" value="pkg_save">
<input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
<input type="hidden" name="pkg_id" value="<?= (int) $form['id'] ?>">
<div class="grid2">
<div>
<label for="pkg_name">Nom *</label>
<input type="text" id="pkg_name" name="name" required value="<?= h($form['name']) ?>">
</div>
<div>
<label for="pkg_slug">Slug / id (vide = auto)</label>
<input type="text" id="pkg_slug" name="slug" value="<?= h($form['slug']) ?>" placeholder="ex. fws-pacmanage">
</div>
</div>
<label for="pkg_tagline">Tagline</label>
<input type="text" id="pkg_tagline" name="tagline" value="<?= h($form['tagline']) ?>">
<label for="pkg_desc">Description</label>
<textarea id="pkg_desc" name="description" rows="3"><?= h($form['description']) ?></textarea>
<div class="grid2">
<div>
<label for="pkg_since">Disponible depuis (date)</label>
<input type="date" id="pkg_since" name="since" value="<?= h((string) ($form['since'] ?? '')) ?>">
</div>
<div>
<label for="pkg_since_label">Badge « depuis »</label>
<input type="text" id="pkg_since_label" name="since_label" value="<?= h($form['since_label']) ?>" placeholder="V1.0.0 / En développement">
</div>
<div>
<label for="pkg_latest_name">Dernière release (nom)</label>
<input type="text" id="pkg_latest_name" name="latest_name" value="<?= h($form['latest_name']) ?>" placeholder="V1.2.1">
</div>
<div>
<label for="pkg_latest_date">Date de la release</label>
<input type="date" id="pkg_latest_date" name="latest_date" value="<?= h((string) ($form['latest_date'] ?? '')) ?>">
</div>
</div>
<label for="pkg_links">Liens utiles — une ligne par lien : <code>Label | URL</code></label>
<textarea id="pkg_links" name="links" rows="3" placeholder="Gitea | https://gitea.nocode-var.tech/FWS/FWS-PacManage"><?= h($fLinks) ?></textarea>
<label for="pkg_changelog">Historique — une ligne par version : <code>Version | Date | Notes</code></label>
<textarea id="pkg_changelog" name="changelog" rows="5" placeholder="V1.2.1 | 2026-08-29 | Correction de bugs"><?= h($fChangelog) ?></textarea>
<label for="pkg_screens">Captures d'écran — une ligne : <code>src | alt | légende</code></label>
<textarea id="pkg_screens" name="screens" rows="2" placeholder="/p/assets/img/… | Alt | Légende"><?= h($fScreens) ?></textarea>
<button class="btn primary" type="submit" style="justify-self:start;margin-top:4px">💾 Enregistrer</button>
</form>
</div>
<div class="card">
<h3>📦 Paquets (<?= count($pkgRows) ?>)</h3>
<?php if (!$pkgRows): ?>
<p class="empty">Aucun paquet. Créez le premier avec le formulaire ci-dessus.</p>
<?php else: ?>
<table class="list">
<tr><th>#</th><th>Nom</th><th>Dernière release</th><th></th></tr>
<?php foreach ($pkgRows as $pr): ?>
<tr>
<td><?= (int) $pr['id'] ?></td>
<td>
<strong><?= h($pr['name']) ?></strong>
<?php if ($pr['slug'] !== ''): ?><br><span style="font-size:.75rem;color:#64748b"><?= h($pr['slug']) ?></span><?php endif; ?>
<?php if ($pr['tagline'] !== ''): ?><br><span style="font-size:.8rem;color:#94a3b8"><?= h($pr['tagline']) ?></span><?php endif; ?>
</td>
<td><?= h($pr['latest_name'] !== '' ? $pr['latest_name'] . ($pr['latest_date'] !== null ? ' — ' . $pr['latest_date'] : '') : '—') ?></td>
<td style="text-align:right;white-space:nowrap">
<a class="btn small" href="index.php?view=packages&edit=<?= (int) $pr['id'] ?>">✏️ Modifier</a>
<form class="inline" method="post" onsubmit="return confirm('Synchroniser « <?= h($pr['name']) ?> » depuis Gitea ? (latest + historique)')">
<input type="hidden" name="action" value="pkg_sync_gitea">
<input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
<input type="hidden" name="pkg_id" value="<?= (int) $pr['id'] ?>">
<button class="btn small" type="submit" title="Rafraîchit la dernière release et l'historique depuis Gitea">🔄 Gitea</button>
</form>
<form class="inline" method="post" onsubmit="return confirm('Supprimer le paquet « <?= h($pr['name']) ?> » ?')">
<input type="hidden" name="action" value="pkg_delete">
<input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
<input type="hidden" name="pkg_id" value="<?= (int) $pr['id'] ?>">
<button class="btn small danger" type="submit">🗑 Supprimer</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
</div>
<?php else: /* ─────────── LISTE ─────────── */
$filter = $_GET['status'] ?? 'tous';
+115
View File
@@ -0,0 +1,115 @@
#!/bin/bash
# =============================================================================
# FWS — Pipeline « Build ISO » déclenché depuis le panneau admin
# (admin/bugs/build.php → process détaché, logs dans le terminal).
#
# Exécuté DANS le conteneur web (fws-files), qui pilote le moteur Docker
# Desktop via /var/run/docker.sock. Toutes les étapes se déroulent dans un
# conteneur archlinux jetable (--privileged, exigé par mkarchiso), le dépôt
# Windows D:\FWS-ISO étant monté sur /fws — exactement le repli Docker que
# font build.sh / setup-aur.sh quand on les lance depuis Git Bash sans WSL.
#
# Étapes :
# 1. passage sur la branche « main » (abandon propre si des modifications
# locales non commitées empêchent le checkout — rien n'est jamais perdu)
# 2. git pull origin main
# 3. bash build.sh
# 4. si build.sh échoue → bash setup-aur.sh, puis relance de build.sh
# =============================================================================
set -u
# ── Token Gitea (optionnel) : déposé par build.php dans
# api/bugs/data/build/git-auth.env (jamais commité, jamais affiché).
# Transmis au conteneur en variable d'environnement → git l'utilise pour
# le pull sans qu'aucune donnée d'auth n'apparaisse dans les logs.
AUTH_ENV="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/../../api/bugs/data/build/git-auth.env"
GIT_AUTH=()
if [ -f "$AUTH_ENV" ]; then
. "$AUTH_ENV"
fi
if [ -n "${FWS_GIT_TOKEN:-}" ]; then
AUTH64="$(printf '%s:%s' "${FWS_GIT_USER:-fws}" "$FWS_GIT_TOKEN" | base64 -w0 2>/dev/null || printf '%s:%s' "${FWS_GIT_USER:-fws}" "$FWS_GIT_TOKEN" | base64)"
GIT_AUTH=(
-e GIT_CONFIG_COUNT=1
-e GIT_CONFIG_KEY_0=http.extraheader
-e "GIT_CONFIG_VALUE_0=AUTHORIZATION: basic ${AUTH64}"
)
fi
IMG="docker.io/library/archlinux:latest"
NAME="fws-iso-build"
REPO_WIN='D:\FWS-ISO' # chemin Windows résolu par le moteur Docker Desktop
now() { date '+%H:%M:%S'; }
echo "[$(now)] ════════════ FWS — Build ISO ════════════"
echo "[$(now)] Pipeline lancé depuis le panneau admin (conteneur web)."
rc=0
echo "[$(now)] docker pull ${IMG}…"
if ! docker pull "$IMG"; then
echo "[$(now)] ÉCHEC : pull de l'image archlinux impossible (Docker Desktop arrêté ou réseau coupé ?)."
rc=70
else
# Nettoie un éventuel build précédent resté vivant (arrêt brutal).
docker rm -f "$NAME" >/dev/null 2>&1
echo "[$(now)] Conteneur Arch : checkout main → pull → build.sh (repli setup-aur.sh)."
docker run --rm --privileged --name "$NAME" \
-e FWS_IN_CONTAINER=1 \
"${GIT_AUTH[@]}" \
-v fws-pacman-cache:/var/cache/pacman/pkg \
-v "${REPO_WIN}:/fws" \
-w /fws \
"$IMG" \
bash -lc '
set -u
cd /fws || { echo "==> /fws introuvable : le montage D:\FWS-ISO est-il actif ?"; exit 81; }
echo "==> Installation de git dans le conteneur (image fraîche sans git)…"
pacman -Sy --noconfirm git >/dev/null 2>&1 \
|| { echo "==> ÉCHEC : pacman -Sy git (réseau du conteneur ?)."; exit 80; }
echo "==> Branche actuelle : $(git branch --show-current)"
echo "==> Passage sur main…"
git checkout main 2>&1 || {
echo
echo "!! Impossible de passer sur main : des modifications locales non commitées"
echo "!! dans D:\FWS-ISO empêchent le checkout (voir « git status »)."
echo "!! Committe ou stash ces modifications, puis relance le build."
exit 90
}
echo "==> git pull (origin main)…"
GIT_TERMINAL_PROMPT=0 git pull --ff-only origin main || {
echo "!! git pull a échoué (réseau, droits, ou conflit ?)."
exit 91
}
echo
echo "==> bash build.sh"
if bash build.sh; then
echo "==> ✅ build.sh terminé sans erreur."
exit 0
fi
echo
echo "!! build.sh a échoué → lancement de setup-aur.sh, puis nouvel essai de build.sh"
if ! bash setup-aur.sh; then
echo "!! setup-aur.sh a échoué."
exit 92
fi
echo "==> bash build.sh (2e tentative)…"
if bash build.sh; then
echo "==> ✅ build.sh (2e tentative) terminé sans erreur."
exit 0
fi
echo "!! Nouvel échec de build.sh."
exit 93
'
rc=$?
docker rm -f "$NAME" >/dev/null 2>&1 || true
fi
echo "[$(now)] ════════════ Fin du pipeline (code ${rc}) ════════════"
exit "$rc"