v1.6.28 : drill-down IP par AS dans stats pays, suppression Répartition par réseau

- Admin stats : clic sur un réseau AS affiche les IPs avec mini sparkline 14 jours + articles/livres consultés
- AccessLogParser : calcul ip_data (daily + top paths) inclus dans le cache stats
- Suppression du tableau statique "Répartition par réseau" (fusionné dans accordéon pays)
- PHP-CS-Fixer appliqué sur l'ensemble des fichiers modifiés

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-19 19:59:44 +02:00
parent d6a7033e9e
commit 40656631ba
23 changed files with 248 additions and 174 deletions
+1 -1
View File
File diff suppressed because one or more lines are too long
+11
View File
@@ -5,6 +5,17 @@ Format : [Keep a Changelog](https://keepachangelog.com/fr/1.0.0/) — versionnag
---
## [1.6.28] - 2026-05-19
### Ajouté
- Admin stats : drill-down AS → IPs dans l'accordéon « Visiteurs par pays » — mini sparkline 14 jours + articles/livres consultés par IP
- Admin stats : `ip_data` dans le cache stats (daily + top paths par IP publique)
### Supprimé
- Admin stats : section « Répartition par réseau » (fusionnée dans l'accordéon pays)
---
## [1.6.27] - 2026-05-19
### Ajouté
+107 -41
View File
@@ -1,35 +1,63 @@
/* Admin stats : groupes AS + chargement pages via flux RSS XML /trending?period=14d */
/* Admin stats : graphiques, sparklines, accordéon pays/AS/IP */
function esc(s) {
return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
// ── Visiteurs par pays ────────────────────────────────────────────────────────
(function () {
var el = document.getElementById('stats-country-container');
var asList = (typeof FOLIO_AS_LIST !== 'undefined') ? FOLIO_AS_LIST : [];
var ipData = (typeof FOLIO_IP_DATA !== 'undefined') ? FOLIO_IP_DATA : {};
if (!el || !asList.length) { return; }
// Noms de pays en français via l'API Intl
var dispNames = null;
try { dispNames = new Intl.DisplayNames(['fr'], { type: 'region' }); } catch (e) {}
function countryName(code) {
if (!code || code === '??') { return 'Inconnu'; }
try { return dispNames ? dispNames.of(code) : code; } catch (e) { return code; }
}
// Drapeau emoji depuis le code ISO-2
function flag(code) {
if (!code || code.length !== 2) { return ''; }
var cp = Array.from(code.toUpperCase()).map(function (c) {
return 0x1F1E6 + c.charCodeAt(0) - 65;
});
return String.fromCodePoint(cp[0], cp[1]) + ' ';
var cp = Array.from(code.toUpperCase()).map(function (c) { return 0x1F1E6 + c.charCodeAt(0) - 65; });
return String.fromCodePoint(cp[0], cp[1]) + ' ';
}
// Index IPs par ASN pour le drill-down
var ipsByAsn = {};
Object.keys(ipData).forEach(function (ip) {
var d = ipData[ip];
var key = d.asn || '__unknown__';
if (!ipsByAsn[key]) { ipsByAsn[key] = []; }
ipsByAsn[key].push({ ip: ip, hits: d.hits, daily: d.daily, paths: d.paths });
});
Object.keys(ipsByAsn).forEach(function (k) {
ipsByAsn[k].sort(function (a, b) { return b.hits - a.hits; });
});
// Mini sparkline (80×20px polyline) pour chaque IP
function ipSparkline(daily) {
if (!daily || !daily.length) { return ''; }
var W = 80, H = 20, padX = 1, padY = 2;
var max = Math.max.apply(null, daily) || 1;
var n = daily.length;
var pts = daily.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(' ');
return '<svg xmlns="http://www.w3.org/2000/svg" width="' + W + '" height="' + H
+ '" style="display:block;flex-shrink:0">'
+ '<polyline points="' + pts + '" fill="none" stroke="#6c757d"'
+ ' stroke-width="1.2" stroke-linejoin="round" stroke-linecap="round"/>'
+ '</svg>';
}
// Agréger par pays
var byCountry = {};
var asByCountry = {}; // country → [{name, asn, hits}]
var byCountry = {}, asByCountry = {};
asList.forEach(function (as) {
var c = as.country || '??';
byCountry[c] = (byCountry[c] || 0) + as.hits;
byCountry[c] = (byCountry[c] || 0) + as.hits;
if (!asByCountry[c]) { asByCountry[c] = []; }
asByCountry[c].push(as);
});
@@ -41,26 +69,83 @@
if (!countries.length) { el.innerHTML = '<p class="text-muted mb-0">Aucune donnée.</p>'; return; }
var maxH = countries[0].hits || 1;
var html = '<div class="accordion accordion-flush" id="acc-countries">';
countries.forEach(function (c, i) {
countries.forEach(function (c, ci) {
var pct = Math.round(c.hits / maxH * 100);
var cname = flag(c.code) + countryName(c.code);
var vis = c.hits.toLocaleString('fr-FR');
var accId = 'acc-country-' + i;
var accId = 'acc-country-' + ci;
var nets = c.networks.slice().sort(function (a, b) { return b.hits - a.hits; });
var maxN = nets[0] ? nets[0].hits : 1;
var netRows = nets.map(function (n) {
var npct = Math.round(n.hits / maxN * 100);
return '<div class="d-flex align-items-center gap-2 py-1">'
+ '<div class="text-muted small" style="width:9rem;flex-shrink:0">'
+ (n.name || '?') + (n.asn ? ' <span class="opacity-50">AS' + n.asn + '</span>' : '') + '</div>'
var netRows = nets.map(function (n, ni) {
var npct = Math.round(n.hits / maxN * 100);
var asId = 'acc-as-' + ci + '-' + ni;
var asnKey = n.asn || '__unknown__';
var ips = ipsByAsn[asnKey] || [];
// Lignes IP avec mini sparkline + chemins
var ipRows = ips.slice(0, 20).map(function (ipInfo) {
var articles = [], books = [];
Object.keys(ipInfo.paths || {}).forEach(function (path) {
var cnt = ipInfo.paths[path];
if (path.indexOf('/post/') === 0) { articles.push({ path: path, cnt: cnt }); }
else if (path.indexOf('/book/') === 0) { books.push({ path: path, cnt: cnt }); }
});
articles.sort(function (a, b) { return b.cnt - a.cnt; });
books.sort(function (a, b) { return b.cnt - a.cnt; });
var pathsHtml = '';
if (articles.length) {
pathsHtml += '<div style="font-size:.75rem;color:#6c757d">Articles : '
+ articles.slice(0, 3).map(function (p) {
var slug = decodeURIComponent(p.path.replace('/post/', ''));
return '<a href="' + esc(p.path) + '" target="_blank" style="color:inherit">'
+ esc(slug.length > 28 ? slug.slice(0, 28) + '…' : slug)
+ '</a>(' + p.cnt + ')';
}).join(', ') + '</div>';
}
if (books.length) {
pathsHtml += '<div style="font-size:.75rem;color:#6c757d">Livres : '
+ books.slice(0, 3).map(function (p) {
var slug = decodeURIComponent(p.path.replace('/book/', ''));
return '<a href="' + esc(p.path) + '" target="_blank" style="color:inherit">'
+ esc(slug.length > 28 ? slug.slice(0, 28) + '…' : slug)
+ '</a>(' + p.cnt + ')';
}).join(', ') + '</div>';
}
if (!pathsHtml) { pathsHtml = '<span style="font-size:.75rem;color:#adb5bd">—</span>'; }
return '<div class="d-flex align-items-center gap-2 py-1 border-bottom">'
+ '<code style="width:9rem;flex-shrink:0;font-size:.72rem;color:#6c757d">'
+ esc(ipInfo.ip) + '</code>'
+ ipSparkline(ipInfo.daily || [])
+ '<div class="flex-grow-1">' + pathsHtml + '</div>'
+ '<div class="text-end text-muted small" style="width:4rem;flex-shrink:0">'
+ (ipInfo.hits || 0).toLocaleString('fr-FR') + '</div>'
+ '</div>';
}).join('');
var hasIps = ips.length > 0;
var toggleAttrs = hasIps ? ' data-bs-toggle="collapse" data-bs-target="#' + asId + '" role="button"' : '';
var chevron = hasIps ? '<span class="text-muted ms-1" style="font-size:.65rem">▾</span>' : '';
return '<div>'
+ '<div class="d-flex align-items-center gap-2 py-1"' + toggleAttrs + '>'
+ '<div class="small" style="width:9rem;flex-shrink:0">'
+ esc(n.name || '?')
+ (n.asn ? ' <span class="text-muted">AS' + esc(n.asn) + '</span>' : '')
+ chevron + '</div>'
+ '<div class="flex-grow-1"><div class="progress" style="height:4px">'
+ '<div class="progress-bar bg-info" style="width:' + npct + '%"></div>'
+ '</div></div>'
+ '<div class="text-end text-muted small" style="width:4rem;flex-shrink:0">'
+ n.hits.toLocaleString('fr-FR') + '</div>'
+ '</div>'
+ (hasIps ? '<div id="' + asId + '" class="collapse">'
+ '<div class="border-start ms-3 ps-2 pb-1">' + ipRows + '</div>'
+ '</div>' : '')
+ '</div>';
}).join('');
@@ -80,6 +165,7 @@
+ '</div>'
+ '</div>';
});
html += '</div>';
el.innerHTML = html;
}());
@@ -91,10 +177,6 @@
var pagesByDay = (typeof FOLIO_PAGES_BY_DAY !== 'undefined') ? FOLIO_PAGES_BY_DAY : {};
if (!container) { return; }
function esc(s) {
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;
@@ -104,7 +186,6 @@
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">'
@@ -123,17 +204,15 @@
var n = totals.length;
var VW = 900, VH = 480;
var ml = 44, mr = 12, mt = 12, mb = 28; // marges pour axes
var ml = 44, mr = 12, mt = 12, mb = 28;
var W = VW - ml - mr;
var H = VH - mt - mb;
// Échelle Y — plafond arrondi à un multiple "propre"
var rawMax = Math.max.apply(null, totals) || 1;
var mag = Math.pow(10, Math.floor(Math.log(rawMax) / Math.LN10));
var maxV = Math.ceil(rawMax / mag) * mag;
var nTicks = 4;
// Dates
var now = new Date();
var labels = totals.map(function (_, i) {
var d = new Date(now);
@@ -141,17 +220,10 @@
return d.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' });
});
// Coordonnées des points
var pts = totals.map(function (v, i) {
return {
x: ml + i * W / (n - 1),
y: mt + H - (v / maxV) * H,
v: v,
l: labels[i]
};
return { x: ml + i * W / (n - 1), y: mt + H - (v / maxV) * H, v: v, l: labels[i] };
});
// Courbe bezier lisse (tension 0.35)
function smoothPath(points) {
var d = 'M ' + points[0].x.toFixed(1) + ' ' + points[0].y.toFixed(1);
for (var i = 0; i < points.length - 1; i++) {
@@ -176,7 +248,6 @@
+ ' L ' + pts[n - 1].x.toFixed(1) + ' ' + (mt + H)
+ ' L ' + pts[0].x.toFixed(1) + ' ' + (mt + H) + ' Z';
// Grille horizontale + labels Y
var grid = '', yLabels = '';
for (var t = 0; t <= nTicks; t++) {
var val = Math.round(maxV * t / nTicks);
@@ -187,7 +258,6 @@
+ ' font-size="11" fill="#adb5bd">' + val + '</text>';
}
// Labels X (toutes les 2 dates + dernière)
var xLabels = '';
pts.forEach(function (p, i) {
if (i % 2 === 0 || i === n - 1) {
@@ -196,7 +266,6 @@
}
});
// Points interactifs (cercle invisible + tooltip natif)
var dots = pts.map(function (p) {
return '<circle cx="' + p.x.toFixed(1) + '" cy="' + p.y.toFixed(1) + '" r="14"'
+ ' fill="transparent" cursor="default">'
@@ -238,7 +307,6 @@
var W = VW - ml - mr;
var H = VH - mt - mb;
// Top articles par total (max 10), dans l'ordre du RSS
var series = [];
rssRows.forEach(function (row) {
var pm = row.link.match(/\/post\/[^?#]*/);
@@ -312,7 +380,6 @@
+ '" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round"/>' + dots;
}).join('');
// Légende
var legend = series.map(function (s, si) {
var color = COLORS[si % COLORS.length];
var short = s.title.length > 32 ? s.title.slice(0, 32) + '…' : s.title;
@@ -351,7 +418,6 @@
var daily = pm ? (pagesByDay[pm[0]] || null) : null;
return { title: title, link: link, slug: slug, vis: vis, daily: daily };
});
// 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) {
+15
View File
@@ -2738,11 +2738,25 @@ switch ($action) {
$topIps = array_slice($accessStats['ips'], 0, 200, true);
$asnMap = (new AsnLookup())->batchLookup(array_keys($topIps));
$ipData = [];
foreach ($accessStats['ips_by_day'] ?? [] as $ip => $daily) {
$info = $asnMap[$ip] ?? ['asn' => '', 'name' => '?', 'country' => ''];
$ipData[$ip] = [
'hits' => $topIps[$ip] ?? (int) array_sum($daily),
'asn' => $info['asn'],
'name' => $info['name'],
'country' => $info['country'],
'daily' => $daily,
'paths' => $accessStats['ip_top_paths'][$ip] ?? [],
];
}
$statsRaw = [
'readable' => $accessParser->isReadable(),
'books' => $tParser->top($cutoff14, 20, ['/book/']),
'as' => AsnLookup::aggregateByAs($topIps, $asnMap),
'pages_by_day' => $accessStats['pages_by_day'] ?? [],
'ip_data' => $ipData,
];
@file_put_contents($statsCacheFile, json_encode($statsRaw));
}
@@ -2752,6 +2766,7 @@ switch ($action) {
$adminData['stats_as_groups'] = AsnLookup::applyGroups($statsRaw['as'], asGroups());
$adminData['as_groups'] = asGroups();
$adminData['stats_pages_by_day'] = $statsRaw['pages_by_day'] ?? [];
$adminData['stats_ip_data'] = $statsRaw['ip_data'] ?? [];
}
if ($tab === 'categories') {
+1
View File
@@ -1,4 +1,5 @@
<?php
declare(strict_types=1);
if (!defined('BASE_PATH')) {
+3 -3
View File
@@ -145,9 +145,9 @@ ob_start();
'7d' => '8 h', '14d' => '8 h', '30d' => '8 h',
'1y' => '8 h',
];
foreach (TENDANCES_PERIODS as $p => $info):
$url = $base . '/trending?period=' . rawurlencode($p);
?>
foreach (TENDANCES_PERIODS as $p => $info):
$url = $base . '/trending?period=' . rawurlencode($p);
?>
<tr>
<td><?= htmlspecialchars($info['label']) ?></td>
<td class="text-muted"><?= $cacheTtlLabels[$p] ?></td>
+1 -1
View File
@@ -122,7 +122,7 @@ echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$title = htmlspecialchars(($a['title'] ?? ''), ENT_XML1);
$plural = $v > 1 ? 's' : '';
$desc = htmlspecialchars($title . ' — ' . $v . ' visiteur' . $plural . ' unique' . $plural . ' (' . $label . ')', ENT_XML1);
?>
?>
<item>
<title><?= $title ?> (<?= $v ?> visiteur<?= $plural ?>)</title>
<link><?= $link ?></link>
+1 -1
View File
@@ -1 +1 @@
1.6.27
1.6.28
+1 -1
View File
@@ -57,7 +57,7 @@ foreach ($pending as $file) {
echo "\n";
$count++;
} catch (Throwable $e) {
echo "" . $e->getMessage() . "\n";
echo '✗ ' . $e->getMessage() . "\n";
$errors++;
break;
}
+43 -14
View File
@@ -30,7 +30,7 @@ class AccessLogParser
}
/**
* @return array{pages:array<string,int>,books:array<string,int>,ips:array<string,int>,pages_by_day:array<string,list<int>>}
* @return array{pages:array<string,int>,books:array<string,int>,ips:array<string,int>,pages_by_day:array<string,list<int>>,ips_by_day:array<string,list<int>>,ip_top_paths:array<string,array<string,int>>}
*/
public function stats(): array
{
@@ -48,19 +48,19 @@ class AccessLogParser
$pages = [];
$books = [];
$ips = [];
$dayPages = []; // [path => [dayOffset => count]], dayOffset 0=oldest
$dayPages = [];
$ipDays = []; // [ip => [dayOffset => count]]
$ipPaths = []; // [ip => [path => count]]
foreach ($this->logFiles() as $file) {
$this->parseFile($file, $cutoff, $pages, $books, $ips, $dayPages);
$this->parseFile($file, $cutoff, $pages, $books, $ips, $dayPages, $ipDays, $ipPaths);
}
arsort($pages);
arsort($books);
arsort($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) {
@@ -71,7 +71,32 @@ class AccessLogParser
$pagesByDay[$path] = $arr;
}
$result = ['pages' => $pages, 'books' => $books, 'ips' => $ips, 'pages_by_day' => $pagesByDay];
// Per-IP daily counts + top paths, limité aux 200 IPs les plus actives
$topIpKeys = array_keys(array_slice($ips, 0, 200, true));
$ipsByDay = [];
$ipTopPaths = [];
foreach ($topIpKeys as $ip) {
$arr = array_fill(0, $this->days, 0);
foreach ($ipDays[$ip] ?? [] as $offset => $count) {
if ($offset >= 0 && $offset < $this->days) {
$arr[$offset] = $count;
}
}
$ipsByDay[$ip] = $arr;
$paths = $ipPaths[$ip] ?? [];
arsort($paths);
$ipTopPaths[$ip] = array_slice($paths, 0, 10, true);
}
$result = [
'pages' => $pages,
'books' => $books,
'ips' => $ips,
'pages_by_day' => $pagesByDay,
'ips_by_day' => $ipsByDay,
'ip_top_paths' => $ipTopPaths,
];
@mkdir(dirname($this->cacheFile), 0755, true);
@file_put_contents($this->cacheFile, json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
return self::$memo = $result;
@@ -127,7 +152,7 @@ class AccessLogParser
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, array &$dayPages): void
private function parseLine(string $line, int $cutoff, array &$pages, array &$books, array &$ips, array &$dayPages, array &$ipDays, array &$ipPaths): void
{
if (!preg_match(self::RE, $line, $m)) {
return;
@@ -142,24 +167,28 @@ class AccessLogParser
return;
}
$publicIp = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false;
$publicIp = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false;
$dayOffset = (int) floor(($tsVal - $cutoff) / 86400);
if (str_starts_with($path, '/post/') && strlen($path) > 6) {
$pages[$path] = ($pages[$path] ?? 0) + 1;
if ($publicIp) {
$ips[$ip] = ($ips[$ip] ?? 0) + 1;
}
$dayOffset = (int) floor(($tsVal - $cutoff) / 86400);
$dayPages[$path][$dayOffset] = ($dayPages[$path][$dayOffset] ?? 0) + 1;
$dayPages[$path][$dayOffset] = ($dayPages[$path][$dayOffset] ?? 0) + 1;
$ipDays[$ip][$dayOffset] = ($ipDays[$ip][$dayOffset] ?? 0) + 1;
$ipPaths[$ip][$path] = ($ipPaths[$ip][$path] ?? 0) + 1;
} elseif (str_starts_with($path, '/book/') && strlen($path) > 6) {
$books[$path] = ($books[$path] ?? 0) + 1;
if ($publicIp) {
$ips[$ip] = ($ips[$ip] ?? 0) + 1;
}
$ipDays[$ip][$dayOffset] = ($ipDays[$ip][$dayOffset] ?? 0) + 1;
$ipPaths[$ip][$path] = ($ipPaths[$ip][$path] ?? 0) + 1;
}
}
private function parseFile(array $file, int $cutoff, array &$pages, array &$books, array &$ips, array &$dayPages): void
private function parseFile(array $file, int $cutoff, array &$pages, array &$books, array &$ips, array &$dayPages, array &$ipDays, array &$ipPaths): void
{
if ($file['type'] === 'tgz') {
try {
@@ -170,7 +199,7 @@ class AccessLogParser
continue;
}
foreach (explode("\n", $content) as $line) {
$this->parseLine($line, $cutoff, $pages, $books, $ips, $dayPages);
$this->parseLine($line, $cutoff, $pages, $books, $ips, $dayPages, $ipDays, $ipPaths);
}
}
} catch (\Exception $e) {
@@ -183,7 +212,7 @@ class AccessLogParser
while (!gzeof($h)) {
$line = gzgets($h, 8192);
if ($line !== false) {
$this->parseLine($line, $cutoff, $pages, $books, $ips, $dayPages);
$this->parseLine($line, $cutoff, $pages, $books, $ips, $dayPages, $ipDays, $ipPaths);
}
}
gzclose($h);
@@ -193,7 +222,7 @@ class AccessLogParser
return;
}
while (($line = fgets($h)) !== false) {
$this->parseLine($line, $cutoff, $pages, $books, $ips, $dayPages);
$this->parseLine($line, $cutoff, $pages, $books, $ips, $dayPages, $ipDays, $ipPaths);
}
fclose($h);
}
+1 -1
View File
@@ -95,7 +95,7 @@ class BookManager
$this->bookPath($slug),
json_encode($book, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n"
);
$this->git?->commit("book: " . ($book['title'] ?? $slug));
$this->git?->commit('book: ' . ($book['title'] ?? $slug));
}
public function delete(string $slug): void
+3 -1
View File
@@ -4,7 +4,9 @@ declare(strict_types=1);
class DataGit
{
public function __construct(private string $dataDir) {}
public function __construct(private string $dataDir)
{
}
public function commit(string $message): void
{
+6 -2
View File
@@ -61,7 +61,9 @@ PROMPT;
$raw = $this->provider === 'claude_code'
? $this->queryClaudeCode(self::SYSTEM_ANALYZE, $userMsg)
: $this->queryAnthropicRaw(self::SYSTEM_ANALYZE, $userMsg, 4096);
if (!$raw['ok']) return $raw;
if (!$raw['ok']) {
return $raw;
}
return $this->parseAnalyzeResponse($raw['text'] ?? '');
}
@@ -129,7 +131,9 @@ PROMPT;
$err = curl_error($ch);
curl_close($ch);
if ($err !== '') return ['ok' => false, 'error' => 'Erreur réseau : ' . $err];
if ($err !== '') {
return ['ok' => false, 'error' => 'Erreur réseau : ' . $err];
}
$data = json_decode((string) $resp, true);
if ($http !== 200) {
+6 -2
View File
@@ -96,14 +96,18 @@ function asGroups(): array
function aiProvider(): string
{
$v = siteSettings()['ai_provider'] ?? '';
if ($v !== '') return $v;
if ($v !== '') {
return $v;
}
return $_ENV['AI_PROVIDER'] ?? getenv('AI_PROVIDER') ?: 'anthropic';
}
function aiModel(): string
{
$v = siteSettings()['ai_model'] ?? '';
if ($v !== '') return $v;
if ($v !== '') {
return $v;
}
return $_ENV['AI_MODEL'] ?? getenv('AI_MODEL') ?: 'claude-haiku-4-5-20251001';
}
+2 -1
View File
@@ -15,7 +15,8 @@ class TrendingParser
public function __construct(
private string $logDir,
private string $pattern,
) {}
) {
}
/**
* Retourne les $limit chemins les plus consultés depuis $cutoff,
+6 -2
View File
@@ -66,8 +66,12 @@ function lineDiff(string $old, string $new): array
if ($n * $m > 2_000_000) {
$diff = [['!', "Diff trop grand ({$n}×{$m} lignes) — affichage simplifié."]];
foreach ($a as $line) { $diff[] = ['-', $line]; }
foreach ($b as $line) { $diff[] = ['+', $line]; }
foreach ($a as $line) {
$diff[] = ['-', $line];
}
foreach ($b as $line) {
$diff[] = ['+', $line];
}
return $diff;
}
+15 -13
View File
@@ -230,7 +230,9 @@ function adminStatusBadge(array $a, int $now): string
return '/admin/articles?' . http_build_query($p);
};
$_sortIcon = function (string $col) use ($_sortBy, $_sortDir): string {
if ($_sortBy !== $col) { return '<span class="text-muted ms-1" style="font-size:.75em">↕</span>'; }
if ($_sortBy !== $col) {
return '<span class="text-muted ms-1" style="font-size:.75em">↕</span>';
}
return '<span class="ms-1" style="font-size:.75em">' . ($_sortDir === 'asc' ? '↑' : '↓') . '</span>';
};
?>
@@ -389,7 +391,7 @@ function adminStatusBadge(array $a, int $now): string
'sort' => $_sortBy,
'dir' => $_sortDir,
], fn ($v) => $v !== ''));
foreach ($adminData['articles'] as $_fa):
foreach ($adminData['articles'] as $_fa):
?>
<form id="toggle-featured-<?= htmlspecialchars($_fa['uuid']) ?>" method="post" action="/?action=admin_toggle_featured" hidden>
<input type="hidden" name="uuid" value="<?= htmlspecialchars($_fa['uuid']) ?>">
@@ -1422,11 +1424,11 @@ foreach (COLOR_PALETTE_16 as $_i => $_rgb):
<option value="">— Choisir un article —</option>
<?php
$alreadyIn = $eb['articles'] ?? [];
foreach ($adminData['all_articles'] as $aa):
if (in_array($aa['slug'] ?? '', $alreadyIn, true)) {
continue;
}
?>
foreach ($adminData['all_articles'] as $aa):
if (in_array($aa['slug'] ?? '', $alreadyIn, true)) {
continue;
}
?>
<option value="<?= htmlspecialchars($aa['slug'] ?? '') ?>">
<?= htmlspecialchars($aa['title']) ?>
<?= !$aa['published'] ? ' (brouillon)' : '' ?>
@@ -1495,11 +1497,11 @@ foreach (COLOR_PALETTE_16 as $_i => $_rgb):
<?php
$_aiNotice = $adminData['ai_notice'] ?? '';
$_aiProvider = $adminData['ai_provider'] ?? 'anthropic';
$_aiModel = $adminData['ai_model'] ?? '';
$_anthropicOk = $adminData['anthropic_key_set'] ?? false;
$_cliOk = $adminData['claude_cli_found'] ?? false;
?>
$_aiProvider = $adminData['ai_provider'] ?? 'anthropic';
$_aiModel = $adminData['ai_model'] ?? '';
$_anthropicOk = $adminData['anthropic_key_set'] ?? false;
$_cliOk = $adminData['claude_cli_found'] ?? false;
?>
<?php if ($_aiNotice === 'saved'): ?>
<div class="alert alert-success py-2 small">Configuration IA enregistrée.</div>
@@ -1619,6 +1621,6 @@ sudo -u www-data HOME=/var/lib/claude-www /usr/local/bin/claude --print "Répond
<?php endif; ?>
<?php
$content = ob_get_clean();
$content = ob_get_clean();
$title = 'Administration — ' . siteTitle();
include __DIR__ . '/layout.php';
+3 -71
View File
@@ -4,10 +4,8 @@ $_statsError = ($_GET['error'] ?? '') === 'write';
$_readable = $adminData['stats_readable'] ?? false;
$_books = $adminData['stats_books'] ?? [];
$_asList = $adminData['stats_as'] ?? [];
$_asGroups = $adminData['stats_as_groups'] ?? [];
$_groups = $adminData['as_groups'] ?? [];
$_pagesByDay = $adminData['stats_pages_by_day'] ?? [];
$_activeGroup = trim($_GET['group'] ?? '');
$_ipData = $adminData['stats_ip_data'] ?? [];
?>
<?php if ($_statsSaved): ?>
@@ -27,7 +25,8 @@ $_activeGroup = trim($_GET['group'] ?? '');
<script>
var FOLIO_PAGES_BY_DAY = <?= json_encode($_pagesByDay, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>;
var FOLIO_AS_LIST = <?= json_encode($_asList, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>;
var FOLIO_AS_LIST = <?= json_encode($_asList, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>;
var FOLIO_IP_DATA = <?= json_encode($_ipData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>;
</script>
<div class="card mb-4">
@@ -98,73 +97,6 @@ var FOLIO_AS_LIST = <?= json_encode($_asList, JSON_UNESCAPED_SLASHES |
</div><!-- /row -->
<!-- Répartition par réseau -->
<div class="card mt-4">
<div class="card-header bg-transparent py-2 small fw-semibold d-flex align-items-center gap-3 flex-wrap">
<span>Répartition par réseau</span>
<?php if (!empty($_groups)): ?>
<div class="d-flex gap-1 flex-wrap">
<a href="/admin/stats" class="badge <?= $_activeGroup === '' ? 'bg-primary' : 'bg-secondary' ?> text-decoration-none">Tous</a>
<?php foreach ($_groups as $g): ?>
<a href="/admin/stats?group=<?= rawurlencode($g['label']) ?>"
class="badge <?= $_activeGroup === $g['label'] ? 'bg-primary' : 'bg-secondary' ?> text-decoration-none">
<?= htmlspecialchars($g['label']) ?>
</a>
<?php endforeach; ?>
<a href="/admin/stats?group=Autres"
class="badge <?= $_activeGroup === 'Autres' ? 'bg-primary' : 'bg-secondary' ?> text-decoration-none">Autres</a>
</div>
<?php endif; ?>
</div>
<div class="card-body p-0">
<?php
// Sélectionner les AS à afficher
if ($_activeGroup !== '' && isset($_asGroups[$_activeGroup])) {
$displayAs = $_asGroups[$_activeGroup];
} else {
$displayAs = $_asList;
}
?>
<?php if (empty($displayAs)): ?>
<p class="text-muted p-3 mb-0">
<?= empty($_asList) ? 'Aucune IP résolue (LAN ou logs vides).' : 'Aucun AS dans ce groupe.' ?>
</p>
<?php else: ?>
<?php $maxAS = max(array_column($displayAs, 'hits')) ?: 1; ?>
<div class="table-responsive">
<table class="table table-sm table-hover mb-0 small">
<thead class="table-light">
<tr>
<th class="ps-3" style="width:2rem">#</th>
<th>Réseau</th>
<th style="width:3rem">Pays</th>
<th style="width:5rem" class="text-end pe-3">Visites</th>
</tr>
</thead>
<tbody>
<?php foreach ($displayAs as $i => $as): ?>
<tr>
<td class="text-muted ps-3"><?= $i + 1 ?></td>
<td>
<span class="fw-medium"><?= htmlspecialchars($as['name'] ?: '?') ?></span>
<?php if ($as['asn'] !== ''): ?>
<span class="text-muted ms-1">AS<?= htmlspecialchars($as['asn']) ?></span>
<?php endif; ?>
<div class="progress mt-1" style="height:3px">
<div class="progress-bar bg-info" style="width:<?= round($as['hits'] / $maxAS * 100) ?>%"></div>
</div>
</td>
<td class="text-muted"><?= htmlspecialchars($as['country']) ?></td>
<td class="text-end fw-semibold pe-3"><?= number_format($as['hits'], 0, ',', '\u{202F}') ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div>
</div>
<?php endif; // readable?>
+3 -3
View File
@@ -21,9 +21,9 @@ ob_start();
$_cover = $_first['cover'] ?? '';
$_cat = trim($_first['category'] ?? '');
$_coverStyle = $_cover !== ''
? "background-image:url('/file?uuid=" . rawurlencode($_first['uuid']) . "&name=" . rawurlencode($_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">
@@ -42,7 +42,7 @@ ob_start();
</div>
<?php
$content = ob_get_clean();
$content = ob_get_clean();
$title = 'Livres — ' . siteTitle();
$metaRobots = 'index, follow';
$canonical = rtrim((string)($_ENV['APP_URL'] ?? getenv('APP_URL') ?: ''), '/') . '/books';
+8 -7
View File
@@ -48,13 +48,14 @@
<link href="/assets/css/bootstrap.min.css" rel="stylesheet">
<?php
$_pub = BASE_PATH . '/public/assets/';
if (!function_exists('_av')) {
function _av(string $base, string $rel): string {
$f = $base . $rel;
return '/assets/' . $rel . (is_file($f) ? '?v=' . substr(md5_file($f), 0, 8) : '');
}
if (!function_exists('_av')) {
function _av(string $base, string $rel): string
{
$f = $base . $rel;
return '/assets/' . $rel . (is_file($f) ? '?v=' . substr(md5_file($f), 0, 8) : '');
}
?>
}
?>
<link rel="stylesheet" href="<?= _av($_pub, 'css/style.css') ?>">
</head>
@@ -65,7 +66,7 @@
<nav class="navbar navbar-expand-lg navbar-dark mb-0" role="navigation" aria-label="Navigation principale">
<div class="container-fluid">
<?php
$_layoutAction = $_GET['action'] ?? 'list';
$_layoutAction = $_GET['action'] ?? 'list';
$_layoutPrivateCats = isset($articles) ? $articles->getPrivateCategories() : [];
$_layoutCats = isset($articles) ? array_filter(
$articles->getCategories(),
+3 -3
View File
@@ -228,9 +228,9 @@ function _renderCard(array $post, array $privateCats, array $allCats, \Parsedown
$_cover = $_first['cover'] ?? '';
$_cat = trim($_first['category'] ?? '');
$_coverStyle = $_cover !== ''
? "background-image:url('/file?uuid=" . rawurlencode($_first['uuid']) . "&name=" . rawurlencode($_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">
@@ -275,7 +275,7 @@ function _renderCard(array $post, array $privateCats, array $allCats, \Parsedown
<?php if ($prevCursor !== null || $nextCursor !== null): ?>
<nav class="pagination-nav mt-5" aria-label="Navigation">
<?php
$hasCat = $filterCat !== '';
$hasCat = $filterCat !== '';
$catBase = $hasCat ? '/categorie/' . rawurlencode($filterCat) : null;
?>
<?php if ($prevCursor !== null): ?>
+5 -5
View File
@@ -294,9 +294,9 @@ $hasSources = (!empty($externalLinks) || !empty($files))
<?php if ($article['published'] ?? false): ?>
<?php
$_shareUrl = rtrim(defined('APP_URL') ? APP_URL : '', '/') . '/post/' . rawurlencode($article['slug'] ?? '');
$_shareTitle = $article['title'] ?? '';
?>
$_shareUrl = rtrim(defined('APP_URL') ? APP_URL : '', '/') . '/post/' . rawurlencode($article['slug'] ?? '');
$_shareTitle = $article['title'] ?? '';
?>
<div class="d-flex flex-wrap align-items-center gap-2 my-3 py-2 border-top"
id="share-bar"
data-url="<?= htmlspecialchars($_shareUrl) ?>"
@@ -442,8 +442,8 @@ $_shareTitle = $article['title'] ?? '';
<?php
$_revisions = array_reverse($article['revisions'] ?? []);
if (!empty($_revisions) && isLoggedIn()):
?>
if (!empty($_revisions) && isLoggedIn()):
?>
<h6 class="related-sidebar-title mt-3">Historique</h6>
<ul class="toc-list small">
<?php foreach (array_slice($_revisions, 0, 10) as $_rev): ?>
+3 -1
View File
@@ -201,5 +201,7 @@ $_hasUuid = $_wizUuid !== '';
<?php
$content = ob_get_clean();
$title = ($mode === 'create' ? 'Nouvel article' : 'Modifier') . ' — Étape 1/' . $totalSteps;
if ($mode === 'edit') { $aiEditor = true; }
if ($mode === 'edit') {
$aiEditor = true;
}
include BASE_PATH . '/templates/layout.php';