Template
Feat(site): rendu serveur PHP — paquets en SQLite, releases Gitea, build ISO
- Front controller page.php + inc/site.php : coquille et pages rendues
en PHP (accueil, dl, paquets, paquets/N, equipe, contact, 404) ; les
URLs ne changent pas et l'apparence est conservée.
- Paquets stockés dans la base SQLite partagée (table packages),
éditables depuis l'onglet 📦 Paquets de /admin/bugs, avec bouton de
synchronisation des releases depuis l'API Gitea du dépôt lié.
Repli automatique sur packages.json si la base est vide.
- Releases ISO de la page Téléchargements récupérées côté serveur
(Gitea FWS/ISO sinon GitHub) avec cache fichier 10 min ; note de
release rendue en Markdown serveur (Voir plus / Voir moins).
- Suppression du routeur SPA et des chargeurs JS devenus inutiles
(app.js, packages.js, downloads.js, creators-loader.js, index.html) ;
restent nav.js, note-toggle.js et hero-carousel.js.
- Panneau admin : onglet Build ISO (git pull sur main, build.sh avec
repli setup-aur.sh, terminal des logs en direct), durcissement UTF-8
à l'écriture des paquets (json_encode ne casse plus sur des accents
mal encodés), 404 réels et gardes d'accès direct sur les corps PHP.
This commit is contained in:
1 parent
34b3f1cf3c
commit
1775adceaa
34 files changed
+2799
-1862
No files matched your search
+610
@@ -0,0 +1,610 @@
|
||||
<?php
|
||||
/**
|
||||
* FWS Linux — bibliothèque du site.
|
||||
*
|
||||
* Tout est rendu côté serveur (PHP) : les pages sont de vraies pages HTML.
|
||||
* Les données viennent de la base SQLite (paquets, modifiables dans
|
||||
* /admin/bugs) et des API Gitea / GitHub (releases, avec cache fichier).
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
define('FWS_SITE_ROOT', dirname(__DIR__));
|
||||
define('FWS_SITE_CACHE_DIR', FWS_SITE_ROOT . '/cache');
|
||||
define('FWS_SITE_CACHE_TTL', 600); // 10 minutes
|
||||
|
||||
/* ───────────────────────── utilitaires ───────────────────────── */
|
||||
|
||||
/** Échappement HTML. */
|
||||
function e(?string $s): string
|
||||
{
|
||||
return htmlspecialchars((string) $s, ENT_QUOTES, 'UTF-8');
|
||||
}
|
||||
|
||||
/* fws_utf8_str / fws_utf8_arr sont définies dans api/bugs/db.php (chargé
|
||||
ci-dessous via fws_site_db()) avec des gardes function_exists : elles
|
||||
sont donc disponibles quel que soit l'ordre d'inclusion. */
|
||||
|
||||
/** Date ISO → « 29 août 2026 » (ou la valeur brute si non parsable). */
|
||||
function fws_format_date(?string $iso): string
|
||||
{
|
||||
if ($iso === null || trim($iso) === '') {
|
||||
return '';
|
||||
}
|
||||
static $mois = [
|
||||
1 => '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', '<strong><em>$1</em></strong>', $t) ?? $t;
|
||||
$t = preg_replace('/\*\*(.+?)\*\*/s', '<strong>$1</strong>', $t) ?? $t;
|
||||
$t = preg_replace('/\*(.+?)\*/s', '<em>$1</em>', $t) ?? $t;
|
||||
$t = preg_replace('/`([^`]+)`/', '<code>$1</code>', $t) ?? $t;
|
||||
$t = preg_replace('/!\[([^\]]*)\]\(([^)\s]+)\)/', '<img alt="$1" src="$2" loading="lazy">', $t) ?? $t;
|
||||
$t = preg_replace('/\[([^\]]+)\]\(([^)\s]+)\)/', '<a href="$2" target="_blank" rel="noreferrer">$1</a>', $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 . '</' . $listKind . ">\n";
|
||||
$listBuf = '';
|
||||
$listKind = '';
|
||||
}
|
||||
};
|
||||
$flushTable = function () use (&$html, &$tableRows, &$tableHeader) {
|
||||
if ($tableRows !== []) {
|
||||
$html .= "<table>\n" . implode("\n", $tableRows) . "\n</table>\n";
|
||||
$tableRows = [];
|
||||
$tableHeader = true;
|
||||
}
|
||||
};
|
||||
$flushQuote = function () use (&$html, &$quoteBuf) {
|
||||
if ($quoteBuf !== '') {
|
||||
$html .= '<blockquote>' . $quoteBuf . "</blockquote>\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 .= '<pre><code' . $langAttr . '>' . fws_md_escape(trim($code)) . "</code></pre>\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 .= '<h' . $lvl . '>' . fws_md_inline($m[2]) . '</h' . $lvl . ">\n";
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^[-*_]{3,}\s*$/', trim($line))) {
|
||||
$flushAll();
|
||||
$html .= "<hr>\n";
|
||||
continue;
|
||||
}
|
||||
|
||||
if (strncmp(ltrim($line), '>', 1) === 0) {
|
||||
$flushList();
|
||||
$flushTable();
|
||||
$quoteBuf .= '<p>' . fws_md_inline((string) preg_replace('/^>\s?/', '', $line)) . '</p>';
|
||||
continue;
|
||||
}
|
||||
$flushQuote();
|
||||
|
||||
if (strpos($line, '|') !== false && !$isSep($line)) {
|
||||
$flushList();
|
||||
$tag = $tableHeader ? 'th' : 'td';
|
||||
$row = '<tr>';
|
||||
foreach ($cells($line) as $c) {
|
||||
$row .= '<' . $tag . '>' . fws_md_inline($c) . '</' . $tag . '>';
|
||||
}
|
||||
$row .= '</tr>';
|
||||
$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 .= '<li>' . fws_md_inline($m[2]) . "</li>\n";
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^(\s*)\d+\.\s+(.+)$/', $line, $m)) {
|
||||
$flushTable();
|
||||
if ($listKind !== 'ol') {
|
||||
$flushList();
|
||||
$listKind = 'ol';
|
||||
}
|
||||
$listBuf .= '<li>' . fws_md_inline($m[2]) . "</li>\n";
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($listBuf !== '' && preg_match('/^\s{2,}/', $line)) {
|
||||
$listBuf = (string) preg_replace('/<\/li>\n$/', ' ' . fws_md_inline(trim($line)) . "</li>\n", $listBuf);
|
||||
continue;
|
||||
}
|
||||
|
||||
$flushList();
|
||||
$flushTable();
|
||||
$html .= '<p>' . fws_md_inline($line) . "</p>\n";
|
||||
}
|
||||
|
||||
$flushAll();
|
||||
if ($inCode) {
|
||||
$langAttr = $codeLang !== '' ? ' class="language-' . e($codeLang) . '"' : '';
|
||||
$html .= '<pre><code' . $langAttr . '>' . fws_md_escape(trim($code)) . "</code></pre>\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 </p>, </div>…) 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 = '<p>' . e(mb_substr($text, 0, $limit)) . '…</p>';
|
||||
return ['html' => $out, 'truncated' => true];
|
||||
}
|
||||
return ['html' => $out, 'truncated' => true];
|
||||
}
|
||||
Reference in new issue
Block a user