5 Commits

Author SHA1 Message Date
cedricAbonnel d729e943a3 feat : graphique trafic global 14j (v1.6.27) 2026-05-19 19:33:46 +02:00
cedricAbonnel 868e68fa85 chore : version 1.6.27 2026-05-19 18:47:21 +02:00
cedricAbonnel ed3f8062da feat : sparklines 14j stats + filtre IPs LAN (v1.6.27)
- Admin stats : sparklines SVG par page (120×28 px, courbe + dégradé),
  carte « Pages les plus visitées » en pleine largeur
- AccessLogParser : données par jour (pages_by_day) sur 14 jours
- AccessLogParser : IPs privées/LAN exclues de la répartition réseau
- ArticleManager : suppression opérateur nullsafe superflu (PHPStan)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 18:20:19 +02:00
cedricAbonnel c2035314fb fix : chargement admin.js manquant dans l'onglet books
Le select « Ajouter une page » ne fonctionnait pas car admin.js
n'était pas chargé dans la section books du template.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 17:01:39 +02:00
cedricAbonnel c140ba4069 feat : page /books et section livres accueil (v1.6.26)
- #99 : page publique /books — catalogue des books avec ≥1 article publié
- #100 : section « Livres » sur la homepage (max 6, après redécouvertes)
- CSS : .book-grid, .book-home-card*, .home-section-more
- .htaccess : règle RewriteRule ^books/?$

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 16:53:23 +02:00
12 changed files with 393 additions and 74 deletions
+18
View File
@@ -5,6 +5,24 @@ Format : [Keep a Changelog](https://keepachangelog.com/fr/1.0.0/) — versionnag
--- ---
## [1.6.27] - 2026-05-19
### Ajouté
- Admin stats : sparklines SVG 14 jours par page dans « Pages les plus visitées » — courbe + dégradé, carte pleine largeur (#101)
### Corrigé
- Admin stats : IPs privées/LAN exclues de la répartition par réseau (Uptime Kuma et hairpin NAT ne polluent plus les stats) (#102)
---
## [1.6.26] - 2026-05-16
### Ajouté
- Page publique `/books` — catalogue de tous les livres avec ≥ 1 article publié, cards cover/titre/description/nombre de pages (#99)
- Accueil : section « Livres » (max 6) après les redécouvertes avec lien « Voir tous → /books » (#100)
---
## [1.6.25] - 2026-05-16 ## [1.6.25] - 2026-05-16
### Ajouté ### Ajouté
+3
View File
@@ -15,6 +15,9 @@ RewriteRule ^ - [L]
# URL propre pour les articles : /post/<slug> # URL propre pour les articles : /post/<slug>
RewriteRule ^post/([a-z0-9][a-z0-9-]*)/?$ /index.php?action=view&slug=$1 [L,QSA] RewriteRule ^post/([a-z0-9][a-z0-9-]*)/?$ /index.php?action=view&slug=$1 [L,QSA]
# Catalogue de tous les livres : /books
RewriteRule ^books/?$ /index.php?action=books_list [L,QSA]
# Livres : /book/<slug> # Livres : /book/<slug>
RewriteRule ^book/([a-z0-9][a-z0-9-]*)/?$ /index.php?action=book&book_slug=$1 [L,QSA] RewriteRule ^book/([a-z0-9][a-z0-9-]*)/?$ /index.php?action=book&book_slug=$1 [L,QSA]
+62
View File
@@ -1844,6 +1844,68 @@ main { transition: max-width .22s ease; }
/* ─── Livres ─────────────────────────────────────────────────────── */ /* ─── Livres ─────────────────────────────────────────────────────── */
/* Grille catalogue /books + section accueil */
.book-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
gap: 1rem;
}
.book-home-card {
display: flex;
flex-direction: column;
border-radius: var(--vl-radius);
overflow: hidden;
text-decoration: none;
color: inherit;
background: var(--vl-card-bg, var(--bs-body-bg));
box-shadow: var(--vl-shadow-sm, 0 1px 3px rgba(0,0,0,.08));
transition: transform .15s, box-shadow .15s;
}
.book-home-card:hover {
transform: translateY(-2px);
box-shadow: var(--vl-shadow-md, 0 4px 12px rgba(0,0,0,.14));
color: inherit;
}
.book-home-card-cover {
height: 120px;
background-size: cover;
background-position: center;
flex-shrink: 0;
}
.book-home-card-body {
padding: .7rem;
display: flex;
flex-direction: column;
gap: .2rem;
flex: 1;
}
.book-home-card-title {
font-weight: 600;
font-size: .9rem;
line-height: 1.3;
}
.book-home-card-desc {
font-size: .78rem;
color: var(--vl-muted);
line-height: 1.4;
}
.book-home-card-meta {
font-size: .72rem;
color: var(--vl-muted);
margin-top: auto;
padding-top: .3rem;
}
.home-section-more {
font-size: .75rem;
font-weight: 400;
margin-left: .5rem;
color: var(--vl-accent);
text-decoration: none;
letter-spacing: 0;
text-transform: none;
}
.home-section-more:hover { text-decoration: underline; }
/* Bandeau dans un article appartenant à un livre */ /* Bandeau dans un article appartenant à un livre */
.book-article-banner { .book-article-banner {
border-radius: var(--vl-radius); border-radius: var(--vl-radius);
+89 -13
View File
@@ -17,16 +17,80 @@
}); });
}()); }());
// ── Pages les plus visitées (RSS XML) ──────────────────────────────────────── // ── Pages les plus visitées (RSS XML + sparklines) ───────────────────────────
(function () { (function () {
var container = document.getElementById('stats-pages-container'); var container = document.getElementById('stats-pages-container');
var badge = document.getElementById('stats-pages-count'); var badge = document.getElementById('stats-pages-count');
var pagesByDay = (typeof FOLIO_PAGES_BY_DAY !== 'undefined') ? FOLIO_PAGES_BY_DAY : {};
if (!container) { return; } if (!container) { return; }
function esc(s) { function esc(s) {
return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
} }
function sparkline(data) {
var W = 120, H = 28, padX = 2, padY = 3;
var max = Math.max.apply(null, data) || 1;
var n = data.length;
var pts = data.map(function (v, i) {
var x = padX + i * (W - 2 * padX) / (n - 1);
var y = H - padY - (v / max) * (H - 2 * padY);
return x.toFixed(1) + ',' + y.toFixed(1);
}).join(' ');
// Zone remplie sous la courbe
var first = padX.toFixed(1) + ',' + (H - padY).toFixed(1);
var last = (W - padX).toFixed(1) + ',' + (H - padY).toFixed(1);
return '<svg xmlns="http://www.w3.org/2000/svg" width="' + W + '" height="' + H + '" style="display:block;overflow:visible">'
+ '<defs><linearGradient id="spk-grad" x1="0" y1="0" x2="0" y2="1">'
+ '<stop offset="0%" stop-color="var(--bs-primary,#0d6efd)" stop-opacity="0.18"/>'
+ '<stop offset="100%" stop-color="var(--bs-primary,#0d6efd)" stop-opacity="0"/>'
+ '</linearGradient></defs>'
+ '<polygon points="' + first + ' ' + pts + ' ' + last + '" fill="url(#spk-grad)"/>'
+ '<polyline points="' + pts + '" fill="none" stroke="var(--bs-primary,#0d6efd)" stroke-width="1.5" stroke-linejoin="round" stroke-linecap="round"/>'
+ '</svg>';
}
function trendChart(totals) {
var trendEl = document.getElementById('stats-trend-container');
if (!trendEl || !totals.length) { return; }
var days = totals.length;
var maxV = Math.max.apply(null, totals) || 1;
var W = 1000; // viewBox, s'adapte en CSS
var H = 80;
var padX = 4;
var padY = 8;
var barW = Math.floor((W - 2 * padX) / days) - 2;
// Dates des jours (index 0 = il y a 13 jours)
var now = new Date();
var labels = totals.map(function (_, i) {
var d = new Date(now);
d.setDate(d.getDate() - (days - 1 - i));
return d.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' });
});
var bars = totals.map(function (v, i) {
var x = padX + i * (W - 2 * padX) / days + 1;
var bh = Math.max(2, (v / maxV) * (H - padY - 16));
var y = H - padY - bh;
var lx = x + barW / 2;
var label = labels[i];
var showLabel = (i === 0 || i === days - 1 || i === Math.floor(days / 2));
return '<rect x="' + x.toFixed(1) + '" y="' + y.toFixed(1) + '" width="' + barW + '" height="' + bh.toFixed(1) + '"'
+ ' fill="var(--bs-primary,#0d6efd)" opacity="0.75" rx="2"/>'
+ '<title>' + label + ' : ' + v + ' vis.</title>'
+ (showLabel
? '<text x="' + lx.toFixed(1) + '" y="' + (H - 1) + '" text-anchor="middle"'
+ ' font-size="10" fill="var(--bs-secondary-color,#6c757d)">' + label + '</text>'
: '');
}).join('');
trendEl.innerHTML = '<p class="small text-muted mb-2 fw-semibold">Trafic total — 14 derniers jours</p>'
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ' + W + ' ' + H + '"'
+ ' style="width:100%;height:80px;display:block">' + bars + '</svg>';
}
fetch('/trending?period=14d') fetch('/trending?period=14d')
.then(function (r) { return r.ok ? r.text() : Promise.reject(); }) .then(function (r) { return r.ok ? r.text() : Promise.reject(); })
.then(function (xml) { .then(function (xml) {
@@ -43,19 +107,31 @@
var vis = m ? parseInt(m[1], 10) : 0; var vis = m ? parseInt(m[1], 10) : 0;
var title = raw.replace(/\s*\(\d+\s+visiteurs?\)$/, ''); var title = raw.replace(/\s*\(\d+\s+visiteurs?\)$/, '');
var slug = decodeURIComponent(link.replace(/.*\/post\//, '')); var slug = decodeURIComponent(link.replace(/.*\/post\//, ''));
return { title: title, link: link, slug: slug, vis: vis }; var pm = link.match(/\/post\/[^?#]*/);
var daily = pm ? (pagesByDay[pm[0]] || null) : null;
return { title: title, link: link, slug: slug, vis: vis, daily: daily };
}); });
var maxV = Math.max.apply(null, rows.map(function (r) { return r.vis; })) || 1;
var html = '<div class="table-responsive"><table class="table table-sm table-hover mb-0 small"><tbody>'; // Graphique global : somme de tous les articles par jour
var nDays = 14;
var totals = new Array(nDays).fill(0);
Object.values(pagesByDay).forEach(function (arr) {
arr.forEach(function (v, i) { if (i < nDays) { totals[i] += v; } });
});
trendChart(totals);
var html = '<div class="table-responsive"><table class="table table-sm table-hover mb-0 small w-100"><tbody>';
rows.forEach(function (row, i) { rows.forEach(function (row, i) {
var pct = Math.round(row.vis / maxV * 100); var vis = row.vis.toLocaleString('fr-FR');
var vis = row.vis.toLocaleString('fr-FR'); var spk = row.daily ? sparkline(row.daily) : '';
html += '<tr>' html += '<tr>'
+ '<td class="text-muted ps-3" style="width:2rem">' + (i + 1) + '</td>' + '<td class="text-muted ps-3" style="width:2rem;vertical-align:middle">' + (i + 1) + '</td>'
+ '<td><a href="' + esc(row.link) + '" target="_blank" class="text-decoration-none text-truncate d-block" style="max-width:260px" title="' + esc(row.slug) + '">' + '<td style="vertical-align:middle"><a href="' + esc(row.link) + '" target="_blank"'
+ esc(row.title || row.slug) + '</a>' + ' class="text-decoration-none" title="' + esc(row.slug) + '">'
+ '<div class="progress mt-1" style="height:3px"><div class="progress-bar" style="width:' + pct + '%"></div></div></td>' + esc(row.title || row.slug) + '</a></td>'
+ '<td class="text-end fw-semibold pe-3">' + vis + ' <span class="text-muted fw-normal">vis.</span></td>' + '<td style="width:130px;vertical-align:middle;padding:4px 8px">' + spk + '</td>'
+ '<td class="text-end fw-semibold pe-3" style="width:5rem;vertical-align:middle">'
+ vis + ' <span class="text-muted fw-normal">vis.</span></td>'
+ '</tr>'; + '</tr>';
}); });
html += '</tbody></table></div>'; html += '</tbody></table></div>';
+70 -16
View File
@@ -73,7 +73,9 @@ function buildAutoSeoDesc(string $content, string $title = ''): string
{ {
require_once BASE_PATH . '/src/Parsedown.php'; require_once BASE_PATH . '/src/Parsedown.php';
$_pd = new Parsedown(); $_pd = new Parsedown();
$_plain = trim((string)preg_replace('/\s+/', ' ', $_plain = trim((string)preg_replace(
'/\s+/',
' ',
html_entity_decode(strip_tags($_pd->text($content)), ENT_QUOTES | ENT_HTML5, 'UTF-8') html_entity_decode(strip_tags($_pd->text($content)), ENT_QUOTES | ENT_HTML5, 'UTF-8')
)); ));
if ($title !== '' && stripos($_plain, $title) === 0) { if ($title !== '' && stripos($_plain, $title) === 0) {
@@ -85,7 +87,9 @@ function buildAutoSeoDesc(string $content, string $title = ''): string
function slugToSearchQuery(string $rawPath): string function slugToSearchQuery(string $rawPath): string
{ {
return trim((string)preg_replace('/\s{2,}/', ' ', (string)preg_replace( return trim((string)preg_replace('/\s{2,}/', ' ', (string)preg_replace(
'/[^a-zA-ZÀ-ÿ0-9\s]/u', ' ', str_replace(['-', '_', '/'], ' ', $rawPath) '/[^a-zA-ZÀ-ÿ0-9\s]/u',
' ',
str_replace(['-', '_', '/'], ' ', $rawPath)
))); )));
} }
@@ -2512,7 +2516,7 @@ switch ($action) {
$allArticles = array_values(array_filter($allArticles, fn ($a) => !empty($a['featured']))); $allArticles = array_values(array_filter($allArticles, fn ($a) => !empty($a['featured'])));
} }
$sortBy = in_array($_GET['sort'] ?? '', ['title', 'published', 'updated']) ? $_GET['sort'] : 'updated'; $sortBy = in_array($_GET['sort'] ?? '', ['title', 'published', 'updated'], true) ? $_GET['sort'] : 'updated';
$sortDir = ($_GET['dir'] ?? '') === 'asc' ? 'asc' : 'desc'; $sortDir = ($_GET['dir'] ?? '') === 'asc' ? 'asc' : 'desc';
usort($allArticles, function ($a, $b) use ($sortBy, $sortDir) { usort($allArticles, function ($a, $b) use ($sortBy, $sortDir) {
$cmp = match ($sortBy) { $cmp = match ($sortBy) {
@@ -2730,21 +2734,24 @@ switch ($action) {
$cutoff14 = strtotime('-14 days midnight') ?: (time() - 14 * 86400); $cutoff14 = strtotime('-14 days midnight') ?: (time() - 14 * 86400);
$tParser = new TrendingParser('/var/log/apache2', apacheAccessLog()); $tParser = new TrendingParser('/var/log/apache2', apacheAccessLog());
$accessParser = new AccessLogParser('/var/log/apache2', apacheAccessLog()); $accessParser = new AccessLogParser('/var/log/apache2', apacheAccessLog());
$topIps = array_slice($accessParser->stats()['ips'], 0, 200, true); $accessStats = $accessParser->stats();
$topIps = array_slice($accessStats['ips'], 0, 200, true);
$asnMap = (new AsnLookup())->batchLookup(array_keys($topIps)); $asnMap = (new AsnLookup())->batchLookup(array_keys($topIps));
$statsRaw = [ $statsRaw = [
'readable' => $accessParser->isReadable(), 'readable' => $accessParser->isReadable(),
'books' => $tParser->top($cutoff14, 20, ['/book/']), 'books' => $tParser->top($cutoff14, 20, ['/book/']),
'as' => AsnLookup::aggregateByAs($topIps, $asnMap), 'as' => AsnLookup::aggregateByAs($topIps, $asnMap),
'pages_by_day' => $accessStats['pages_by_day'] ?? [],
]; ];
@file_put_contents($statsCacheFile, json_encode($statsRaw)); @file_put_contents($statsCacheFile, json_encode($statsRaw));
} }
$adminData['stats_readable'] = $statsRaw['readable']; $adminData['stats_readable'] = $statsRaw['readable'];
$adminData['stats_books'] = $statsRaw['books']; $adminData['stats_books'] = $statsRaw['books'];
$adminData['stats_as'] = $statsRaw['as']; $adminData['stats_as'] = $statsRaw['as'];
$adminData['stats_as_groups'] = AsnLookup::applyGroups($statsRaw['as'], asGroups()); $adminData['stats_as_groups'] = AsnLookup::applyGroups($statsRaw['as'], asGroups());
$adminData['as_groups'] = asGroups(); $adminData['as_groups'] = asGroups();
$adminData['stats_pages_by_day'] = $statsRaw['pages_by_day'] ?? [];
} }
if ($tab === 'categories') { if ($tab === 'categories') {
@@ -2764,7 +2771,8 @@ switch ($action) {
try { try {
$st = $pdo->query('SELECT id, user_email, feed_url, label, created_at FROM rss_feeds ORDER BY created_at DESC'); $st = $pdo->query('SELECT id, user_email, feed_url, label, created_at FROM rss_feeds ORDER BY created_at DESC');
$adminData['flux_feeds'] = $st->fetchAll(PDO::FETCH_ASSOC); $adminData['flux_feeds'] = $st->fetchAll(PDO::FETCH_ASSOC);
} catch (\Throwable) {} } catch (\Throwable) {
}
} }
} }
@@ -2784,7 +2792,10 @@ switch ($action) {
} }
if ($tab === 'ia') { if ($tab === 'ia') {
if (!isAdmin()) { http_response_code(403); exit; } if (!isAdmin()) {
http_response_code(403);
exit;
}
require_once BASE_PATH . '/src/SiteSettings.php'; require_once BASE_PATH . '/src/SiteSettings.php';
require_once BASE_PATH . '/src/Service/AiService.php'; require_once BASE_PATH . '/src/Service/AiService.php';
$adminData['ai_provider'] = aiProvider(); $adminData['ai_provider'] = aiProvider();
@@ -2800,7 +2811,8 @@ switch ($action) {
case 'admin_save_ai_config': case 'admin_save_ai_config':
requireAuth(); requireAuth();
if (!isAdmin() || $_SERVER['REQUEST_METHOD'] !== 'POST') { if (!isAdmin() || $_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(403); exit; http_response_code(403);
exit;
} }
require_once BASE_PATH . '/src/SiteSettings.php'; require_once BASE_PATH . '/src/SiteSettings.php';
$allowedProviders = ['anthropic', 'claude_code']; $allowedProviders = ['anthropic', 'claude_code'];
@@ -3439,7 +3451,8 @@ switch ($action) {
if ($pdo) { if ($pdo) {
try { try {
$pdo->prepare('DELETE FROM rss_feeds WHERE id = :id')->execute([':id' => $feedId]); $pdo->prepare('DELETE FROM rss_feeds WHERE id = :id')->execute([':id' => $feedId]);
} catch (\Throwable) {} } catch (\Throwable) {
}
} }
} }
header('Location: /admin/flux?deleted=1'); header('Location: /admin/flux?deleted=1');
@@ -3530,6 +3543,27 @@ switch ($action) {
include BASE_PATH . '/templates/search.php'; include BASE_PATH . '/templates/search.php';
break; break;
case 'books_list':
$allCats = $articles->getCategories();
$booksData = [];
foreach ($books->getAll() as $_bk) {
$_published = [];
foreach ($_bk['articles'] ?? [] as $_aSlug) {
$_a = $articles->getBySlug($_aSlug);
if ($_a && $_a['published'] && strtotime((string)($_a['published_at'] ?? '')) <= time()) {
$_published[] = $_a;
}
}
if (empty($_published)) {
continue;
}
$booksData[] = ['book' => $_bk, 'count' => count($_published), 'first' => $_published[0]];
}
unset($_bk, $_published, $_aSlug, $_a);
$seoDescription = 'Retrouvez tous les livres et séries d\'articles publiés sur ' . siteTitle() . '.';
include BASE_PATH . '/templates/books_list.php';
break;
case 'book': case 'book':
$bookSlug = trim($_GET['book_slug'] ?? ''); $bookSlug = trim($_GET['book_slug'] ?? '');
$book = $books->getBySlug($bookSlug); $book = $books->getBySlug($bookSlug);
@@ -3834,6 +3868,26 @@ switch ($action) {
$recentlyUpdated[] = $_a; $recentlyUpdated[] = $_a;
} }
unset($_sevenDaysAgo, $_latestUuids, $_popularUuids, $_heroUuid, $_a, $allPostsMap); unset($_sevenDaysAgo, $_latestUuids, $_popularUuids, $_heroUuid, $_a, $allPostsMap);
// Books à mettre en avant (max 6, ayant ≥ 1 article publié)
$homeBooks = [];
foreach ($books->getAll() as $_bk) {
$_published = [];
foreach ($_bk['articles'] ?? [] as $_aSlug) {
$_a = $articles->getBySlug($_aSlug);
if ($_a && $_a['published'] && strtotime((string)($_a['published_at'] ?? '')) <= time()) {
$_published[] = $_a;
}
}
if (empty($_published)) {
continue;
}
$homeBooks[] = ['book' => $_bk, 'count' => count($_published), 'first' => $_published[0]];
if (count($homeBooks) >= 6) {
break;
}
}
unset($_bk, $_published, $_aSlug, $_a);
} }
// ────────────────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────────────────
+1 -1
View File
@@ -1 +1 @@
1.6.25 1.6.27
+38 -15
View File
@@ -30,7 +30,7 @@ class AccessLogParser
} }
/** /**
* @return array{pages:array<string,int>,books:array<string,int>,ips:array<string,int>} * @return array{pages:array<string,int>,books:array<string,int>,ips:array<string,int>,pages_by_day:array<string,list<int>>}
*/ */
public function stats(): array public function stats(): array
{ {
@@ -44,20 +44,34 @@ class AccessLogParser
} }
} }
$cutoff = strtotime("-{$this->days} days midnight") ?: (time() - $this->days * 86400); $cutoff = strtotime("-{$this->days} days midnight") ?: (time() - $this->days * 86400);
$pages = []; $pages = [];
$books = []; $books = [];
$ips = []; $ips = [];
$dayPages = []; // [path => [dayOffset => count]], dayOffset 0=oldest
foreach ($this->logFiles() as $file) { foreach ($this->logFiles() as $file) {
$this->parseFile($file, $cutoff, $pages, $books, $ips); $this->parseFile($file, $cutoff, $pages, $books, $ips, $dayPages);
} }
arsort($pages); arsort($pages);
arsort($books); arsort($books);
arsort($ips); arsort($ips);
$result = compact('pages', 'books', 'ips'); // Normalise dayPages : pour chaque page, tableau de $this->days entiers (index 0 = le plus ancien)
$pagesByDay = [];
$today = (int) strtotime('today midnight');
foreach ($dayPages as $path => $byOffset) {
$arr = array_fill(0, $this->days, 0);
foreach ($byOffset as $offset => $count) {
if ($offset >= 0 && $offset < $this->days) {
$arr[$offset] = $count;
}
}
$pagesByDay[$path] = $arr;
}
$result = ['pages' => $pages, 'books' => $books, 'ips' => $ips, 'pages_by_day' => $pagesByDay];
@mkdir(dirname($this->cacheFile), 0755, true); @mkdir(dirname($this->cacheFile), 0755, true);
@file_put_contents($this->cacheFile, json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); @file_put_contents($this->cacheFile, json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
return self::$memo = $result; return self::$memo = $result;
@@ -113,7 +127,7 @@ class AccessLogParser
return (int) strtotime("{$m[1]} {$m[2]} {$m[3]} {$m[4]} {$m[5]}"); return (int) strtotime("{$m[1]} {$m[2]} {$m[3]} {$m[4]} {$m[5]}");
} }
private function parseLine(string $line, int $cutoff, array &$pages, array &$books, array &$ips): void private function parseLine(string $line, int $cutoff, array &$pages, array &$books, array &$ips, array &$dayPages): void
{ {
if (!preg_match(self::RE, $line, $m)) { if (!preg_match(self::RE, $line, $m)) {
return; return;
@@ -123,20 +137,29 @@ class AccessLogParser
if ($status !== '200') { if ($status !== '200') {
return; return;
} }
if (self::parseTimestamp($ts) < $cutoff) { $tsVal = self::parseTimestamp($ts);
if ($tsVal < $cutoff) {
return; return;
} }
$publicIp = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false;
if (str_starts_with($path, '/post/') && strlen($path) > 6) { if (str_starts_with($path, '/post/') && strlen($path) > 6) {
$pages[$path] = ($pages[$path] ?? 0) + 1; $pages[$path] = ($pages[$path] ?? 0) + 1;
$ips[$ip] = ($ips[$ip] ?? 0) + 1; if ($publicIp) {
$ips[$ip] = ($ips[$ip] ?? 0) + 1;
}
$dayOffset = (int) floor(($tsVal - $cutoff) / 86400);
$dayPages[$path][$dayOffset] = ($dayPages[$path][$dayOffset] ?? 0) + 1;
} elseif (str_starts_with($path, '/book/') && strlen($path) > 6) { } elseif (str_starts_with($path, '/book/') && strlen($path) > 6) {
$books[$path] = ($books[$path] ?? 0) + 1; $books[$path] = ($books[$path] ?? 0) + 1;
$ips[$ip] = ($ips[$ip] ?? 0) + 1; if ($publicIp) {
$ips[$ip] = ($ips[$ip] ?? 0) + 1;
}
} }
} }
private function parseFile(array $file, int $cutoff, array &$pages, array &$books, array &$ips): void private function parseFile(array $file, int $cutoff, array &$pages, array &$books, array &$ips, array &$dayPages): void
{ {
if ($file['type'] === 'tgz') { if ($file['type'] === 'tgz') {
try { try {
@@ -147,7 +170,7 @@ class AccessLogParser
continue; continue;
} }
foreach (explode("\n", $content) as $line) { foreach (explode("\n", $content) as $line) {
$this->parseLine($line, $cutoff, $pages, $books, $ips); $this->parseLine($line, $cutoff, $pages, $books, $ips, $dayPages);
} }
} }
} catch (\Exception $e) { } catch (\Exception $e) {
@@ -160,7 +183,7 @@ class AccessLogParser
while (!gzeof($h)) { while (!gzeof($h)) {
$line = gzgets($h, 8192); $line = gzgets($h, 8192);
if ($line !== false) { if ($line !== false) {
$this->parseLine($line, $cutoff, $pages, $books, $ips); $this->parseLine($line, $cutoff, $pages, $books, $ips, $dayPages);
} }
} }
gzclose($h); gzclose($h);
@@ -170,7 +193,7 @@ class AccessLogParser
return; return;
} }
while (($line = fgets($h)) !== false) { while (($line = fgets($h)) !== false) {
$this->parseLine($line, $cutoff, $pages, $books, $ips); $this->parseLine($line, $cutoff, $pages, $books, $ips, $dayPages);
} }
fclose($h); fclose($h);
} }
+7 -7
View File
@@ -293,7 +293,7 @@ class ArticleManager
} }
$meta['updated_at'] = date('Y-m-d H:i:s'); $meta['updated_at'] = date('Y-m-d H:i:s');
$this->writeMeta($dir, $meta); $this->writeMeta($dir, $meta);
$this->git?->commit("meta: " . ($meta['title'] ?? $uuid)); $this->git?->commit('meta: ' . ($meta['title'] ?? $uuid));
} }
public function saveDraftOverlay(string $uuid, array $metaFields, ?string $content = null): void public function saveDraftOverlay(string $uuid, array $metaFields, ?string $content = null): void
@@ -379,7 +379,7 @@ class ArticleManager
@unlink($dir . '/draft_overlay.json'); @unlink($dir . '/draft_overlay.json');
@unlink($dir . '/draft_overlay.md'); @unlink($dir . '/draft_overlay.md');
if ($title !== null) { if ($title !== null) {
$this->git?->commit("discard-draft: $title"); $this->git->commit("discard-draft: $title");
} }
} }
@@ -488,7 +488,7 @@ class ArticleManager
} }
$meta['cover'] = $coverName; $meta['cover'] = $coverName;
$this->writeMeta($this->dataDir . '/' . $uuid, $meta); $this->writeMeta($this->dataDir . '/' . $uuid, $meta);
$this->git?->commit("cover: " . ($article['title'] ?? $uuid)); $this->git?->commit('cover: ' . ($article['title'] ?? $uuid));
} }
public function addFileFromUrl(string $uuid, string $url, bool $isCover = false, string $author = '', string $sourceUrl = '', string $title = '', array $extraMeta = []): ?string public function addFileFromUrl(string $uuid, string $url, bool $isCover = false, string $author = '', string $sourceUrl = '', string $title = '', array $extraMeta = []): ?string
@@ -775,7 +775,7 @@ class ArticleManager
$this->tagTypesPath(), $this->tagTypesPath(),
json_encode($types, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n" json_encode($types, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n"
); );
$this->git?->commit("tag-types"); $this->git?->commit('tag-types');
} }
/** Enregistre les tags d'un article directement (utile pour les scripts de migration). */ /** Enregistre les tags d'un article directement (utile pour les scripts de migration). */
@@ -795,7 +795,7 @@ class ArticleManager
$meta['tags'] = $this->normalizeTags($tags); $meta['tags'] = $this->normalizeTags($tags);
$this->writeMeta($dir, $meta); $this->writeMeta($dir, $meta);
$this->rebuildSearchIndex(); $this->rebuildSearchIndex();
$this->git?->commit("tags: " . ($meta['title'] ?? $uuid)); $this->git?->commit('tags: ' . ($meta['title'] ?? $uuid));
} }
/** @return list<string> Toutes les valeurs distinctes d'un type de tag, triées. */ /** @return list<string> Toutes les valeurs distinctes d'un type de tag, triées. */
@@ -845,7 +845,7 @@ class ArticleManager
$this->writeMeta($dir, $meta); $this->writeMeta($dir, $meta);
$this->allCache = null; $this->allCache = null;
@unlink($this->articleCachePath($uuid)); @unlink($this->articleCachePath($uuid));
$this->git?->commit("featured: " . ($meta['title'] ?? $uuid) . " (" . ($featured ? 'on' : 'off') . ")"); $this->git?->commit('featured: ' . ($meta['title'] ?? $uuid) . ' (' . ($featured ? 'on' : 'off') . ')');
} }
public function delete(string $uuid): bool public function delete(string $uuid): bool
@@ -871,7 +871,7 @@ class ArticleManager
} }
$this->rebuildSearchIndex(); $this->rebuildSearchIndex();
$this->rebuildBacklinksCache(); $this->rebuildBacklinksCache();
$this->git?->commit("delete: " . ($title ?? $uuid)); $this->git?->commit('delete: ' . ($title ?? $uuid));
return true; return true;
} }
+1
View File
@@ -1487,6 +1487,7 @@ foreach (COLOR_PALETTE_16 as $_i => $_rgb):
</div> </div>
</div> </div>
<script src="/assets/js/admin.js" defer></script>
<?php endif; ?> <?php endif; ?>
+23 -22
View File
@@ -1,11 +1,12 @@
<?php <?php
$_statsSaved = isset($_GET['saved']); $_statsSaved = isset($_GET['saved']);
$_statsError = ($_GET['error'] ?? '') === 'write'; $_statsError = ($_GET['error'] ?? '') === 'write';
$_readable = $adminData['stats_readable'] ?? false; $_readable = $adminData['stats_readable'] ?? false;
$_books = $adminData['stats_books'] ?? []; $_books = $adminData['stats_books'] ?? [];
$_asList = $adminData['stats_as'] ?? []; $_asList = $adminData['stats_as'] ?? [];
$_asGroups = $adminData['stats_as_groups'] ?? []; $_asGroups = $adminData['stats_as_groups'] ?? [];
$_groups = $adminData['as_groups'] ?? []; $_groups = $adminData['as_groups'] ?? [];
$_pagesByDay = $adminData['stats_pages_by_day'] ?? [];
$_activeGroup = trim($_GET['group'] ?? ''); $_activeGroup = trim($_GET['group'] ?? '');
?> ?>
@@ -24,20 +25,20 @@ $_activeGroup = trim($_GET['group'] ?? '');
<p class="text-muted small mb-4">14 derniers jours · visiteurs uniques · flux RSS XML</p> <p class="text-muted small mb-4">14 derniers jours · visiteurs uniques · flux RSS XML</p>
<div class="row g-4"> <script>var FOLIO_PAGES_BY_DAY = <?= json_encode($_pagesByDay, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>;</script>
<!-- Pages (chargées via le flux RSS XML /trending?period=14d) --> <div class="card mb-4">
<div class="col-lg-6"> <div class="card-header bg-transparent py-2 small fw-semibold d-flex justify-content-between">
<div class="card h-100"> <span>Pages les plus visitées</span>
<div class="card-header bg-transparent py-2 small fw-semibold d-flex justify-content-between"> <span class="text-muted" id="stats-pages-count"></span>
<span>Pages les plus visitées</span>
<span class="text-muted" id="stats-pages-count"></span>
</div>
<div class="card-body p-0" id="stats-pages-container">
<p class="text-muted p-3 mb-0">Chargement…</p>
</div>
</div>
</div> </div>
<div class="card-body p-0" id="stats-pages-container">
<p class="text-muted p-3 mb-0">Chargement…</p>
</div>
<div class="card-footer bg-transparent border-top px-3 pt-3 pb-2" id="stats-trend-container"></div>
</div>
<div class="row g-4">
<!-- Livres --> <!-- Livres -->
<div class="col-lg-6"> <div class="col-lg-6">
@@ -60,7 +61,7 @@ $_activeGroup = trim($_GET['group'] ?? '');
$rankB++; $rankB++;
$slug = rawurldecode(substr($url, 6)); $slug = rawurldecode(substr($url, 6));
$pct = round($hits / $maxB * 100); $pct = round($hits / $maxB * 100);
?> ?>
<tr> <tr>
<td class="text-muted ps-3" style="width:2rem"><?= $rankB ?></td> <td class="text-muted ps-3" style="width:2rem"><?= $rankB ?></td>
<td> <td>
@@ -112,7 +113,7 @@ $_activeGroup = trim($_GET['group'] ?? '');
} else { } else {
$displayAs = $_asList; $displayAs = $_asList;
} }
?> ?>
<?php if (empty($displayAs)): ?> <?php if (empty($displayAs)): ?>
<p class="text-muted p-3 mb-0"> <p class="text-muted p-3 mb-0">
<?= empty($_asList) ? 'Aucune IP résolue (LAN ou logs vides).' : 'Aucun AS dans ce groupe.' ?> <?= empty($_asList) ? 'Aucune IP résolue (LAN ou logs vides).' : 'Aucun AS dans ce groupe.' ?>
@@ -153,7 +154,7 @@ $_activeGroup = trim($_GET['group'] ?? '');
</div> </div>
</div> </div>
<?php endif; // readable ?> <?php endif; // readable?>
<!-- Groupes de réseaux --> <!-- Groupes de réseaux -->
<div class="card mt-4" style="max-width:600px"> <div class="card mt-4" style="max-width:600px">
+49
View File
@@ -0,0 +1,49 @@
<?php
ob_start();
?>
<div class="container py-4">
<div class="d-flex align-items-baseline justify-content-between mb-4">
<h1 class="h3 mb-0">Livres</h1>
<span class="text-muted small"><?= count($booksData) ?> livre<?= count($booksData) > 1 ? 's' : '' ?></span>
</div>
<?php if (empty($booksData)): ?>
<p class="text-muted">Aucun livre disponible pour l'instant.</p>
<?php else: ?>
<div class="book-grid">
<?php foreach ($booksData as $_bd):
$_book = $_bd['book'];
$_first = $_bd['first'];
$_count = $_bd['count'];
$_cover = $_first['cover'] ?? '';
$_cat = trim($_first['category'] ?? '');
$_coverStyle = $_cover !== ''
? "background-image:url('/file?uuid=" . rawurlencode($_first['uuid']) . "&name=" . rawurlencode($_cover) . "')"
: 'background:' . coverGradient($_cat !== '' ? $_cat : $_first['uuid'], $allCats ?? []);
?>
<a href="/book/<?= rawurlencode($_book['slug']) ?>" class="book-home-card">
<div class="book-home-card-cover" style="<?= $_coverStyle ?>"></div>
<div class="book-home-card-body">
<div class="book-home-card-title"><?= htmlspecialchars($_book['title']) ?></div>
<?php if (!empty($_book['description'])): ?>
<div class="book-home-card-desc"><?= htmlspecialchars(mb_strimwidth($_book['description'], 0, 100, '…')) ?></div>
<?php endif; ?>
<div class="book-home-card-meta"><?= $_count ?> page<?= $_count > 1 ? 's' : '' ?></div>
</div>
</a>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<?php
$content = ob_get_clean();
$title = 'Livres — ' . siteTitle();
$metaRobots = 'index, follow';
$canonical = rtrim((string)($_ENV['APP_URL'] ?? getenv('APP_URL') ?: ''), '/') . '/books';
include BASE_PATH . '/templates/layout.php';
+32
View File
@@ -214,6 +214,38 @@ function _renderCard(array $post, array $privateCats, array $allCats, \Parsedown
</section> </section>
<?php endif; ?> <?php endif; ?>
<?php if (!empty($homeBooks ?? [])): ?>
<section class="home-section">
<h2 class="home-section-title">
Livres
<a href="/books" class="home-section-more">Voir tous </a>
</h2>
<div class="book-grid">
<?php foreach ($homeBooks as $_hb):
$_book = $_hb['book'];
$_first = $_hb['first'];
$_count = $_hb['count'];
$_cover = $_first['cover'] ?? '';
$_cat = trim($_first['category'] ?? '');
$_coverStyle = $_cover !== ''
? "background-image:url('/file?uuid=" . rawurlencode($_first['uuid']) . "&name=" . rawurlencode($_cover) . "')"
: 'background:' . coverGradient($_cat !== '' ? $_cat : $_first['uuid'], $allCats ?? []);
?>
<a href="/book/<?= rawurlencode($_book['slug']) ?>" class="book-home-card">
<div class="book-home-card-cover" style="<?= $_coverStyle ?>"></div>
<div class="book-home-card-body">
<div class="book-home-card-title"><?= htmlspecialchars($_book['title']) ?></div>
<?php if (!empty($_book['description'])): ?>
<div class="book-home-card-desc"><?= htmlspecialchars(mb_strimwidth($_book['description'], 0, 80, '…')) ?></div>
<?php endif; ?>
<div class="book-home-card-meta"><?= $_count ?> page<?= $_count > 1 ? 's' : '' ?></div>
</div>
</a>
<?php endforeach; ?>
</div>
</section>
<?php endif; ?>
<?php else: /* ─── VUE PAGINÉE / FILTRÉE ─────────────────────────────── */ ?> <?php else: /* ─── VUE PAGINÉE / FILTRÉE ─────────────────────────────── */ ?>
<?php if ($cursor === '' && $filterCat === ''): ?> <?php if ($cursor === '' && $filterCat === ''): ?>