From 1775adceaa55dcb2d1c56d844a705f938006e28f Mon Sep 17 00:00:00 2001 From: BlackAngelTVdev Date: Mon, 14 Sep 2026 13:19:37 +0200 Subject: [PATCH] =?UTF-8?q?Feat(site):=20rendu=20serveur=20PHP=20=E2=80=94?= =?UTF-8?q?=20paquets=20en=20SQLite,=20releases=20Gitea,=20build=20ISO?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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. --- .gitignore | 3 + .htaccess | 5 + Doc/fonctionnement-onepage.md | 220 +++-------- admin/bugs/build.php | 558 +++++++++++++++++++++++++++ admin/bugs/index.php | 321 +++++++++++++++- admin/bugs/run-build.sh | 115 ++++++ api/bugs/config.local.php.example | 19 +- api/bugs/data/.gitignore | 4 + api/bugs/db.php | 207 +++++++++- api/packages.php | 31 ++ inc/site.php | 610 ++++++++++++++++++++++++++++++ index.html | 110 ------ index.php | 8 + p/404.php | 21 + p/assets/js/creators-loader.js | 108 ------ p/assets/js/downloads.js | 461 ---------------------- p/assets/js/note-toggle.js | 23 ++ p/assets/js/packages.js | 487 ------------------------ p/assets/main-nav/app.js | 222 ----------- p/assets/main-nav/nav.js | 35 ++ p/assets/styles/paquets.css | 32 -- p/contact/index.html | 33 -- p/contact/index.php | 36 ++ p/dl/index.html | 43 --- p/dl/index.php | 112 ++++++ p/equipe/index.html | 27 -- p/equipe/index.php | 69 ++++ p/index/index.html | 116 ------ p/index/index.php | 117 ++++++ p/paquets/_detail/index.html | 18 - p/paquets/detail.php | 108 ++++++ p/paquets/index.html | 24 -- p/paquets/index.php | 117 ++++++ page.php | 241 ++++++++++++ 34 files changed, 2799 insertions(+), 1862 deletions(-) create mode 100644 admin/bugs/build.php create mode 100644 admin/bugs/run-build.sh create mode 100644 api/packages.php create mode 100644 inc/site.php delete mode 100644 index.html create mode 100644 index.php create mode 100644 p/404.php delete mode 100644 p/assets/js/creators-loader.js delete mode 100644 p/assets/js/downloads.js create mode 100644 p/assets/js/note-toggle.js delete mode 100644 p/assets/js/packages.js delete mode 100644 p/assets/main-nav/app.js create mode 100644 p/assets/main-nav/nav.js delete mode 100644 p/contact/index.html create mode 100644 p/contact/index.php delete mode 100644 p/dl/index.html create mode 100644 p/dl/index.php delete mode 100644 p/equipe/index.html create mode 100644 p/equipe/index.php delete mode 100644 p/index/index.html create mode 100644 p/index/index.php delete mode 100644 p/paquets/_detail/index.html create mode 100644 p/paquets/detail.php delete mode 100644 p/paquets/index.html create mode 100644 p/paquets/index.php create mode 100644 page.php diff --git a/.gitignore b/.gitignore index 9598771..998b410 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,6 @@ api/bugs/data/*.db-shm *.sqlite *.sqlite-wal *.sqlite-shm + +# Cache HTTP local du site (releases Gitea/GitHub, généré par inc/site.php) +cache/ diff --git a/.htaccess b/.htaccess index 1c1b46c..71fbcad 100644 --- a/.htaccess +++ b/.htaccess @@ -1,5 +1,10 @@ # ── FWS Linux — .htaccess (performance + sécurité) ────────────────────────── +# Le site est rendu côté serveur : page.php est le point d'entrée unique. +# (Les sous-dossiers avec leur propre index.php — admin/bugs, api — restent +# prioritaires via l'ordre de DirectoryIndex.) +DirectoryIndex index.php page.php + # Pas de listing de répertoires (ex : /p/, /api/, /admin/) Options -Indexes diff --git a/Doc/fonctionnement-onepage.md b/Doc/fonctionnement-onepage.md index 6af2ca3..c706842 100644 --- a/Doc/fonctionnement-onepage.md +++ b/Doc/fonctionnement-onepage.md @@ -1,183 +1,57 @@ -# Fonctionnement du JavaScript +# Fonctionnement du site (PHP) -Ce projet fonctionne comme un site statique avec un seul point d'entrée HTML. Le JavaScript sert à lire l'URL, charger le bon fichier dans `p/`, injecter son contenu dans le `main`, et reprendre aussi les styles définis dans le `` de la page chargée. +Le site est **entièrement rendu côté serveur (PHP)**. Il n'y a plus de routeur +JavaScript : chaque URL sert une page HTML complète. Les seuls scripts restants +sont des améliorations progressives (carrousel, menu déroulant, « Voir plus »). -## Principe général +## Architecture -1. `index.html` garde le header, le footer et le conteneur principal. -2. Chaque page vit dans un dossier sous `p/`. -3. Le script lit la route demandée dans l'URL. -4. Le script charge `p//index.html` avec `fetch`. -5. Le contenu de la page est injecté dans le `main`. -6. Les styles déclarés dans le `head` de cette page sont copiés dans le `head` du document courant. +1. **`page.php`** (racine) est le point d'entrée unique. Il lit la route dans + l'URL (`?p/dl/`, `?p=dl`, `?p/paquets/1/`…), inclut le corps de page + correspondant, puis assemble la coquille (header/nav/footer). +2. **`inc/site.php`** contient les helpers : connexion SQLite partagée, + paquets (base + fusion des releases Gitea), fetch HTTP avec cache fichier + (`cache/`, gitignoré), rendu Markdown (portage PHP de l'ancien + `downloads.js`), dates en français, troncature HTML. +3. **`p//index.php`** (et `p/paquets/detail.php` pour `/?p/paquets/N/`) + contiennent le corps de chaque page. Ils définissent `$title`, + `$description`, `$extraCss[]` et `$extraJs[]` avant l'affichage. +4. `index.php` à la racine délègue à `page.php` (DirectoryIndex Apache). + +## Données + +- **Paquets** : table SQLite `packages` (base `api/bugs/data/fws_bugs.sqlite`, + partagée avec le panneau d'admin). Éditables dans `/admin/bugs` (onglet + 📦 Paquets) + bouton 🔄 Gitea qui synchronise `latest` et l'historique depuis + l'API Gitea du dépôt lié. Repli automatique sur `p/paquets/packages.json` + si la base est vide. API publique conservée : `/api/packages.php`. +- **Téléchargements** : releases ISO rendues serveur — Gitea `FWS/ISO` s'il + existe, sinon GitHub (cache 10 min dans `cache/`). +- **Équipe** : rendu serveur depuis `p/equipe/creators.json`. ## Fichiers impliqués -- [index.html](../index.html) contient le chrome global du site. -- [.htaccess](../.htaccess) contient la configuration Apache (`Options +Indexes`). -- [p/assets/main-nav/app.js](../p/assets/main-nav/app.js) contient le routeur JavaScript. -- [p/index/index.html](../p/index/index.html) contient la page principale. -- [p/dl/index.html](../p/dl/index.html) contient la page DL. -- [p/contact/index.html](../p/contact/index.html) contient la page contact. +- [page.php](../page.php) — front controller + coquille HTML. +- [inc/site.php](../inc/site.php) — helpers (DB, Gitea/GitHub, Markdown…). +- [index.php](../index.php) — shim vers `page.php`. +- `p/index|dl|paquets|equipe|contact/index.php`, `p/paquets/detail.php`, + `p/404.php` — corps de pages. +- [p/assets/main-nav/nav.js](../p/assets/main-nav/nav.js) — ouverture du menu + déroulant Paquets. +- [p/assets/js/note-toggle.js](../p/assets/js/note-toggle.js) — « Voir plus / + Voir moins » de la note de release. +- [p/assets/js/hero-carousel.js](../p/assets/js/hero-carousel.js) — carrousel + de l'accueil. -## Comment le script lit l'URL +## Supprimés (devenus inutiles avec le rendu serveur) -La fonction `routeFromLocation()` lit la route courante depuis plusieurs formes possibles d'URL. +- `index.html` (racine), tous les `p/**/index.html` +- `p/assets/main-nav/app.js` (routeur SPA) +- `p/assets/js/packages.js`, `downloads.js`, `creators-loader.js` -Exemples reconnus: +## Panneau admin & API (inchangés dans leur principe) -- `/?p/index/` -- `/?p/dl/` -- `/?p=contact` -- `/p/about/` - -La fonction `normalizeRoute(value)` nettoie ensuite la valeur pour obtenir une route simple comme `index`, `dl` ou `contact`. - -## Chargement du contenu - -La fonction `loadRoute(route)` fait le chargement réel. - -### Route principale - -Pour la route `index`, le script charge: - -```text -p/index/index.html -``` - -### Autres routes - -Pour une route comme `dl`, le script charge: - -```text -p/dl/index.html -``` - -Le fichier chargé doit contenir un bloc avec `data-page-content`: - -```html -
- ... -
-``` - -Le script n'injecte pas tout le document dans la page courante. Il prend seulement le contenu à l'intérieur de cet élément. - -## Injection des styles du head - -Le routeur copie maintenant aussi les balises suivantes depuis le `head` de la page chargée: - -- `link rel="stylesheet"` -- `style` - -Ces balises sont clonées dans le `head` du document principal avec un attribut de suivi `data-page-style`. - -Avant d'ajouter les nouveaux styles, le script supprime les styles injectés par la route précédente pour éviter les doublons et les conflits. - -Exemple dans une page custom: - -```html - - - - -``` - -Si cette page est chargée, le CSS est repris automatiquement. - -## Mise à jour de l'URL - -Après le chargement, le script met à jour l'URL avec l'API History. - -Exemples: - -- `index` devient `/?p/index/` -- `dl` devient `/?p/dl/` - -Le navigateur garde donc une URL partageable, sans recharger complètement la page. - -## Navigation au clic - -Le script écoute les clics sur les liens qui possèdent `data-route`. - -Quand tu cliques sur un lien: - -1. il bloque la navigation normale avec `event.preventDefault()`; -2. il lit `data-route`; -3. il appelle `render(route)`; -4. il charge la page correspondante dans le `main`; -5. il applique aussi ses styles de page. - -## Retour arrière du navigateur - -Le script écoute l'événement `popstate`. - -Cela permet de revenir en arrière ou d'avancer dans l'historique tout en rechargeant la bonne route et les bons styles. - -## Ajouter une nouvelle page - -Pour ajouter une page, crée un nouveau dossier sous `p/`. - -Exemple pour une page contact: - -```text -p/contact/index.html -``` - -Puis ajoute éventuellement un fichier CSS dans cette page via son `head`. - -Enfin, ajoute un lien dans `index.html`: - -```html -Contact -``` - -Le JavaScript n'a pas besoin d'être modifié tant que la structure reste la même. - -## Ce que ce système n'utilise pas - -Ce projet n'utilise pas: - -- Node.js, -- un bundler, -- un framework front, -- des fichiers `.html` séparés dans la racine pour chaque page. - -Tout repose sur un site statique et un routeur JavaScript léger. - -## Point important - -Le chargement via `fetch` fonctionne mieux quand le site est servi par un serveur statique, comme Five Server. - -Si tu ouvres le fichier en `file://`, le navigateur peut bloquer l'accès aux fichiers internes pour des raisons de sécurité. - -## Fichier .htaccess - -Le fichier [.htaccess](../.htaccess) à la racine contient la directive Apache suivante : - -```apache -Options +Indexes -``` - -Cela active l'**indexation des répertoires** : si un dossier ne contient pas de fichier `index.html`, Apache affiche automatiquement la liste de son contenu. - -### Points à noter - -- Cette option ne fonctionne que si le serveur Apache a `AllowOverride Options` (ou `AllowOverride All`) activé dans sa configuration. -- En production, il peut être préférable de désactiver les indexes pour des raisons de sécurité. Remplacez par `Options -Indexes` si besoin. -- Le fichier `.htaccess` est placé à la racine du projet pour couvrir tous les sous-dossiers. - -## Structure de la documentation - -La documentation du projet est dans le dossier `Doc/` et rédigée en Markdown : - -``` -Doc/ -└── fonctionnement-onepage.md # Ce fichier -``` - -Chaque fichier `.md` documente un aspect du projet. Le README à la racine (`README.md`) donne une vue d'ensemble rapide. \ No newline at end of file +- `admin/bugs/index.php` — signalements, invitations/comptes, paquets. +- `admin/bugs/build.php` — onglet « Build ISO » (réservé au compte admin). +- `api/bugs.php` — réception des signalements (`curl` ou navigateur). +- `api/packages.php` — paquets au format JSON (consommé par des tiers). diff --git a/admin/bugs/build.php b/admin/bugs/build.php new file mode 100644 index 0000000..a91d020 --- /dev/null +++ b/admin/bugs/build.php @@ -0,0 +1,558 @@ + 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) . ' > ' . 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'); +?> + + + + + +Build ISO — FWS Linux + + + +
+ +
+
+

🔨 Build ISO

+
Connecté : · dépôt : D:\FWS-ISO (branche main)
+
+
+ + + +
+
+ + + + +
+

Accès restreint

+

Votre compte () n'est pas autorisé à lancer des builds. + Seul le compte admin le peut (voir fws_bugs_can_build() dans api/bugs/db.php).

+ ← Retour aux signalements +
+ + + +
+

🔑 Accès Gitea (pour le git pull)

+

+ Le dépôt D:\FWS-ISO est privé et le build tourne dans un conteneur sans tes identifiants + Windows : crée un token dans Gitea (Settings → Applications → Generate New Token, lecture du dépôt) + puis enregistre-le ici. Il n'est stocké que sur ce serveur — jamais commité, jamais affiché dans les logs. +

+ … +
+
+ + +
+
+ + +
+ + +
+
+ +
+

🖥️ Terminal du build

+
+ État : inconnu… + · Git Bash lancerait ici : git checkout main && git pull && bash build.sh +
+ +
Chargement du terminal…
+ +
+ + + + +
+ +

+ Le build se déroule dans un conteneur archlinux jetable (via Docker Desktop, comme + build.sh à la main) : passage sur main → git pull → bash build.sh ; + en cas d'échec de build, bash setup-aur.sh est lancé puis build.sh est relancé. + Si le checkout de main est bloqué par des modifications locales non commitées dans + D:\FWS-ISO, le build s'arrête proprement sans rien toucher. L'ISO sort dans + D:\FWS-ISO\out\. Peut prendre 30 min et plus — laissez l'onglet ouvert, les logs défilent en direct. +

+
+ + + +
+ + + diff --git a/admin/bugs/index.php b/admin/bugs/index.php index f011276..360ff5b 100644 --- a/admin/bugs/index.php +++ b/admin/bugs/index.php @@ -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
@@ -548,6 +752,119 @@ table.list th { color: #94a3b8; font-size: .72rem; text-transform: uppercase; le +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) ?: [])); +?> + +
+

+

← Annuler la modification

+

Les champs « une ligne par entrée » utilisent le format Label | URL (liens), + Version | Date | Notes (historique) et src | alt | légende (captures).

+
+ + + +
+
+ + +
+
+ + +
+
+ + + + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + + + + + + +
+
+ +
+

📦 Paquets ()

+ +

Aucun paquet. Créez le premier avec le formulaire ci-dessus.

+ + + + + + + + + + + +
#NomDernière release
+ +
+
+
+ ✏️ Modifier +
+ + + + +
+
+ + + + +
+
+ +
+ /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" diff --git a/api/bugs/config.local.php.example b/api/bugs/config.local.php.example index 0fed076..29499fe 100644 --- a/api/bugs/config.local.php.example +++ b/api/bugs/config.local.php.example @@ -1,6 +1,6 @@ 'https://discord.com/api/webhooks/REMPLACE_PAR_ID/REMPLACE_PAR_TOKEN', - 'bot_token' => '', - 'tags' => [ + 'webhook_url' => 'https://discord.com/api/webhooks/REMPLACE_PAR_ID/REMPLACE_PAR_TOKEN', + 'bot_token' => '', + 'gitea_username' => '', // optionnel : nom du compte Gitea (défaut « fws ») + 'gitea_token' => '', // token Gitea (lecture dépôt) pour le build ISO + 'tags' => [ 'nouveau' => '', 'en_cours' => '', 'resolu' => '', 'ignore' => '', ], -]; \ No newline at end of file +]; diff --git a/api/bugs/data/.gitignore b/api/bugs/data/.gitignore index 317b8f2..9188804 100644 --- a/api/bugs/data/.gitignore +++ b/api/bugs/data/.gitignore @@ -2,3 +2,7 @@ *.sqlite *.sqlite-wal *.sqlite-shm +fws_bugs.sqlite + +# Logs / états de l'onglet « Build ISO » (admin/bugs/build.php) +/build/ diff --git a/api/bugs/db.php b/api/bugs/db.php index 867f594..0a519d3 100644 --- a/api/bugs/db.php +++ b/api/bugs/db.php @@ -6,6 +6,36 @@ declare(strict_types=1); +/* ───────────── 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; @@ -98,6 +128,25 @@ function fws_bugs_schema(PDO $pdo): void )' ); + /* 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); } @@ -108,7 +157,7 @@ function fws_bugs_schema(PDO $pdo): void */ function fws_bugs_next_id(PDO $pdo, string $table): int { - if (!in_array($table, ['bug_reports', 'admin_users', 'invite_codes'], true)) { + if (!in_array($table, ['bug_reports', 'admin_users', 'invite_codes', 'packages'], true)) { throw new InvalidArgumentException('Table inconnue : ' . $table); } $used = []; @@ -200,3 +249,159 @@ function fws_bugs_client_ip(): string } 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), + ':screens' => (string) json_encode(fws_utf8_arr((array) ($d['screens'] ?? [])), 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; +} diff --git a/api/packages.php b/api/packages.php new file mode 100644 index 0000000..d727384 --- /dev/null +++ b/api/packages.php @@ -0,0 +1,31 @@ +getMessage()); + http_response_code(500); + header('Content-Type: application/json; charset=utf-8'); + echo json_encode(['ok' => false, 'error' => 'Erreur base de données.']); + exit; +} + +header('Content-Type: application/json; charset=utf-8'); +header('Access-Control-Allow-Origin: *'); +echo json_encode($packages, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); \ No newline at end of file diff --git a/inc/site.php b/inc/site.php new file mode 100644 index 0000000..44eb16c --- /dev/null +++ b/inc/site.php @@ -0,0 +1,610 @@ + 'janvier', 'février', 'mars', 'avril', 'mai', 'juin', + 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre', + ]; + try { + $d = new DateTimeImmutable($iso); + return trim($d->format('j')) . ' ' . $mois[(int) $d->format('n')] . ' ' . $d->format('Y'); + } catch (Throwable $e) { + return $iso; + } +} + +/* ───────────────────────── paquets (base SQLite) ───────────────────────── */ + +/** + * Connexion à la base du site (celle des bugs, partagée). Renvoie null si la + * base n'est pas disponible : le site doit rester fonctionnel sans DB. + */ +function fws_site_db(): ?PDO +{ + static $pdo = null; + static $failed = false; + if ($pdo instanceof PDO || $failed) { + return $failed ? null : $pdo; + } + try { + require_once __DIR__ . '/../api/bugs/db.php'; + $pdo = fws_bugs_db(); + } catch (Throwable $e) { + error_log('[fws-site] base indisponible : ' . $e->getMessage()); + $failed = true; + return null; + } + return $pdo; +} + +/** + * Paquets du site : base SQLite (source de vérité, éditable dans /admin/bugs) + * avec repli sur p/paquets/packages.json si la base est vide ou absente. + * Chaque entrée est nettoyée (UTF-8 valide) pour ne jamais casser json_encode + * ni le rendu HTML. + */ +function fws_site_packages(): array +{ + static $cache = null; + if ($cache !== null) { + return $cache; + } + + $out = []; + + $pdo = fws_site_db(); + if ($pdo !== null) { + try { + $has = $pdo->query( + "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='packages'" + )->fetchColumn(); + if ((int) $has > 0) { + foreach ($pdo->query('SELECT * FROM packages ORDER BY id ASC') as $r) { + $out[] = fws_site_package_row($r); + } + } + } catch (Throwable $e) { + error_log('[fws-site] lecture paquets : ' . $e->getMessage()); + } + } + + /* Repli : l'ancien fichier JSON (avant la DB, ou base vide). */ + if ($out === []) { + /* dbId = 0 : les URLs /?p/paquets/N/ se rabattent sur la position. */ + $file = FWS_SITE_ROOT . '/p/paquets/packages.json'; + if (is_file($file)) { + $data = json_decode((string) file_get_contents($file), true); + if (is_array($data)) { + foreach ($data as $p) { + if (is_array($p)) { + $out[] = fws_site_package_shape($p); + } + } + } + } + } + + /* Release + historique tirés de Gitea (URL des liens du paquet). */ + foreach ($out as $i => $pkg) { + $out[$i] = fws_site_package_with_releases($pkg); + } + + $cache = $out; + return $cache; +} + +/** Normalise un paquet quelconque (JSON ou DB) vers la forme du site. + * « dbId » = identifiant en base (0 si venant du fichier JSON de repli) : + * c'est lui qui pilote les URLs /?p/paquets/N/. */ +function fws_site_package_shape(array $p): array +{ + return fws_utf8_arr([ + 'id' => (string) ($p['id'] ?? ''), + 'name' => (string) ($p['name'] ?? ''), + 'tagline' => (string) ($p['tagline'] ?? ''), + 'description' => (string) ($p['description'] ?? ''), + 'since' => (string) ($p['since'] ?? '') !== '' ? (string) $p['since'] : null, + 'sinceLabel' => (string) ($p['sinceLabel'] ?? 'FWS'), + 'latest' => isset($p['latest']) && is_array($p['latest']) + ? [ + 'name' => (string) ($p['latest']['name'] ?? ''), + 'date' => (string) ($p['latest']['date'] ?? '') !== '' ? (string) $p['latest']['date'] : null, + ] + : null, + 'links' => is_array($p['links'] ?? null) ? array_values($p['links']) : [], + 'screens' => is_array($p['screens'] ?? null) ? array_values($p['screens']) : [], + 'changelog' => is_array($p['changelog'] ?? null) ? array_values($p['changelog']) : [], + 'dbId' => (int) ($p['dbId'] ?? 0), + ]); +} + +/** Ligne brute DB → forme du site (même format que l'ancien packages.json). */ +function fws_site_package_row(array $r): array +{ + return fws_site_package_shape([ + 'dbId' => (int) ($r['id'] ?? 0), + 'id' => $r['slug'] ?? '', + 'name' => $r['name'] ?? '', + 'tagline' => $r['tagline'] ?? '', + 'description' => $r['description'] ?? '', + 'since' => $r['since'] ?? null, + 'sinceLabel' => $r['since_label'] ?? 'FWS', + 'latest' => [ + 'name' => $r['latest_name'] ?? '', + 'date' => $r['latest_date'] ?? '', + ], + 'links' => json_decode((string) ($r['links'] ?? '[]'), true) ?: [], + 'screens' => json_decode((string) ($r['screens'] ?? '[]'), true) ?: [], + 'changelog' => json_decode((string) ($r['changelog'] ?? '[]'), true) ?: [], + ]); +} + +/** + * Enrichit un paquet avec les releases Gitea (à partir de l'URL « Releases » + * ou « Gitea » de ses liens) : latest + changelog réels, en cache fichier. + */ +function fws_site_package_with_releases(array $pkg): array +{ + $repo = fws_site_gitea_repo_from_links($pkg['links'] ?? []); + if ($repo === null) { + return $pkg; + } + + $releases = fws_site_gitea_releases($repo['owner'], $repo['name']); + if ($releases === []) { + /* Pas de release Gitea : on garde latest/changelog de la DB. */ + return $pkg; + } + + $first = $releases[0]; + $pkg['latest'] = [ + 'name' => (string) ($first['tag_name'] ?? ''), + 'date' => isset($first['published_at']) ? substr((string) $first['published_at'], 0, 10) : null, + ]; + + $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 !== '' ? $notes : '', + ]; + } + $pkg['changelog'] = $changelog; + + return $pkg; +} + +/** Trouve owner/name du dépôt Gitea dans les liens d'un paquet (null sinon). */ +function fws_site_gitea_repo_from_links(array $links): ?array +{ + foreach ($links as $link) { + $url = (string) ($link['url'] ?? ''); + if (preg_match('~^https?://gitea\.nocode-var\.tech/([^/]+)/([^/]+)/?$~i', $url, $m)) { + return ['owner' => $m[1], 'name' => $m[2]]; + } + } + return null; +} + +/* ───────────────────────── HTTP + cache fichier ───────────────────────── */ + +/** GET JSON avec cache fichier (cache/ gitignoré) ; [] en cas d'échec. */ +function fws_site_fetch_json(string $url, array $headers = []): array +{ + $key = 'http_' . sha1($url); + $file = FWS_SITE_CACHE_DIR . '/' . $key . '.json'; + + if (is_file($file) && (time() - (int) filemtime($file)) < FWS_SITE_CACHE_TTL) { + $data = json_decode((string) file_get_contents($file), true); + if (is_array($data)) { + return $data; + } + } + + $cacheOk = is_dir(FWS_SITE_CACHE_DIR) || @mkdir(FWS_SITE_CACHE_DIR, 0777, true); + if ($cacheOk && !is_writable(FWS_SITE_CACHE_DIR)) { + @chmod(FWS_SITE_CACHE_DIR, 0777); + $cacheOk = is_writable(FWS_SITE_CACHE_DIR); + } + + $data = []; + if (function_exists('curl_init')) { + $ch = curl_init($url); + $allHeaders = ['Accept: application/json', 'User-Agent: FWS-Linux-Website']; + foreach ($headers as $h) { + $allHeaders[] = $h; + } + curl_setopt_array($ch, [ + CURLOPT_RETURNTRANSFER => true, + CURLOPT_TIMEOUT => 8, + CURLOPT_CONNECTTIMEOUT => 4, + CURLOPT_HTTPHEADER => $allHeaders, + CURLOPT_FOLLOWLOCATION => true, + ]); + $body = curl_exec($ch); + $code = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); + curl_close($ch); + if (is_string($body) && $code >= 200 && $code < 300) { + $decoded = json_decode($body, true); + if (is_array($decoded)) { + $data = $decoded; + } + } + } + + if (!$cacheOk) { + /* Répertoire de cache non accessible (droits) : on répond quand même, + simplement sans persistance entre les requêtes. */ + return $data; + } + + if ($data !== []) { + @file_put_contents($file, json_encode($data, JSON_UNESCAPED_UNICODE), LOCK_EX); + } elseif (is_file($file)) { + /* API injoignable : on sert le dernier cache connu (périmé mais mieux que rien). */ + $data = json_decode((string) file_get_contents($file), true) ?: []; + } + + return $data; +} + +/** Releases d'un dépôt Gitea (les plus récentes d'abord). */ +function fws_site_gitea_releases(string $owner, string $name): array +{ + static $memo = []; + $key = $owner . '/' . $name; + if (isset($memo[$key])) { + return $memo[$key]; + } + $url = 'https://gitea.nocode-var.tech/api/v1/repos/' + . rawurlencode($owner) . '/' . rawurlencode($name) . '/releases?limit=10'; + $data = fws_site_fetch_json($url); + $out = []; + /* L'API renvoie un tableau, ou {message:...} si le dépôt n'existe pas. */ + if (isset($data[0]) && is_array($data[0]) && isset($data[0]['tag_name'])) { + foreach ($data as $rel) { + if (is_array($rel) && isset($rel['tag_name'])) { + $out[] = $rel; + } + } + } + $memo[$key] = $out; + return $out; +} + +/* ───────────────────────── releases ISO (page Téléchargements) ─────────── */ + +/** + * Releases de l'ISO pour la page Téléchargements : Gitea FWS/ISO s'il existe, + * sinon GitHub (comme avant). Renvoie ['mode' => 'gitea'|'github'|'none', 'items' => [...]]. + */ +function fws_site_iso_releases(): array +{ + $gitea = fws_site_gitea_releases('FWS', 'ISO'); + if ($gitea !== []) { + return ['mode' => 'gitea', 'items' => $gitea]; + } + + $gh = fws_site_fetch_json( + 'https://api.github.com/repos/You-re-like-Windows-a-bitch/ISO/releases?per_page=6', + ['Accept: application/vnd.github+json'] + ); + if (isset($gh[0]) && is_array($gh[0]) && isset($gh[0]['tag_name'])) { + return ['mode' => 'github', 'items' => $gh]; + } + + $tags = fws_site_fetch_json( + 'https://api.github.com/repos/You-re-like-Windows-a-bitch/ISO/tags?per_page=6', + ['Accept: application/vnd.github+json'] + ); + if (isset($tags[0]) && is_array($tags[0]) && isset($tags[0]['name'])) { + return ['mode' => 'tags', 'items' => $tags]; + } + + return ['mode' => 'none', 'items' => []]; +} + +/** Libellé d'une release (Gitea : « name » sinon tag ; GitHub : idem). */ +function fws_site_release_label(array $rel): string +{ + $name = trim((string) ($rel['name'] ?? '')); + $tag = (string) ($rel['tag_name'] ?? ($rel['ref'] ?? '')); + return $name !== '' ? $name : ($tag !== '' ? $tag : 'Sans nom'); +} + +/** URL de téléchargement directe d'une release (asset .iso sinon page). */ +function fws_site_release_download_url(array $rel): string +{ + $assets = $rel['assets'] ?? []; + if (is_array($assets)) { + foreach ($assets as $asset) { + if (is_array($asset) + && preg_match('/\.iso$/i', (string) ($asset['name'] ?? '')) + && isset($asset['browser_download_url'])) { + return (string) $asset['browser_download_url']; + } + } + foreach ($assets as $asset) { + if (is_array($asset) && isset($asset['browser_download_url'])) { + return (string) $asset['browser_download_url']; + } + } + } + return (string) ($rel['html_url'] ?? ($rel['zipball_url'] ?? '#')); +} + +/** Date de publication d'une release (date ISO brute, sans l'heure). */ +function fws_site_release_date(array $rel): ?string +{ + foreach (['published_at', 'created_at'] as $k) { + if (!empty($rel[$k])) { + return substr((string) $rel[$k], 0, 10); + } + } + return null; +} + +/* ───────────────────────── Markdown (portage PHP de downloads.js) ──────── */ + +function fws_md_escape(string $t): string +{ + return htmlspecialchars($t, ENT_NOQUOTES, 'UTF-8'); +} + +function fws_md_inline(string $t): string +{ + $t = fws_md_escape($t); + $t = preg_replace('/\*\*\*(.+?)\*\*\*/s', '$1', $t) ?? $t; + $t = preg_replace('/\*\*(.+?)\*\*/s', '$1', $t) ?? $t; + $t = preg_replace('/\*(.+?)\*/s', '$1', $t) ?? $t; + $t = preg_replace('/`([^`]+)`/', '$1', $t) ?? $t; + $t = preg_replace('/!\[([^\]]*)\]\(([^)\s]+)\)/', '$1', $t) ?? $t; + $t = preg_replace('/\[([^\]]+)\]\(([^)\s]+)\)/', '$1', $t) ?? $t; + return $t; +} + +/** Rendu Markdown minimal (titres, listes, tables, citations, code…) + sanitisé. */ +function fws_markdown(string $md): string +{ + if (trim($md) === '') { + return ''; + } + + $lines = preg_split('/\r?\n/', $md) ?: []; + $html = ''; + $inCode = false; + $code = ''; + $codeLang = ''; + $listBuf = ''; + $listKind = ''; + $tableRows = []; + $tableHeader = true; + $quoteBuf = ''; + + $flushList = function () use (&$html, &$listBuf, &$listKind) { + if ($listBuf !== '') { + $html .= '<' . $listKind . ">\n" . $listBuf . '\n"; + $listBuf = ''; + $listKind = ''; + } + }; + $flushTable = function () use (&$html, &$tableRows, &$tableHeader) { + if ($tableRows !== []) { + $html .= "\n" . implode("\n", $tableRows) . "\n
\n"; + $tableRows = []; + $tableHeader = true; + } + }; + $flushQuote = function () use (&$html, &$quoteBuf) { + if ($quoteBuf !== '') { + $html .= '
' . $quoteBuf . "
\n"; + $quoteBuf = ''; + } + }; + $flushAll = function () use ($flushList, $flushTable, $flushQuote) { + $flushList(); + $flushTable(); + $flushQuote(); + }; + $cells = function (string $line): array { + $line = preg_replace('/^\|/', '', $line) ?? $line; + $line = preg_replace('/\|$/', '', $line) ?? $line; + return array_map('trim', explode('|', $line)); + }; + $isSep = function (string $line): bool { + return (bool) preg_match('/^\|?[\s|:\-]+\|?$/', $line) && strpos($line, '-') !== false; + }; + + foreach ($lines as $line) { + if (strncmp($line, '```', 3) === 0) { + $flushAll(); + if ($inCode) { + $langAttr = $codeLang !== '' ? ' class="language-' . e($codeLang) . '"' : ''; + $html .= '
' . fws_md_escape(trim($code)) . "
\n"; + $code = ''; + $codeLang = ''; + $inCode = false; + } else { + $inCode = true; + $codeLang = trim(substr($line, 3)); + } + continue; + } + + if ($inCode) { + $code .= ($code !== '' ? "\n" : '') . $line; + continue; + } + + if (trim($line) === '') { + $flushAll(); + continue; + } + + if (preg_match('/^(#{1,6})\s+(.+)$/', $line, $m)) { + $flushAll(); + $lvl = strlen($m[1]); + $html .= '' . fws_md_inline($m[2]) . '\n"; + continue; + } + + if (preg_match('/^[-*_]{3,}\s*$/', trim($line))) { + $flushAll(); + $html .= "
\n"; + continue; + } + + if (strncmp(ltrim($line), '>', 1) === 0) { + $flushList(); + $flushTable(); + $quoteBuf .= '

' . fws_md_inline((string) preg_replace('/^>\s?/', '', $line)) . '

'; + continue; + } + $flushQuote(); + + if (strpos($line, '|') !== false && !$isSep($line)) { + $flushList(); + $tag = $tableHeader ? 'th' : 'td'; + $row = ''; + foreach ($cells($line) as $c) { + $row .= '<' . $tag . '>' . fws_md_inline($c) . ''; + } + $row .= ''; + $tableRows[] = $row; + $tableHeader = false; + continue; + } + + if ($isSep($line)) { + $tableHeader = false; + continue; + } + + if (preg_match('/^(\s*)[-*+]\s+(.+)$/', $line, $m)) { + $flushTable(); + if ($listKind !== 'ul') { + $flushList(); + $listKind = 'ul'; + } + $listBuf .= '
  • ' . fws_md_inline($m[2]) . "
  • \n"; + continue; + } + + if (preg_match('/^(\s*)\d+\.\s+(.+)$/', $line, $m)) { + $flushTable(); + if ($listKind !== 'ol') { + $flushList(); + $listKind = 'ol'; + } + $listBuf .= '
  • ' . fws_md_inline($m[2]) . "
  • \n"; + continue; + } + + if ($listBuf !== '' && preg_match('/^\s{2,}/', $line)) { + $listBuf = (string) preg_replace('/<\/li>\n$/', ' ' . fws_md_inline(trim($line)) . "\n", $listBuf); + continue; + } + + $flushList(); + $flushTable(); + $html .= '

    ' . fws_md_inline($line) . "

    \n"; + } + + $flushAll(); + if ($inCode) { + $langAttr = $codeLang !== '' ? ' class="language-' . e($codeLang) . '"' : ''; + $html .= '
    ' . fws_md_escape(trim($code)) . "
    \n"; + } + + return fws_sanitize_html($html); +} + +/** Retire scripts/événements/URL javascript: du HTML généré côté serveur. */ +function fws_sanitize_html(string $html): string +{ + $html = (string) preg_replace('#<\s*(script|iframe|object|embed|link|style)\b[^>]*>.*?<\s*/\s*\1\s*>#is', '', $html); + $html = (string) preg_replace('#<\s*(script|iframe|object|embed|link|style)\b[^>]*/?>#i', '', $html); + $html = (string) preg_replace_callback( + '/\son\w+\s*=\s*("[^"]*"|\'[^\']*\'|[^\s>]+)/i', + static function ($m) { + return ''; + }, + $html + ); + $html = (string) preg_replace('/(href|src)\s*=\s*(["\'])\s*javascript:[^"\']*\2/i', '$1="#"', $html); + return $html; +} + +/** + * Tronque un rendu HTML vers ~N caractères de texte (portage de truncateHtml), + * sans couper au milieu d'une balise : on retire les blocs entiers en trop. + * Renvoie ['html' => …, 'truncated' => bool]. + */ +function fws_truncate_html(string $html, int $limit = 600): array +{ + $text = trim((string) preg_replace('/\s+/u', ' ', strip_tags($html))); + if (mb_strlen($text) <= $limit) { + return ['html' => $html, 'truncated' => false]; + } + + $blocks = preg_split('/(?=<)/', $html) ?: [$html]; + $acc = ''; + $count = 0; + $out = ''; + foreach ($blocks as $block) { + if ($block === '') { + continue; + } + $blockText = trim((string) preg_replace('/\s+/u', ' ', strip_tags($block))); + /* On ne coupe qu'avant un bloc porteur de texte : les blocs vides + (fermetures

    , …) suivent toujours leur ouverture, sinon + on produirait du HTML non fermé. */ + if ($blockText !== '' && $count > 0 && $count + mb_strlen($blockText) > $limit) { + break; + } + $out .= $block; + if ($blockText !== '') { + $count += mb_strlen($blockText); + } + } + if ($out === '') { + $out = '

    ' . e(mb_substr($text, 0, $limit)) . '…

    '; + return ['html' => $out, 'truncated' => true]; + } + return ['html' => $out, 'truncated' => true]; +} diff --git a/index.html b/index.html deleted file mode 100644 index a9ea618..0000000 --- a/index.html +++ /dev/null @@ -1,110 +0,0 @@ - - - - - - - Accueil | FWS Linux - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - -
    - -
    - - -
    - - - - - - diff --git a/index.php b/index.php new file mode 100644 index 0000000..386a399 --- /dev/null +++ b/index.php @@ -0,0 +1,8 @@ + +
    +

    Page introuvable

    +

    Cette page n'existe pas ou a été déplacée.

    + +
    diff --git a/p/assets/js/creators-loader.js b/p/assets/js/creators-loader.js deleted file mode 100644 index 39f4fe7..0000000 --- a/p/assets/js/creators-loader.js +++ /dev/null @@ -1,108 +0,0 @@ -(() => { - function formatDate(iso) { - if (!iso) return null; - try { - const d = new Date(iso); - return d.toLocaleDateString("fr-FR", { - year: "numeric", - month: "long", - day: "numeric", - }); - } catch { - return iso; - } - } - - function createCreatorCard(creator) { - const card = document.createElement("article"); - card.className = "creator-card"; - - if (creator.avatar) { - const img = document.createElement("img"); - img.className = "creator-avatar"; - img.src = creator.avatar; - img.alt = creator.name || creator.role || ""; - img.loading = "lazy"; - card.appendChild(img); - } - - const info = document.createElement("div"); - info.className = "creator-info"; - - if (creator.name) { - const name = document.createElement("h3"); - name.className = "creator-name"; - name.textContent = creator.name; - info.appendChild(name); - } - - if (creator.role) { - const role = document.createElement("span"); - role.className = "creator-role"; - role.textContent = creator.role; - info.appendChild(role); - } - - if (creator.joined) { - const joined = document.createElement("span"); - joined.className = "creator-joined"; - joined.textContent = "A rejoint le " + formatDate(creator.joined); - info.appendChild(joined); - } - - if (creator.email) { - const email = document.createElement("a"); - email.className = "creator-email"; - email.href = "mailto:" + creator.email; - email.textContent = creator.email; - info.appendChild(email); - } - - if (creator.links && creator.links.length > 0) { - const links = document.createElement("div"); - links.className = "creator-links"; - for (const link of creator.links) { - const a = document.createElement("a"); - a.className = "creator-link"; - a.href = link.url; - a.target = "_blank"; - a.rel = "noopener noreferrer"; - a.textContent = link.label || link.url; - links.appendChild(a); - } - info.appendChild(links); - } - - card.appendChild(info); - return card; - } - - async function loadCreators() { - const containers = document.querySelectorAll("[data-creators-src]"); - for (const container of containers) { - const src = container.getAttribute("data-creators-src"); - if (!src) continue; - - try { - const response = await fetch(src, { cache: "no-store" }); - if (!response.ok) throw new Error("Erreur " + response.status); - const creators = await response.json(); - - const grid = document.createElement("div"); - grid.className = "creators-grid"; - - for (const creator of creators) { - grid.appendChild(createCreatorCard(creator)); - } - - container.innerHTML = ""; - container.appendChild(grid); - } catch (err) { - container.innerHTML = - '

    Impossible de charger les données des créateurs.

    '; - } - } - } - - loadCreators(); -})(); diff --git a/p/assets/js/downloads.js b/p/assets/js/downloads.js deleted file mode 100644 index c8b542a..0000000 --- a/p/assets/js/downloads.js +++ /dev/null @@ -1,461 +0,0 @@ -(() => { - const OWNER = "You-re-like-Windows-a-bitch"; - const REPO = "ISO"; - const RELEASES_URL = `https://api.github.com/repos/${OWNER}/${REPO}/releases?per_page=5`; - const TAGS_URL = `https://api.github.com/repos/${OWNER}/${REPO}/tags?per_page=5`; - const REPO_URL = `https://github.com/${OWNER}/${REPO}`; - - const currentVersionNode = document.querySelector("[data-current-version]"); - const currentVersionDateNode = document.querySelector("[data-current-version-date]"); - const currentReleaseNoteNode = document.querySelector("[data-current-release-note]"); - const latestDownloadNode = document.querySelector("[data-latest-download]"); - const viewMoreNode = document.querySelector("[data-view-more]"); - const versionsListNode = document.querySelector("[data-versions-list]"); - const toggleNoteNode = document.querySelector("[data-toggle-release-note]"); - - let fullReleaseBodyHtml = ""; - const TRUNCATE_LENGTH = 600; - - function formatDate(value) { - if (!value) return ""; - const date = new Date(value); - if (Number.isNaN(date.getTime())) return ""; - return date.toLocaleDateString("fr-FR", { - year: "numeric", - month: "long", - day: "numeric", - }); - } - - function getReleaseLabel(entry) { - return entry?.name || entry?.tag_name || entry?.ref || "Sans nom"; - } - - function getReleasePageUrl(entry, mode) { - if (mode === "releases") { - return pickDirectDownloadUrl(entry); - } - - if (entry?.name) { - return `${REPO_URL}/releases/tag/${encodeURIComponent(entry.name)}`; - } - - return REPO_URL; - } - - function escapeHtml(text) { - return text - .replace(/&/g, "&") - .replace(//g, ">"); - } - - function parseInline(text) { - let result = escapeHtml(text); - result = result.replace(/\*\*\*(.+?)\*\*\*/g, "$1"); - result = result.replace(/\*\*(.+?)\*\*/g, "$1"); - result = result.replace(/\*(.+?)\*/g, "$1"); - result = result.replace(/`([^`]+)`/g, "$1"); - result = result.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, '$1'); - result = result.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1'); - return result; - } - - function renderMarkdown(md) { - if (!md) return ""; - - var lines = md.split(/\r?\n/); - var html = ""; - var inCodeBlock = false; - var codeBlockContent = ""; - var codeBlockLang = ""; - var listBuffer = ""; - var listKind = ""; - var tableRows = []; - var tableHeader = true; - var blockquoteBuffer = ""; - - function flushList() { - if (listBuffer) { - html += "<" + listKind + ">\n" + listBuffer + "\n"; - listBuffer = ""; - listKind = ""; - } - } - - function flushTable() { - if (tableRows.length) { - html += "\n" + tableRows.join("\n") + "\n
    \n"; - tableRows = []; - tableHeader = true; - } - } - - function flushBlockquote() { - if (blockquoteBuffer) { - html += "
    " + blockquoteBuffer + "
    \n"; - blockquoteBuffer = ""; - } - } - - function parseTableCells(line) { - var trimmed = line.replace(/^\|/, "").replace(/\|$/, ""); - return trimmed.split("|").map(function (c) { return c.trim(); }); - } - - function isTableSep(line) { - return /^\|?[\s|:\-]+\|?$/.test(line) && line.indexOf("-") !== -1; - } - - for (var i = 0; i < lines.length; i++) { - var line = lines[i]; - - if (line.startsWith("```")) { - flushBlockquote(); - flushList(); - flushTable(); - if (inCodeBlock) { - var langAttr = codeBlockLang ? " class=\"language-" + escapeHtml(codeBlockLang) + "\"" : ""; - html += "
    " + escapeHtml(codeBlockContent.trim()) + "
    \n"; - codeBlockContent = ""; - codeBlockLang = ""; - inCodeBlock = false; - } else { - inCodeBlock = true; - codeBlockLang = line.slice(3).trim(); - } - continue; - } - - if (inCodeBlock) { - codeBlockContent += (codeBlockContent ? "\n" : "") + line; - continue; - } - - if (line.trim() === "") { - flushBlockquote(); - flushList(); - flushTable(); - continue; - } - - var hMatch = line.match(/^(#{1,6})\s+(.+)$/); - if (hMatch) { - flushBlockquote(); - flushList(); - flushTable(); - var level = hMatch[1].length; - html += "" + parseInline(hMatch[2]) + "\n"; - continue; - } - - if (/^[-*_]{3,}\s*$/.test(line.trim())) { - flushBlockquote(); - flushList(); - flushTable(); - html += "
    \n"; - continue; - } - - if (line.startsWith("> ") || line.startsWith(">")) { - flushList(); - flushTable(); - var content = line.replace(/^>\s?/, ""); - blockquoteBuffer += "

    " + parseInline(content) + "

    "; - continue; - } else { - flushBlockquote(); - } - - if (line.includes("|") && !isTableSep(line)) { - flushList(); - var cells = parseTableCells(line); - var tag = tableHeader ? "th" : "td"; - tableRows.push("" + cells.map(function (c) { return "<" + tag + ">" + parseInline(c) + ""; }).join("") + ""); - if (tableHeader) tableHeader = false; - continue; - } - - if (isTableSep(line)) { - tableHeader = false; - continue; - } - - if (line.includes("|")) { - flushTable(); - } - - var ulMatch = line.match(/^(\s*)[-*+]\s+(.+)$/); - if (ulMatch) { - flushTable(); - if (listKind !== "ul") { - flushList(); - listKind = "ul"; - } - listBuffer += "
  • " + parseInline(ulMatch[2]) + "
  • \n"; - continue; - } - - var olMatch = line.match(/^(\s*)\d+\.\s+(.+)$/); - if (olMatch) { - flushTable(); - if (listKind !== "ol") { - flushList(); - listKind = "ol"; - } - listBuffer += "
  • " + parseInline(olMatch[2]) + "
  • \n"; - continue; - } - - if (listBuffer && /^\s{2,}/.test(line)) { - listBuffer = listBuffer.replace(/<\/li>\n$/, " " + parseInline(line.trim()) + "\n"); - continue; - } - - flushList(); - flushTable(); - html += "

    " + parseInline(line) + "

    \n"; - } - - flushBlockquote(); - flushList(); - flushTable(); - if (inCodeBlock) { - var langAttr2 = codeBlockLang ? " class=\"language-" + escapeHtml(codeBlockLang) + "\"" : ""; - html += "
    " + escapeHtml(codeBlockContent.trim()) + "
    \n"; - } - - return html; - } - - function sanitizeRenderedHtml(rawHtml) { - const wrapper = document.createElement("div"); - wrapper.innerHTML = rawHtml; - - wrapper.querySelectorAll("script, iframe, object, embed, link, style").forEach(function (node) { node.remove(); }); - wrapper.querySelectorAll("*").forEach(function (node) { - Array.from(node.attributes).forEach(function (attribute) { - var name = attribute.name.toLowerCase(); - var value = attribute.value || ""; - if (name.startsWith("on")) { node.removeAttribute(attribute.name); return; } - if ((name === "href" || name === "src") && /^javascript:/i.test(value)) { node.removeAttribute(attribute.name); } - }); - }); - - return wrapper.innerHTML; - } - - function truncateHtml(fullHtml) { - var temp = document.createElement("div"); - temp.innerHTML = fullHtml; - var text = temp.textContent || ""; - - if (text.length <= TRUNCATE_LENGTH) { - return { html: fullHtml, truncated: false }; - } - - var acc = ""; - var count = 0; - var truncatedHtml = ""; - var children = Array.from(temp.childNodes); - - for (var ci = 0; ci < children.length; ci++) { - var child = children[ci]; - var childText = child.textContent || ""; - - if (count + childText.length > TRUNCATE_LENGTH && count > 0) { - break; - } - - if (child.nodeType === Node.ELEMENT_NODE) { - truncatedHtml += child.outerHTML; - } else { - var remaining = TRUNCATE_LENGTH - count; - if (childText.length > remaining) { - truncatedHtml += escapeHtml(childText.slice(0, remaining)) + "…"; - count = TRUNCATE_LENGTH; - break; - } - truncatedHtml += escapeHtml(childText); - } - count += childText.length; - } - - return { html: truncatedHtml, truncated: true }; - } - - function setupToggle() { - if (!toggleNoteNode || !currentReleaseNoteNode) return; - - toggleNoteNode.addEventListener("click", function () { - var expanded = toggleNoteNode.dataset.expanded === "true"; - if (expanded) { - var result = truncateHtml(fullReleaseBodyHtml); - currentReleaseNoteNode.innerHTML = result.html; - toggleNoteNode.textContent = "Voir plus"; - toggleNoteNode.dataset.expanded = "false"; - } else { - currentReleaseNoteNode.innerHTML = fullReleaseBodyHtml; - toggleNoteNode.textContent = "Voir moins"; - toggleNoteNode.dataset.expanded = "true"; - } - }); - } - - setupToggle(); - - function pickDirectDownloadUrl(release) { - const assets = Array.isArray(release?.assets) ? release.assets : []; - const isoAsset = assets.find((asset) => /\.iso$/i.test(asset?.name || "")); - const directAsset = isoAsset || assets[0]; - - if (directAsset) { - return directAsset.browser_download_url || release.html_url || REPO_URL; - } - - return release?.zipball_url || release?.html_url || REPO_URL; - } - - function renderEmptyState(title, message) { - if (!versionsListNode) return; - versionsListNode.innerHTML = ` -
  • -
    - ${title} - ${message} -
    - -
  • - `; - } - - function renderList(items, mode) { - if (!versionsListNode) return; - versionsListNode.innerHTML = ""; - - const visibleItems = items.slice(1, 6); - - if (!visibleItems.length) { - if (items.length === 0) { - renderEmptyState("Aucune release trouvée", "Le dépôt n'expose pas encore de release ou les releases ne sont pas accessibles."); - } else { - renderEmptyState( - mode === "releases" ? "Aucune release précédente trouvée" : "Aucun tag précédent trouvé", - mode === "releases" - ? "Il n'y a qu'une seule release publiée pour le moment." - : "Il n'y a qu'un seul tag disponible pour le moment." - ); - } - return; - } - - visibleItems.forEach((entry) => { - const li = document.createElement("li"); - li.className = "version-item"; - - const label = getReleaseLabel(entry); - const downloadUrl = getReleasePageUrl(entry, mode); - const published = formatDate(entry.published_at || entry.commit?.committer?.date); - - li.innerHTML = ` -
    - ${label} - ${published ? `Publié le ${published}` : mode === "releases" ? "Date inconnue" : "Tag GitHub"} -
    - - `; - - versionsListNode.appendChild(li); - }); - } - - async function fetchJson(url) { - const response = await fetch(url, { - headers: { Accept: "application/vnd.github+json" }, - }); - - if (!response.ok) { - throw new Error(`GitHub API ${response.status}`); - } - - return response.json(); - } - - async function loadReleases() { - if (currentVersionNode) currentVersionNode.textContent = "Chargement..."; - if (currentVersionDateNode) currentVersionDateNode.textContent = ""; - if (currentReleaseNoteNode) currentReleaseNoteNode.textContent = ""; - if (latestDownloadNode) latestDownloadNode.href = REPO_URL; - if (viewMoreNode) viewMoreNode.href = `${REPO_URL}/releases`; - - try { - const releases = await fetchJson(RELEASES_URL); - - if (Array.isArray(releases) && releases.length > 0) { - const latest = releases[0]; - const latestLabel = getReleaseLabel(latest); - const latestDownloadUrl = pickDirectDownloadUrl(latest); - const latestDate = formatDate(latest.published_at); - - if (currentVersionNode) currentVersionNode.textContent = latestLabel; - if (currentVersionDateNode) currentVersionDateNode.textContent = latestDate ? ` · ${latestDate}` : ""; - if (currentReleaseNoteNode) { - fullReleaseBodyHtml = sanitizeRenderedHtml(renderMarkdown(latest.body || "")); - var result = truncateHtml(fullReleaseBodyHtml); - currentReleaseNoteNode.innerHTML = result.html || "

    Release GitHub la plus récente.

    "; - if (toggleNoteNode) { - toggleNoteNode.style.display = result.truncated ? "inline-block" : "none"; - toggleNoteNode.dataset.expanded = "false"; - toggleNoteNode.textContent = "Voir plus"; - } - } - if (latestDownloadNode) latestDownloadNode.href = latestDownloadUrl; - - renderList(releases, "releases"); - return; - } - } catch (error) { - console.error("Erreur fetch releases:", error.message); - // On tente le fallback tags ci-dessous. - } - - try { - const tags = await fetchJson(TAGS_URL); - - if (Array.isArray(tags) && tags.length > 0) { - const latestTag = tags[0]; - const latestLabel = getReleaseLabel(latestTag); - const latestDownloadUrl = `${REPO_URL}/releases/tag/${encodeURIComponent(latestTag.name)}`; - - if (currentVersionNode) currentVersionNode.textContent = `${latestLabel} (tag)`; - if (currentVersionDateNode) currentVersionDateNode.textContent = ""; - if (currentReleaseNoteNode) { - currentReleaseNoteNode.textContent = "Aucune release GitHub publiée pour le moment, affichage des tags du dépôt."; - } - if (latestDownloadNode) latestDownloadNode.href = latestDownloadUrl; - - renderList(tags, "tags"); - return; - } - - if (currentVersionNode) currentVersionNode.textContent = "Aucune release trouvée"; - if (currentReleaseNoteNode) { - currentReleaseNoteNode.textContent = "Le dépôt ne renvoie ni release ni tag public."; - } - renderEmptyState("Aucune release trouvée", "Le dépôt ne renvoie ni release ni tag public."); - } catch (error) { - console.error("Erreur fetch tags:", error.message); - if (currentVersionNode) currentVersionNode.textContent = "Impossible de charger les releases"; - if (currentReleaseNoteNode) { - currentReleaseNoteNode.textContent = `Erreur: ${error.message}. Vérifie que le repo GitHub est public et qu'il expose des releases ou des tags.`; - } - renderEmptyState("Impossible de charger les releases", "Ouvre le repo GitHub pour vérifier les releases ou les tags."); - } - } - - loadReleases(); -})(); \ No newline at end of file diff --git a/p/assets/js/note-toggle.js b/p/assets/js/note-toggle.js new file mode 100644 index 0000000..3a535f2 --- /dev/null +++ b/p/assets/js/note-toggle.js @@ -0,0 +1,23 @@ +(() => { + const note = document.querySelector("[data-current-release-note]"); + const toggle = document.querySelector("[data-toggle-release-note]"); + if (!note || !toggle) return; + + const fullTemplate = note.querySelector("template[data-note-full]"); + if (!fullTemplate) return; + const fullHtml = fullTemplate.innerHTML; + const truncatedHtml = note.innerHTML; + + toggle.addEventListener("click", () => { + const expanded = toggle.dataset.expanded === "true"; + if (expanded) { + note.innerHTML = truncatedHtml; + toggle.textContent = "Voir plus"; + toggle.dataset.expanded = "false"; + } else { + note.innerHTML = fullHtml; + toggle.textContent = "Voir moins"; + toggle.dataset.expanded = "true"; + } + }); +})(); diff --git a/p/assets/js/packages.js b/p/assets/js/packages.js deleted file mode 100644 index f16375e..0000000 --- a/p/assets/js/packages.js +++ /dev/null @@ -1,487 +0,0 @@ -(() => { - const PACKAGES_SRC = "/p/paquets/packages.json"; - - let packagesPromise = null; - - function fetchPackages() { - if (!packagesPromise) { - packagesPromise = fetch(PACKAGES_SRC, { cache: "no-store" }) - .then((response) => { - if (!response.ok) throw new Error("Erreur " + response.status); - return response.json(); - }); - } - return packagesPromise; - } - - function formatDate(iso) { - if (!iso) return null; - try { - return new Date(iso).toLocaleDateString("fr-FR", { - year: "numeric", - month: "long", - day: "numeric", - }); - } catch { - return iso; - } - } - - /* ── Menu déroulant de la barre de navigation ── */ - - function initNavDropdown() { - const root = document.querySelector("[data-nav-dropdown]"); - if (!root) return; - // Le script est chargé aussi dans la page « Paquets » (injection SPA) : - // on ne câble le menu qu'une seule fois. - if (root.dataset.navReady === "1") return; - root.dataset.navReady = "1"; - - const toggle = root.querySelector(".nav-dropdown-toggle"); - const panel = root.querySelector(".nav-dropdown-panel"); - if (!toggle || !panel) return; - - function setOpen(open) { - root.classList.toggle("is-open", open); - toggle.setAttribute("aria-expanded", open ? "true" : "false"); - } - - function closeIfOutside(event) { - if (!root.contains(event.target)) setOpen(false); - } - - toggle.addEventListener("click", (event) => { - event.stopPropagation(); - setOpen(!root.classList.contains("is-open")); - }); - - document.addEventListener("click", closeIfOutside); - document.addEventListener("keydown", (event) => { - if (event.key === "Escape" && root.classList.contains("is-open")) { - setOpen(false); - toggle.focus(); - } - }); - - // Refermer le menu quand on navigue vers une autre page et - // réévaluer l'état actif une fois l'URL SPA réécrite. - document.addEventListener("page:before-route-change", () => { - setOpen(false); - setTimeout(markActiveRoute, 300); - }); - - function markActiveRoute() { - const search = window.location.search || ""; - const active = search.includes("p=paquets") || search.includes("p/paquets"); - if (active) { - toggle.setAttribute("aria-current", "page"); - } else { - toggle.removeAttribute("aria-current"); - } - } - - window.addEventListener("popstate", markActiveRoute); - markActiveRoute(); - - const list = panel.querySelector("[data-packages-nav]"); - if (!list) return; - - fetchPackages() - .then((packages) => { - list.innerHTML = ""; - packages.forEach((pkg, index) => { - const item = document.createElement("a"); - item.className = "nav-dropdown-item"; - item.href = "/?p/paquets/" + (index + 1) + "/"; - item.dataset.route = "paquets/" + (index + 1); - - const name = document.createElement("strong"); - name.textContent = pkg.name; - - if (pkg.latest && pkg.latest.name) { - const version = document.createElement("span"); - version.className = "nav-dropdown-version"; - version.textContent = pkg.latest.name; - name.appendChild(version); - } - - const tagline = document.createElement("small"); - tagline.textContent = pkg.tagline || ""; - - item.appendChild(name); - item.appendChild(tagline); - - item.addEventListener("click", () => setOpen(false)); - - list.appendChild(item); - }); - }) - .catch(() => { - list.innerHTML = ''; - }); - } - - /* ── Page « Paquets » ── */ - - function createEmptyState(message) { - const p = document.createElement("p"); - p.className = "paquet-empty"; - p.textContent = message; - return p; - } - - function createChangelog(pkg) { - const wrapper = document.createElement("div"); - wrapper.className = "paquet-changelog"; - - const title = document.createElement("h3"); - title.textContent = "Historique"; - wrapper.appendChild(title); - - if (!pkg.changelog || pkg.changelog.length === 0) { - wrapper.appendChild(createEmptyState("Historique en cours de rédaction.")); - return wrapper; - } - - const timeline = document.createElement("ol"); - timeline.className = "paquet-timeline"; - - for (const entry of pkg.changelog) { - const li = document.createElement("li"); - li.className = "paquet-timeline-item"; - - const version = document.createElement("strong"); - version.className = "paquet-timeline-version"; - version.textContent = entry.version || "—"; - - const date = document.createElement("time"); - date.className = "paquet-timeline-date"; - date.textContent = formatDate(entry.date) || ""; - if (entry.date) date.dateTime = entry.date; - - const notes = document.createElement("span"); - notes.className = "paquet-timeline-notes"; - notes.textContent = entry.notes || ""; - - li.appendChild(version); - li.appendChild(date); - if (entry.notes) li.appendChild(notes); - timeline.appendChild(li); - } - - wrapper.appendChild(timeline); - return wrapper; - } - - function createScreens(pkg) { - const wrapper = document.createElement("div"); - wrapper.className = "paquet-screens"; - - const title = document.createElement("h3"); - title.textContent = "Captures d'écran"; - wrapper.appendChild(title); - - if (!pkg.screens || pkg.screens.length === 0) { - wrapper.appendChild(createEmptyState("Captures d'écran à venir.")); - return wrapper; - } - - const grid = document.createElement("div"); - grid.className = "paquet-screens-grid"; - - for (const screen of pkg.screens) { - const figure = document.createElement("figure"); - const img = document.createElement("img"); - img.src = screen.src; - img.alt = screen.alt || pkg.name; - img.loading = "lazy"; - figure.appendChild(img); - if (screen.caption) { - const figcaption = document.createElement("figcaption"); - figcaption.textContent = screen.caption; - figure.appendChild(figcaption); - } - grid.appendChild(figure); - } - - wrapper.appendChild(grid); - return wrapper; - } - - function createLinks(pkg) { - const wrapper = document.createElement("div"); - wrapper.className = "paquet-links"; - - const title = document.createElement("h3"); - title.textContent = "Liens utiles"; - wrapper.appendChild(title); - - if (!pkg.links || pkg.links.length === 0) { - wrapper.appendChild(createEmptyState("Aucun lien pour le moment.")); - return wrapper; - } - - for (const link of pkg.links) { - const a = document.createElement("a"); - a.className = "button button-secondary"; - a.href = link.url; - const external = /^https?:\/\//i.test(link.url); - if (external) { - a.target = "_blank"; - a.rel = "noopener noreferrer"; - } - a.textContent = link.label || link.url; - wrapper.appendChild(a); - } - - return wrapper; - } - - function createPackageCard(pkg, position) { - const card = document.createElement("article"); - card.className = "paquet-card"; - card.id = "paquet-" + pkg.id; - - const head = document.createElement("header"); - head.className = "paquet-head"; - - const titleRow = document.createElement("div"); - titleRow.className = "paquet-title-row"; - - const title = document.createElement("h2"); - title.textContent = pkg.name; - - const badge = document.createElement("span"); - badge.className = "paquet-since"; - badge.textContent = pkg.sinceLabel || "FWS"; - if (pkg.since) { - badge.title = "Depuis le " + formatDate(pkg.since); - } - - const detailLink = document.createElement("a"); - detailLink.className = "paquet-detail-link"; - detailLink.href = "/?p/paquets/" + position + "/"; - detailLink.dataset.route = "paquets/" + position; - detailLink.textContent = "Voir en grand"; - - titleRow.appendChild(title); - titleRow.appendChild(badge); - titleRow.appendChild(detailLink); - head.appendChild(titleRow); - - if (pkg.tagline) { - const tagline = document.createElement("p"); - tagline.className = "paquet-tagline"; - tagline.textContent = pkg.tagline; - head.appendChild(tagline); - } - - const latest = document.createElement("p"); - latest.className = "paquet-latest"; - if (pkg.latest && pkg.latest.name) { - latest.textContent = - "Dernière release : " + - pkg.latest.name + - (pkg.latest.date ? " — " + formatDate(pkg.latest.date) : ""); - } else { - latest.textContent = "Aucune release publiée pour le moment."; - } - head.appendChild(latest); - - if (pkg.description) { - const description = document.createElement("p"); - description.className = "paquet-description"; - description.textContent = pkg.description; - head.appendChild(description); - } - - card.appendChild(head); - - const body = document.createElement("div"); - body.className = "paquet-body"; - body.appendChild(createChangelog(pkg)); - body.appendChild(createScreens(pkg)); - body.appendChild(createLinks(pkg)); - card.appendChild(body); - - return card; - } - - function initPackagesPage(container) { - fetchPackages() - .then((packages) => { - container.innerHTML = ""; - packages.forEach((pkg, index) => { - container.appendChild(createPackageCard(pkg, index + 1)); - }); - }) - .catch(() => { - container.innerHTML = ""; - container.appendChild( - createEmptyState("Impossible de charger les paquets. Réessayez plus tard.") - ); - }); - } - - /* ── Page détail « Paquets / N » ── */ - - function packageIndexFromLocation() { - const haystack = window.location.search + window.location.pathname; - const match = haystack.match(/paquets\/(\d+)/); - return match ? parseInt(match[1], 10) : 1; - } - - function createDetailNav(nav, position, total) { - if (position > 1) { - const prev = document.createElement("a"); - prev.className = "paquet-detail-prev"; - prev.href = "/?p/paquets/" + (position - 1) + "/"; - prev.dataset.route = "paquets/" + (position - 1); - prev.textContent = "← Paquet précédent"; - nav.appendChild(prev); - } - - if (position < total) { - const next = document.createElement("a"); - next.className = "paquet-detail-next"; - next.href = "/?p/paquets/" + (position + 1) + "/"; - next.dataset.route = "paquets/" + (position + 1); - next.textContent = "Paquet suivant →"; - nav.appendChild(next); - } - } - - function renderPackageDetail(container, pkg, position, total) { - const back = document.createElement("a"); - back.className = "paquet-detail-back"; - back.href = "/?p/paquets/"; - back.dataset.route = "paquets"; - back.textContent = "← Tous les paquets"; - container.appendChild(back); - - const hero = document.createElement("div"); - hero.className = "paquet-detail-hero"; - - const badge = document.createElement("span"); - badge.className = "paquet-since"; - badge.textContent = pkg.sinceLabel || "FWS"; - if (pkg.since) { - badge.title = "Depuis le " + formatDate(pkg.since); - } - hero.appendChild(badge); - - const title = document.createElement("h1"); - title.textContent = pkg.name; - hero.appendChild(title); - - if (pkg.tagline) { - const tagline = document.createElement("p"); - tagline.className = "paquet-tagline"; - tagline.textContent = pkg.tagline; - hero.appendChild(tagline); - } - - if (pkg.description) { - const description = document.createElement("p"); - description.className = "paquet-description"; - description.textContent = pkg.description; - hero.appendChild(description); - } - - const latest = document.createElement("div"); - latest.className = "paquet-detail-latest"; - if (pkg.latest && pkg.latest.name) { - const version = document.createElement("span"); - version.className = "paquet-detail-version"; - version.textContent = pkg.latest.name; - latest.appendChild(version); - - if (pkg.latest.date) { - const date = document.createElement("span"); - date.className = "paquet-detail-date"; - date.textContent = "Publiée le " + formatDate(pkg.latest.date); - latest.appendChild(date); - } - } else { - latest.textContent = "Aucune release publiée pour le moment."; - latest.classList.add("paquet-detail-latest-empty"); - } - hero.appendChild(latest); - - container.appendChild(hero); - - const body = document.createElement("div"); - body.className = "paquet-detail-body"; - body.appendChild(createChangelog(pkg)); - body.appendChild(createScreens(pkg)); - container.appendChild(body); - - container.appendChild(createLinks(pkg)); - - const nav = document.createElement("nav"); - nav.className = "paquet-detail-nav"; - nav.setAttribute("aria-label", "Parcourir les paquets"); - createDetailNav(nav, position, total); - if (nav.childNodes.length > 0) { - container.appendChild(nav); - } - } - - function initPackageDetail(container) { - const position = packageIndexFromLocation(); - - fetchPackages() - .then((packages) => { - container.innerHTML = ""; - const pkg = packages[position - 1]; - if (!pkg) { - container.appendChild( - createEmptyState("Ce paquet n'existe pas (il y en a " + packages.length + ").") - ); - const back = document.createElement("a"); - back.className = "paquet-detail-back"; - back.href = "/?p/paquets/"; - back.dataset.route = "paquets"; - back.textContent = "← Tous les paquets"; - container.appendChild(back); - return; - } - - renderPackageDetail(container, pkg, position, packages.length); - // Le routeur SPA applique le titre et le scroll après le rendu : - // on force le vrai nom du paquet un peu plus tard. - setTimeout(() => { - document.title = pkg.name + " | FWS Linux"; - }, 150); - }) - .catch(() => { - container.innerHTML = ""; - container.appendChild( - createEmptyState("Impossible de charger le paquet. Réessayez plus tard.") - ); - }); - } - - /* ── Initialisation ── */ - - function init() { - const hasNav = document.querySelector("[data-nav-dropdown]") !== null; - const hasPage = document.querySelector("[data-packages-page]") !== null; - const hasDetail = document.querySelector("[data-package-detail]") !== null; - if (!hasNav && !hasPage && !hasDetail) return; - - initNavDropdown(); - - const pageContainers = document.querySelectorAll("[data-packages-page]"); - pageContainers.forEach(initPackagesPage); - - const detailContainers = document.querySelectorAll("[data-package-detail]"); - detailContainers.forEach(initPackageDetail); - } - - if (document.readyState === "loading") { - document.addEventListener("DOMContentLoaded", init); - } else { - init(); - } -})(); \ No newline at end of file diff --git a/p/assets/main-nav/app.js b/p/assets/main-nav/app.js deleted file mode 100644 index 197771f..0000000 --- a/p/assets/main-nav/app.js +++ /dev/null @@ -1,222 +0,0 @@ -(() => { - const main = document.getElementById("app-main"); - const footerYear = document.getElementById("footer-year"); - const pageStyleSelectors = "[data-page-style='true']"; - const pageScriptSelectors = "script[data-page-script='true']"; - - const links = Array.from(document.querySelectorAll("[data-route]")); - - if (footerYear) { - footerYear.textContent = new Date().getFullYear().toString(); - } - - function clearInjectedPageStyles() { - document.querySelectorAll(pageStyleSelectors).forEach((node) => node.remove()); - } - - function clearInjectedPageScripts() { - document.dispatchEvent(new CustomEvent("page:before-route-change")); - document.querySelectorAll(pageScriptSelectors).forEach((node) => node.remove()); - } - - function injectPageStyles(parsedDocument, sourceUrl) { - clearInjectedPageStyles(); - - const head = parsedDocument.head; - if (!head) { - return; - } - - const styleNodes = Array.from(head.querySelectorAll("link[rel='stylesheet'], style")); - - styleNodes.forEach((node) => { - const clonedNode = node.cloneNode(true); - clonedNode.setAttribute("data-page-style", "true"); - - if (clonedNode.tagName === "LINK") { - const href = clonedNode.getAttribute("href"); - if (href) { - clonedNode.href = new URL(href, sourceUrl).toString(); - } - } - - document.head.appendChild(clonedNode); - }); - } - - async function injectPageScripts(parsedDocument, sourceUrl) { - clearInjectedPageScripts(); - - const scriptNodes = Array.from(parsedDocument.querySelectorAll("script")); - - for (const node of scriptNodes) { - const scriptElement = document.createElement("script"); - scriptElement.setAttribute("data-page-script", "true"); - - const src = node.getAttribute("src"); - if (src) { - scriptElement.src = new URL(src, sourceUrl).toString(); - scriptElement.async = false; - if (node.defer) { - scriptElement.defer = true; - } - - await new Promise((resolve, reject) => { - scriptElement.onload = () => resolve(); - scriptElement.onerror = () => reject(new Error(`Impossible de charger le script: ${src}`)); - document.body.appendChild(scriptElement); - }); - - continue; - } - - scriptElement.textContent = node.textContent; - document.body.appendChild(scriptElement); - } - } - - function normalizeRoute(value) { - const raw = (value ?? "").toString().trim().toLowerCase(); - if (!raw || raw === "/" || raw === "home" || raw === "index" || raw === "accueil") { - return "index"; - } - return raw.replace(/^\/+|\/+$/g, "") || "index"; - } - - function routeFromLocation() { - const params = new URLSearchParams(window.location.search); - - if (params.has("p")) { - return normalizeRoute(params.get("p")); - } - - const rawSearch = window.location.search.replace(/^\?/, ""); - if (rawSearch.startsWith("p/")) { - return normalizeRoute(rawSearch.slice(2)); - } - - if (rawSearch.startsWith("p=")) { - return normalizeRoute(rawSearch.slice(2)); - } - - const path = window.location.pathname.replace(/^\/+|\/+$/g, ""); - if (path) { - if (path.endsWith(".html")) { - return "index"; - } - - const parts = path.split("/"); - if (parts[0] === "p" && parts[1]) { - return normalizeRoute(parts.slice(1).join("/")); - } - return normalizeRoute(parts[0]); - } - - return "index"; - } - - function setActiveRoute(route) { - links.forEach((link) => { - const isActive = link.dataset.route === route; - if (isActive) { - link.setAttribute("aria-current", "page"); - } else { - link.removeAttribute("aria-current"); - } - }); - } - - function setCanonicalUrl(route, replace = false) { - const url = route === "index" ? "/?p/index/" : `/?p/${route}/`; - if (replace) { - history.replaceState({ route }, "", url); - return; - } - history.pushState({ route }, "", url); - } - - function routeToSource(route) { - // Les routes « paquets/N » affichent le détail (grand format) du paquet N. - if (/^paquets\/\d+$/.test(route)) { - return "p/paquets/_detail/index.html"; - } - return `p/${route}/index.html`; - } - - function routeToTitle(route) { - if (route === "index") { - return "Accueil | FWS Linux"; - } - - const label = route - .split("/") - .filter(Boolean) - .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1)) - .join(" / "); - - return `${label} | FWS Linux`; - } - - async function loadRoute(route) { - clearInjectedPageScripts(); - - const source = routeToSource(route); - // On laisse le cache HTTP faire son travail (revalidation 304) : - // le .htaccess renvoie « Cache-Control: no-cache » sur le HTML, - // donc on revalide à chaque navigation sans re-télécharger le corps. - const response = await fetch(source); - if (!response.ok) { - throw new Error(`Impossible de charger ${source} (${response.status})`); - } - - const html = await response.text(); - const parsed = new DOMParser().parseFromString(html, "text/html"); - injectPageStyles(parsed, response.url); - const injected = parsed.querySelector("[data-page-content]") ?? parsed.body; - main.innerHTML = injected.innerHTML.trim(); - await injectPageScripts(parsed, response.url); - // Update document title from the fetched page if present, otherwise use generated title - const pageTitleEl = parsed.querySelector("title"); - if (pageTitleEl && pageTitleEl.textContent && pageTitleEl.textContent.trim()) { - document.title = pageTitleEl.textContent.trim(); - } else { - document.title = routeToTitle(route); - } - } - - function render(route, { replaceHistory = false } = {}) { - const safeRoute = route || "index"; - - loadRoute(safeRoute) - .then(() => { - setActiveRoute(safeRoute); - setCanonicalUrl(safeRoute, replaceHistory); - window.scrollTo({ top: 0, behavior: "smooth" }); - }) - .catch((error) => { - main.innerHTML = `

    Erreur de chargement

    ${error.message}

    `; - setActiveRoute("index"); - }); - } - - document.addEventListener("click", (event) => { - const link = event.target.closest("[data-route]"); - if (!link) { - return; - } - - const route = normalizeRoute(link.dataset.route); - if (!route) { - return; - } - - event.preventDefault(); - render(route); - }); - - window.addEventListener("popstate", () => { - render(routeFromLocation(), { replaceHistory: true }); - }); - - render(routeFromLocation(), { replaceHistory: true }); -})(); \ No newline at end of file diff --git a/p/assets/main-nav/nav.js b/p/assets/main-nav/nav.js new file mode 100644 index 0000000..a4bd2b4 --- /dev/null +++ b/p/assets/main-nav/nav.js @@ -0,0 +1,35 @@ +(() => { + /* Menu déroulant « Paquets » de la barre de navigation. + Le reste (contenu, données, états actifs) est rendu côté serveur. */ + const root = document.querySelector("[data-nav-dropdown]"); + if (!root) return; + + const toggle = root.querySelector(".nav-dropdown-toggle"); + const panel = root.querySelector(".nav-dropdown-panel"); + if (!toggle || !panel) return; + + function setOpen(open) { + root.classList.toggle("is-open", open); + toggle.setAttribute("aria-expanded", open ? "true" : "false"); + } + + toggle.addEventListener("click", (event) => { + event.stopPropagation(); + setOpen(!root.classList.contains("is-open")); + }); + + document.addEventListener("click", (event) => { + if (!root.contains(event.target)) setOpen(false); + }); + + document.addEventListener("keydown", (event) => { + if (event.key === "Escape" && root.classList.contains("is-open")) { + setOpen(false); + toggle.focus(); + } + }); + + panel.querySelectorAll("a").forEach((link) => { + link.addEventListener("click", () => setOpen(false)); + }); +})(); diff --git a/p/assets/styles/paquets.css b/p/assets/styles/paquets.css index 31e8e53..ca35b23 100644 --- a/p/assets/styles/paquets.css +++ b/p/assets/styles/paquets.css @@ -460,38 +460,6 @@ grid-column: auto; } -.paquet-detail-nav { - display: flex; - justify-content: space-between; - gap: 1rem; - padding-top: 0.5rem; -} - -.paquet-detail-nav a { - color: var(--accent); - text-decoration: none; - font-weight: 500; - font-size: 0.95rem; - padding: 0.5rem 0.75rem; - border: 1px solid var(--border); - border-radius: 0.5rem; - background: var(--surface); - transition: color 160ms ease, background 160ms ease; -} - -.paquet-detail-nav a:hover { - color: var(--accent-strong); - background: var(--accent-bg); -} - -.paquet-detail-prev { - margin-right: auto; -} - -.paquet-detail-next { - margin-left: auto; -} - /* ── Responsive ── */ @media (max-width: 700px) { diff --git a/p/contact/index.html b/p/contact/index.html deleted file mode 100644 index 123a6f2..0000000 --- a/p/contact/index.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - Contact | FWS Linux - - - - - - -
    -

    Contactez l'équipe de développement

    -

    Une question, un bug à signaler ou envie de contribuer ? Voici comment nous joindre.

    -
    - -
    - -
    -
    -

    Notre seul canal officiel actuel

    -

    Le projet est en plein développement. Pour le moment, nous n'avons pas encore d'adresse email dédiée ni de réseaux sociaux.

    -

    - Suivez le projet et ouvrez des Issues / PR ici : -

    - Notre GitHub -
    - -
    -
    - - diff --git a/p/contact/index.php b/p/contact/index.php new file mode 100644 index 0000000..c864c49 --- /dev/null +++ b/p/contact/index.php @@ -0,0 +1,36 @@ + +
    +

    Contactez l'équipe de développement

    +

    Une question, un bug à signaler ou envie de contribuer ? Voici comment nous joindre.

    +
    + +
    + +
    +
    +

    Notre seul canal officiel actuel

    +

    Le projet est en plein développement. Pour le moment, nous n'avons pas encore d'adresse email dédiée ni de réseaux sociaux.

    +

    + Suivez le projet et ouvrez des Issues / PR ici : +

    + Notre GitHub +
    + +
    +
    diff --git a/p/dl/index.html b/p/dl/index.html deleted file mode 100644 index 2e4cf01..0000000 --- a/p/dl/index.html +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - Téléchargements | FWS Linux - - - - - -
    -
    -
    -

    Téléchargements

    -
    -
    -

    Dernière version

    -
    -
    - Chargement... - -
    - -
    -
    - -
    - -
    -

    Versions précédentes

    -
      -
      -
      -
      -
      -
      - - - - diff --git a/p/dl/index.php b/p/dl/index.php new file mode 100644 index 0000000..34f3030 --- /dev/null +++ b/p/dl/index.php @@ -0,0 +1,112 @@ +Release la plus récente.

      '; + } + $tr = fws_truncate_html($latestNoteFull, 600); + $latestNote = $tr['html']; + $latestTruncated = $tr['truncated']; +} +?> +
      +
      +

      Téléchargements

      +
      +
      +

      Dernière version

      +
      +
      + + +
      + +
      +
      Aucune release publiée pour le moment, affichage des tags du dépôt.

      '; + } elseif ($latest === null) { + echo '

      Le dépôt ne renvoie ni release ni tag public.

      '; + } else { + echo $latestNote; + } + ?>
      + +
      + +
      +

      Versions précédentes

      +
        Aucune release trouvéeLe dépôt n\'expose pas encore de release ou les releases ne sont pas accessibles.
        ' + . ''; + } elseif ($previous === []) { + echo '
      • Aucune release précédenteIl n\'y a qu\'une seule release publiée pour le moment.
      • '; + } else { + foreach ($previous as $rel) { + $d = fws_format_date(fws_site_release_date($rel)); + $url = $mode === 'tags' + ? 'https://github.com/You-re-like-Windows-a-bitch/ISO/releases/tag/' . rawurlencode((string) ($rel['name'] ?? $rel['ref'] ?? '')) + : fws_site_release_download_url($rel); + echo '
      • ' . e(fws_site_release_label($rel)) . '' + . '' . ($d !== '' ? 'Publié le ' . e($d) : ($mode === 'tags' ? 'Tag GitHub' : 'Date inconnue')) . '
        ' + . '
      • '; + } + } + ?>
      +
      +
      +
      +
      diff --git a/p/equipe/index.html b/p/equipe/index.html deleted file mode 100644 index 5db02c8..0000000 --- a/p/equipe/index.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - L'équipe | FWS Linux - - - - - - - -
      -
      -

      L'équipe

      -

      Les personnes qui contribuent au projet FWS Linux.

      -
      - -
      -
      -
      -
      - - - - diff --git a/p/equipe/index.php b/p/equipe/index.php new file mode 100644 index 0000000..95d1667 --- /dev/null +++ b/p/equipe/index.php @@ -0,0 +1,69 @@ + +
      +

      L'équipe

      +

      Les personnes qui contribuent au projet FWS Linux.

      +
      + +
      + +

      Impossible de charger les données des créateurs.

      + +
      + +
      + + <?= e((string) ($creator['name'] ?? $creator['role'] ?? '')) ?> + +
      + +

      + + + + + + A rejoint le + + + + + + + +
      +
      + +
      + +
      diff --git a/p/index/index.html b/p/index/index.html deleted file mode 100644 index 6685f92..0000000 --- a/p/index/index.html +++ /dev/null @@ -1,116 +0,0 @@ - - - - - - Accueil | FWS Linux - - - - - -
      - - -
      -
      -

      Installation simplifiée

      -

      Installateur graphique pour une configuration facile et rapide.

      -
      -
      -

      Léger et rapide

      -

      Conçu pour être peu gourmand en ressources : idéal pour redonner vie à d'anciens PC.

      -
      -
      -

      Respect de la vie privée

      -

      Pas de télémétrie intrusive ni de collecte de données : vous gardez le contrôle.

      -
      -
      -

      Compatibilité Windows

      -

      Exécutez vos logiciels Windows avec Wine et Winboat sans devoir rester sous Windows.

      -
      -
      - -
      -
      -

      Choisissez votre environnement à l'installation

      -

      FWS Linux vous laisse choisir l'interface qui correspond à votre usage. Vous pouvez démarrer en CLI minimale ou installer un bureau complet dès le début.

      -
      - -
      -
      -

      KDE Plasma

      -

      Interface moderne, complète et hautement personnalisable. Un excellent choix si vous voulez un bureau riche avec de nombreux outils intégrés.

      -
      -
      - Capture d'écran de l'environnement KDE Plasma sur FWS Linux -
      -
      - -
      -
      - Capture d'écran de l'environnement GNOME sur FWS Linux -
      -
      -

      GNOME

      -

      Expérience épurée et orientée productivité. GNOME met l'accent sur la simplicité d'utilisation et un flux de travail propre sans surcharge visuelle.

      -
      -
      - -
      -
      -

      XFCE

      -

      Environnement léger et très stable, idéal pour les machines modestes ou pour privilégier les performances au quotidien.

      -
      -
      - Capture d'écran de l'environnement XFCE sur FWS Linux -
      -
      - -
      -
      - Capture d'écran de l'environnement Hyprland sur FWS Linux -
      -
      -

      Hyprland

      -

      Tiling Wayland rapide et moderne, pensé pour un workflow clavier et une grande efficacité. Parfait pour les utilisateurs techniques qui aiment optimiser leur espace de travail.

      -
      -
      - -
      -
      -

      CLI (sans environnement)

      -

      Version minimale pour les utilisateurs avancés, les serveurs ou ceux qui veulent construire leur système à la carte. Aucun bureau graphique n'est préinstallé.

      -
      -
      - Capture d'écran de l'interface CLI de FWS Linux -
      -
      -
      -
      - - - - diff --git a/p/index/index.php b/p/index/index.php new file mode 100644 index 0000000..604cd1d --- /dev/null +++ b/p/index/index.php @@ -0,0 +1,117 @@ + + + +
      +
      +

      Installation simplifiée

      +

      Installateur graphique pour une configuration facile et rapide.

      +
      +
      +

      Léger et rapide

      +

      Conçu pour être peu gourmand en ressources : idéal pour redonner vie à d'anciens PC.

      +
      +
      +

      Respect de la vie privée

      +

      Pas de télémétrie intrusive ni de collecte de données : vous gardez le contrôle.

      +
      +
      +

      Compatibilité Windows

      +

      Exécutez vos logiciels Windows avec Wine et Winboat sans devoir rester sous Windows.

      +
      +
      + +
      +
      +

      Choisissez votre environnement à l'installation

      +

      FWS Linux vous laisse choisir l'interface qui correspond à votre usage. Vous pouvez démarrer en CLI minimale ou installer un bureau complet dès le début.

      +
      + +
      +
      +

      KDE Plasma

      +

      Interface moderne, complète et hautement personnalisable. Un excellent choix si vous voulez un bureau riche avec de nombreux outils intégrés.

      +
      +
      + Capture d'écran de l'environnement KDE Plasma sur FWS Linux +
      +
      + +
      +
      + Capture d'écran de l'environnement GNOME sur FWS Linux +
      +
      +

      GNOME

      +

      Expérience épurée et orientée productivité. GNOME met l'accent sur la simplicité d'utilisation et un flux de travail propre sans surcharge visuelle.

      +
      +
      + +
      +
      +

      XFCE

      +

      Environnement léger et très stable, idéal pour les machines modestes ou pour privilégier les performances au quotidien.

      +
      +
      + Capture d'écran de l'environnement XFCE sur FWS Linux +
      +
      + +
      +
      + Capture d'écran de l'environnement Hyprland sur FWS Linux +
      +
      +

      Hyprland

      +

      Tiling Wayland rapide et moderne, pensé pour un workflow clavier et une grande efficacité. Parfait pour les utilisateurs techniques qui aiment optimiser leur espace de travail.

      +
      +
      + +
      +
      +

      CLI (sans environnement)

      +

      Version minimale pour les utilisateurs avancés, les serveurs ou ceux qui veulent construire leur système à la carte. Aucun bureau graphique n'est préinstallé.

      +
      +
      + Capture d'écran de l'interface CLI de FWS Linux +
      +
      +
      diff --git a/p/paquets/_detail/index.html b/p/paquets/_detail/index.html deleted file mode 100644 index 3f029df..0000000 --- a/p/paquets/_detail/index.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - Paquet | FWS Linux - - - - - -
      -
      -
      - - - - \ No newline at end of file diff --git a/p/paquets/detail.php b/p/paquets/detail.php new file mode 100644 index 0000000..084405d --- /dev/null +++ b/p/paquets/detail.php @@ -0,0 +1,108 @@ + $p) { + if ((int) ($p['dbId'] ?? 0) === $detailId || ($p['dbId'] ?? 0) === 0 && ($i + 1) === $detailId) { + $pkg = $p; + break; + } +} + +if ($pkg === null) { + http_response_code(404); + $title = 'Paquet introuvable | FWS Linux'; + echo '
      ' + . '

      Ce paquet n\'existe pas (il y en a ' . count($packages) . ').

      ' + . '← Tous les paquets' + . '
      '; + return; +} + +$title = $pkg['name'] . ' | FWS Linux'; +$description = (string) ($pkg['tagline'] ?? '') !== '' ? (string) $pkg['tagline'] : (string) ($pkg['description'] ?? ''); + +$latest = $pkg['latest'] ?? null; +?> +
      + ← Tous les paquets + +
      + +

      +

      +

      +
      + + + + Publiée le + + + Aucune release publiée pour le moment. + +
      +
      + +
      + +

      Historique

      Historique en cours de rédaction.

      + +

      Historique

      +
        + +
      1. + + + + + +
      2. + +
      +
      + + + +

      Captures d'écran

      Captures d'écran à venir.

      + +

      Captures d'écran

      +
      + +
      + <?= e((string) ($screen['alt'] ?? $pkg['name'])) ?> + +
      + +
      + +
      +
      + +
      + + +
      diff --git a/p/paquets/index.html b/p/paquets/index.html deleted file mode 100644 index 2f5028a..0000000 --- a/p/paquets/index.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - Paquets | FWS Linux - - - - - - -
      -
      -

      Paquets

      -

      Tous les outils développés pour FWS Linux, leur historique, leurs captures d'écran et les liens utiles.

      -
      - -
      -
      - - - - \ No newline at end of file diff --git a/p/paquets/index.php b/p/paquets/index.php new file mode 100644 index 0000000..6a500bd --- /dev/null +++ b/p/paquets/index.php @@ -0,0 +1,117 @@ +' . e($message) . '

      '; +} + +function fws_packages_changelog(array $pkg): string +{ + $html = '

      Historique

      '; + if (empty($pkg['changelog'])) { + $html .= fws_packages_empty('Historique en cours de rédaction.') . '
      '; + return $html; + } + $html .= '
        '; + foreach ($pkg['changelog'] as $entry) { + $html .= '
      1. ' + . '' . e((string) ($entry['version'] ?? '—')) . '' + . '' + . (!empty($entry['notes']) ? '' . e((string) $entry['notes']) . '' : '') + . '
      2. '; + } + $html .= '
      '; + return $html; +} + +function fws_packages_screens(array $pkg): string +{ + $html = '

      Captures d\'écran

      '; + if (empty($pkg['screens'])) { + $html .= fws_packages_empty("Captures d'écran à venir.") . '
      '; + return $html; + } + $html .= '
      '; + foreach ($pkg['screens'] as $screen) { + $html .= '
      '
+            . e((string) ($screen['alt'] ?? ($pkg['name'] ?? ''))) . ''; + if (!empty($screen['caption'])) { + $html .= '
      ' . e((string) $screen['caption']) . '
      '; + } + $html .= '
      '; + } + $html .= '
      '; + return $html; +} + +function fws_packages_links(array $pkg): string +{ + $html = ''; + return $html; + } + foreach ($pkg['links'] as $link) { + $url = (string) ($link['url'] ?? ''); + $external = (bool) preg_match('/^https?:\/\//i', $url); + $html .= '' + . e((string) ($link['label'] ?? '') !== '' ? (string) $link['label'] : $url) . ''; + } + $html .= ''; + return $html; +} + +function fws_packages_card(array $pkg, int $position): string +{ + $latest = $pkg['latest'] ?? null; + $latestText = ($latest !== null && ($latest['name'] ?? '') !== '') + ? 'Dernière release : ' . $latest['name'] . (!empty($latest['date']) ? ' — ' . fws_format_date((string) $latest['date']) : '') + : 'Aucune release publiée pour le moment.'; + + $html = '
      ' + . '
      ' + . '

      ' . e($pkg['name']) . '

      ' + . '' + . e($pkg['sinceLabel'] !== '' ? $pkg['sinceLabel'] : 'FWS') . '' + . 'Voir en grand' + . '
      ' + . (!empty($pkg['tagline']) ? '

      ' . e($pkg['tagline']) . '

      ' : '') + . '

      ' . e($latestText) . '

      ' + . (!empty($pkg['description']) ? '

      ' . e($pkg['description']) . '

      ' : '') + . '
      ' + . '
      ' . fws_packages_changelog($pkg) . fws_packages_screens($pkg) . fws_packages_links($pkg) . '
      ' + . '
      '; + return $html; +} +?> +
      +

      Paquets

      +

      Tous les outils développés pour FWS Linux, leur historique, leurs captures d'écran et les liens utiles.

      +
      + +
      + + + + $pkg): ?> + + + +
      diff --git a/page.php b/page.php new file mode 100644 index 0000000..d83fcb1 --- /dev/null +++ b/page.php @@ -0,0 +1,241 @@ +/index.php et la coquille + * (header/nav/footer) est écrite une seule fois ici. + */ + +declare(strict_types=1); + +require __DIR__ . '/inc/site.php'; + +/* ───────────────────────── route ───────────────────────── */ + +function fws_site_current_route(): string +{ + $raw = ''; + $qs = (string) ($_SERVER['QUERY_STRING'] ?? ''); + if ($qs !== '') { + if (str_starts_with($qs, 'p=')) { + $raw = substr($qs, 2); + } elseif (str_starts_with($qs, 'p/')) { + $raw = substr($qs, 2); + } + } + if ($raw === '' && isset($_GET['p'])) { + $raw = (string) $_GET['p']; + } + if ($raw === '') { + /* Forme chemin : /p/dl/ (directement sous la racine). */ + $path = trim((string) (parse_url((string) ($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH) ?: '/'), '/'); + if ($path !== '' && !str_contains($path, '.') && str_starts_with($path, 'p/')) { + $raw = substr($path, 2); + } + } + + $raw = strtolower(trim($raw)); + $raw = trim(preg_replace('/^\/+|\/+$/', '', $raw) ?? ''); + if ($raw === '' || $raw === 'home' || $raw === 'accueil' || $raw === 'index') { + return 'index'; + } + return $raw; +} + +$route = fws_site_current_route(); + +/* Résolution du corps de page : index, dl, paquets, paquets/N, equipe, contact. */ +$pageFile = null; +$detailId = 0; +if (preg_match('/^paquets\/(\d+)$/', $route, $m)) { + $detailId = max(1, (int) $m[1]); + $route = 'paquets/_detail'; + $pageFile = __DIR__ . '/p/paquets/detail.php'; +} else { + $known = ['index', 'dl', 'paquets', 'equipe', 'contact']; + if (in_array($route, $known, true)) { + $pageFile = __DIR__ . '/p/' . $route . '/index.php'; + } +} + +$is404 = $pageFile === null || !is_file($pageFile); + +/* Paquets : une seule lecture DB + cache Gitea pour toute la page + (le corps ET la nav déroulante les consomment). */ +$packages = fws_site_packages(); + +/* ───────────────────────── corps de page ───────────────────────── */ +/* Le corps est rendu d'abord : il peut définir $title, $description, + $canonical, $extraCss[] et $extraJs[] (données issues de la DB / API). */ + +/* NB : pas de null pour title/description — isset(null) est false et les + gardes des pages incluses (« isset($title, …) ») échoueraient. */ +$title = ''; +$description = ''; +$canonical = null; +$extraCss = []; +$extraJs = []; + +define('FWS_PAGE_SHELL', 1); /* les corps inclus peuvent vérifier qu'ils + ne sont pas exécutés en accès direct */ + +ob_start(); +if ($is404) { + http_response_code(404); + include __DIR__ . '/p/404.php'; +} else { + include $pageFile; +} +$body = ob_get_clean(); + +if ($title === null) { + $labels = [ + 'index' => 'Accueil', 'dl' => 'Téléchargements', 'paquets' => 'Paquets', + 'paquets/_detail' => 'Paquet', 'equipe' => "L'équipe", 'contact' => 'Contact', + ]; + $label = $labels[$route] ?? 'FWS Linux'; + $title = $label . ' | FWS Linux'; +} +if ($description === null) { + $description = 'FWS Linux — distribution open-source basée sur Arch Linux. Installation simplifiée, léger, respectueux de la vie privée, compatible Windows grâce à Wine et Winboat.'; +} +if ($canonical === null) { + $canonRoute = $route === 'paquets/_detail' ? 'paquets/' . $detailId : $route; + $canonical = 'https://fwslinux.fr/?p/' . ($canonRoute === 'index' ? 'index' : $canonRoute) . '/'; +} + +function fws_site_active(string $route, string $prefix): string +{ + return $route === $prefix || str_starts_with($route, $prefix . '/') + ? ' aria-current="page"' : ''; +} +?> + + + + + + <?= e($title) ?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + +
      + +
      + + +
      + + + + + + + +