/* Admin stats : graphiques, sparklines, accordΓ©on pays/AS/IP, agents */ function esc(s) { return String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); } function trunc(s, n) { return s.length > n ? s.slice(0, n) + '…' : s; } // DΓ©tection de bot par correspondance partielle insensible Γ  la casse var _botPatterns = (typeof FOLIO_BOT_PATTERNS !== 'undefined') ? FOLIO_BOT_PATTERNS : []; function isBot(ua) { if (!ua) { return false; } var lo = ua.toLowerCase(); for (var i = 0; i < _botPatterns.length; i++) { if (lo.indexOf(_botPatterns[i].toLowerCase()) !== -1) { return true; } } return false; } function botBadge(ua) { return isBot(ua) ? 'πŸ€– ' : ''; } // AS exclus (modifiΓ© dynamiquement par les boutons) var _excludedAs = (typeof FOLIO_EXCLUDED_AS !== 'undefined') ? FOLIO_EXCLUDED_AS.slice() : []; var _csrf = (typeof FOLIO_CSRF !== 'undefined') ? FOLIO_CSRF : ''; // ── RΓ©sumΓ© visiteurs ───────────────────────────────────────────────────────── (function () { var el = document.getElementById('stats-summary-container'); var uv = (typeof FOLIO_UNIQUE_VISITORS !== 'undefined') ? FOLIO_UNIQUE_VISITORS : {}; var ipd = (typeof FOLIO_IP_DATA !== 'undefined') ? FOLIO_IP_DATA : {}; if (!el) { return; } function computeCounts() { var base = { 7: uv[7] || 0, 14: uv[14] || 0, 30: uv[30] || 0 }; // Soustraire les IPs des AS exclus (top 200 uniquement β€” approximation) Object.keys(ipd).forEach(function (ip) { var d = ipd[ip]; if (!d.asn || _excludedAs.indexOf(d.asn) === -1) { return; } var daily = d.daily || []; var n = daily.length; if (daily.some(function (v) { return v > 0; })) { base[30] = Math.max(0, base[30] - 1); } if (daily.slice(Math.max(0, n - 14)).some(function (v) { return v > 0; })) { base[14] = Math.max(0, base[14] - 1); } if (daily.slice(Math.max(0, n - 7)).some(function (v) { return v > 0; })) { base[7] = Math.max(0, base[7] - 1); } }); return base; } function render() { var c = computeCounts(); el.innerHTML = '
' + '
' + '
' + 'Visiteurs uniques non-bot' + '' + c[7].toLocaleString('fr-FR') + '7 jours' + '' + c[14].toLocaleString('fr-FR') + '14 jours' + '' + c[30].toLocaleString('fr-FR') + '30 jours' + (_excludedAs.length ? '' + _excludedAs.length + ' AS exclu(s)' : '') + '
' + '
' + '
'; } render(); document.addEventListener('folio:excluded-as-changed', render); }()); // ── 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; } var _countryClickHandler = null; 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; } } 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]) + ' '; } // Index IPs par ASN 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, agents: d.agents || [] }); }); Object.keys(ipsByAsn).forEach(function (k) { ipsByAsn[k].sort(function (a, b) { return b.hits - a.hits; }); }); // IPs sans AS var noAsCount = Object.keys(ipData).filter(function (ip) { return !ipData[ip].asn; }).length; 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 '' + '' + ''; } function excludeAs(asn, name) { var fd = new FormData(); fd.append('_csrf', _csrf); fd.append('asn', asn); fetch('/?action=admin_add_excluded_as', { method: 'POST', body: fd }) .then(function (r) { return r.json(); }) .then(function (d) { if (d.ok && _excludedAs.indexOf(asn) === -1) { _excludedAs.push(asn); document.dispatchEvent(new CustomEvent('folio:excluded-as-changed')); renderCountry(); } }); } function includeAs(asn) { var fd = new FormData(); fd.append('_csrf', _csrf); fd.append('asn', asn); fetch('/?action=admin_remove_excluded_as', { method: 'POST', body: fd }) .then(function (r) { return r.json(); }) .then(function (d) { if (d.ok) { _excludedAs = _excludedAs.filter(function (a) { return a !== asn; }); document.dispatchEvent(new CustomEvent('folio:excluded-as-changed')); renderCountry(); } }); } function buildIpRow(ipInfo) { // Agents sous l'IP avec badge bot (UA en entier) var agentsHtml = ''; (ipInfo.agents || []).forEach(function (ua) { agentsHtml += '
' + botBadge(ua) + esc(ua) + '
'; }); // Chemins triΓ©s : /post/ et /book/ avec ts, reste sans ts var postBook = [], other = []; Object.keys(ipInfo.paths || {}).forEach(function (path) { var p = ipInfo.paths[path]; var cnt = (p && typeof p === 'object') ? p.n : p; var ts = (p && typeof p === 'object') ? p.ts : 0; if (ts > 0) { postBook.push({ path: path, cnt: cnt, ts: ts }); } else { other.push({ path: path, cnt: cnt }); } }); postBook.sort(function (a, b) { return b.ts - a.ts; }); other.sort(function (a, b) { return b.cnt - a.cnt; }); function pathLine(p, prefix) { var raw = p.path.replace(prefix, ''); var slug = ''; try { slug = decodeURIComponent(raw); } catch (e) { slug = raw; } return '
' + '' + esc(trunc(slug || p.path, 40)) + '' + ' (' + p.cnt + ')
'; } function otherLine(p) { return '
' + '' + esc(trunc(p.path, 44)) + '' + ' (' + p.cnt + ')
'; } var pathsHtml = ''; var articles = postBook.filter(function (p) { return p.path.indexOf('/post/') === 0; }); var books = postBook.filter(function (p) { return p.path.indexOf('/book/') === 0; }); if (articles.length) { pathsHtml += '
Articles
' + articles.map(function (p) { return pathLine(p, '/post/'); }).join(''); } if (books.length) { pathsHtml += '
Livres
' + books.map(function (p) { return pathLine(p, '/book/'); }).join(''); } if (other.length) { pathsHtml += '
Autres chemins
' + other.map(otherLine).join(''); } if (!pathsHtml) { pathsHtml = 'β€”'; } return '
' + '
' + '' + esc(ipInfo.ip) + '' + agentsHtml + '
' + '
' + ipSparkline(ipInfo.daily || []) + '
' + '
' + pathsHtml + '
' + '
' + (ipInfo.hits || 0).toLocaleString('fr-FR') + '
' + '
'; } function renderCountry() { // Filtrer les AS actifs / exclus var activeLists = asList.filter(function (as) { return _excludedAs.indexOf(as.asn) === -1; }); var excludedLists = asList.filter(function (as) { return _excludedAs.indexOf(as.asn) !== -1; }); // AgrΓ©ger par pays (AS actifs uniquement) var byCountry = {}, asByCountry = {}; activeLists.forEach(function (as) { var c = as.country || '??'; byCountry[c] = (byCountry[c] || 0) + as.hits; if (!asByCountry[c]) { asByCountry[c] = []; } asByCountry[c].push(as); }); var countries = Object.keys(byCountry).map(function (c) { return { code: c, hits: byCountry[c], networks: asByCountry[c] }; }).sort(function (a, b) { return b.hits - a.hits; }).slice(0, 20); // En-tΓͺte avec alerte IPs sans AS var headerExtra = ''; if (noAsCount > 0) { headerExtra = '' + noAsCount + ' IP(s) sans AS'; } var countryCard = document.querySelector('#stats-country-container'); if (countryCard) { var hdr = countryCard.closest('.card') ? countryCard.closest('.card').querySelector('.card-header') : null; if (hdr && !hdr.querySelector('.no-as-badge')) { var span = document.createElement('span'); span.className = 'no-as-badge'; span.innerHTML = headerExtra; hdr.appendChild(span); } } if (!countries.length) { el.innerHTML = '

Aucune donnΓ©e.

'; return; } var maxH = countries[0].hits || 1; var html = '
'; 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-' + 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, ni) { var npct = Math.round(n.hits / maxN * 100); var asId = 'acc-as-' + ci + '-' + ni; var asnKey = n.asn || '__unknown__'; var ips = ipsByAsn[asnKey] || []; var ipRows = ips.slice(0, 20).map(buildIpRow).join(''); var hasIps = ips.length > 0; var toggleAttrs = hasIps ? ' data-bs-toggle="collapse" data-bs-target="#' + asId + '" role="button"' : ''; var chevron = hasIps ? 'β–Ύ' : ''; var excludeBtn = n.asn ? '' : ''; return '
' + '
' + '
' + '' + esc(n.name || '?') + '' + (n.asn ? ' AS' + esc(n.asn) + '' : '') + chevron + '
' + excludeBtn + '
' + '
' + '
' + '
' + n.hits.toLocaleString('fr-FR') + '
' + '
' + (hasIps ? '
' + '
' + ipRows + '
' + '
' : '') + '
'; }).join(''); html += '
' + '' + '
' + '
' + netRows + '
' + '
' + '
'; }); html += '
'; // Section AS exclus if (excludedLists.length) { html += '
' + '
AS exclus des stats (' + excludedLists.length + ')
' + '
'; excludedLists.forEach(function (n) { html += '' + esc(n.name || '?') + (n.asn ? ' AS' + esc(n.asn) + '' : '') + '' + ''; }); html += '
'; } el.innerHTML = html; // DΓ©lΓ©gation : boutons exclure / inclure (handler unique pour Γ©viter les doublons) if (_countryClickHandler) { el.removeEventListener('click', _countryClickHandler); } _countryClickHandler = function (e) { var btn = e.target.closest('.exclude-as-btn'); if (btn) { e.stopPropagation(); excludeAs(btn.getAttribute('data-asn'), btn.getAttribute('data-name')); return; } btn = e.target.closest('.include-as-btn'); if (btn) { e.stopPropagation(); includeAs(btn.getAttribute('data-asn')); } }; el.addEventListener('click', _countryClickHandler); } renderCountry(); document.addEventListener('folio:excluded-as-changed', renderCountry); }()); // ── Liste consolidΓ©e de tous les agents ────────────────────────────────────── (function () { var el = document.getElementById('stats-agents-container'); var badge = document.getElementById('agents-count'); var allUas = (typeof FOLIO_ALL_UAS !== 'undefined') ? FOLIO_ALL_UAS : {}; var csrf = (typeof FOLIO_CSRF !== 'undefined') ? FOLIO_CSRF : ''; if (!el) { return; } var agents = Object.keys(allUas).map(function (ua) { return { ua: ua, hits: allUas[ua], bot: isBot(ua) }; }).sort(function (a, b) { if (a.bot !== b.bot) { return a.bot ? -1 : 1; } return b.hits - a.hits; }); if (!agents.length) { el.innerHTML = '

Aucun agent dΓ©tectΓ©.

'; return; } var bots = agents.filter(function (a) { return a.bot; }); var unknown = agents.filter(function (a) { return !a.bot; }); if (badge) { badge.textContent = 'β€” ' + bots.length + ' bot(s) sur ' + agents.length; } function addBot(ua, btn) { btn.disabled = true; var fd = new FormData(); fd.append('_csrf', csrf); fd.append('pattern', ua); fetch('/?action=admin_add_bot', { method: 'POST', body: fd }) .then(function (r) { return r.json(); }) .then(function (d) { if (d.ok) { _botPatterns.push(ua); btn.closest('tr').querySelector('td:first-child').innerHTML = 'πŸ€–'; btn.remove(); } else { btn.disabled = false; } }) .catch(function () { btn.disabled = false; }); } function agentRow(a) { var addBtn = (!a.bot) ? '' : ''; return '' + '' + (a.bot ? 'πŸ€–' : '?') + '' + '' + '' + esc(a.ua) + '' + addBtn + '' + '' + a.hits.toLocaleString('fr-FR') + '' + ''; } var botsHtml = bots.map(agentRow).join(''); var unknownHtml = unknown.map(agentRow).join(''); var html = '
' + '' + '' + '' + '' + '' + '' + ''; if (botsHtml) { html += '' + botsHtml; } if (unknownHtml) { html += '' + unknownHtml; } html += '
User-AgentReq.
' + 'Bots connus (' + bots.length + ')
' + 'Agents non classΓ©s (' + unknown.length + ')
'; el.innerHTML = html; // DΓ©lΓ©gation : boutons "+ bot" el.addEventListener('click', function (e) { var btn = e.target.closest('.add-bot-btn'); if (!btn) { return; } var row = btn.closest('tr'); var code = row ? row.querySelector('code') : null; if (code) { addBot(code.textContent, btn); } }); }()); // ── Pages les plus visitΓ©es (RSS XML + sparklines) ─────────────────────────── (function () { var container = document.getElementById('stats-pages-container'); var badge = document.getElementById('stats-pages-count'); var pagesByDay = (typeof FOLIO_PAGES_BY_DAY !== 'undefined') ? FOLIO_PAGES_BY_DAY : {}; if (!container) { return; } 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(' '); var first = padX.toFixed(1) + ',' + (H - padY).toFixed(1); var last = (W - padX).toFixed(1) + ',' + (H - padY).toFixed(1); return '' + '' + '' + '' + '' + '' + '' + ''; } function trendChart(totals) { var trendEl = document.getElementById('stats-trend-container'); if (!trendEl || !totals.length) { return; } var n = totals.length; var VW = 900, VH = 480; var ml = 44, mr = 12, mt = 12, mb = 28; var W = VW - ml - mr; var H = VH - mt - mb; 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; var now = new Date(); var labels = totals.map(function (_, i) { var d = new Date(now); d.setDate(d.getDate() - (n - 1 - i)); return d.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' }); }); 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] }; }); 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++) { var p0 = points[i > 0 ? i - 1 : i]; var p1 = points[i]; var p2 = points[i + 1]; var p3 = points[i + 2 < points.length ? i + 2 : i + 1]; var t = 0.35; var cp1x = p1.x + t * (p2.x - p0.x) / 2; var cp1y = p1.y + t * (p2.y - p0.y) / 2; var cp2x = p2.x - t * (p3.x - p1.x) / 2; var cp2y = p2.y - t * (p3.y - p1.y) / 2; d += ' C ' + cp1x.toFixed(1) + ' ' + cp1y.toFixed(1) + ', ' + cp2x.toFixed(1) + ' ' + cp2y.toFixed(1) + ', ' + p2.x.toFixed(1) + ' ' + p2.y.toFixed(1); } return d; } var linePath = smoothPath(pts); var areaPath = linePath + ' L ' + pts[n - 1].x.toFixed(1) + ' ' + (mt + H) + ' L ' + pts[0].x.toFixed(1) + ' ' + (mt + H) + ' Z'; var grid = '', yLabels = ''; for (var t = 0; t <= nTicks; t++) { var val = Math.round(maxV * t / nTicks); var gy = (mt + H - (val / maxV) * H).toFixed(1); grid += ''; yLabels += '' + val + ''; } var xLabels = ''; pts.forEach(function (p, i) { if (i % 3 === 0 || i === n - 1) { xLabels += '' + p.l + ''; } }); var dots = pts.map(function (p) { return '' + '' + esc(p.l) + ' : ' + p.v + ' visiteur(s)' + '' + ''; }).join(''); trendEl.innerHTML = '

Visiteurs uniques / jour β€” 30 derniers jours (top 200 IPs)

' + '' + '' + '' + '' + '' + '' + '' + grid + '' + '' + dots + yLabels + xLabels + ''; } function multiLineChart(pagesByDay, rssRows) { var el = document.getElementById('stats-multiline-container'); if (!el) { return; } var COLORS = ['#0d6efd','#198754','#dc3545','#fd7e14','#6f42c1', '#20c997','#0dcaf0','#e63946','#f4a261','#457b9d']; var VW = 900, VH = 480; var ml = 44, mr = 12, mt = 12, mb = 28; var W = VW - ml - mr; var H = VH - mt - mb; var series = []; rssRows.forEach(function (row) { var pm = row.link.match(/\/post\/[^?#]*/); var data = pm ? (pagesByDay[pm[0]] || null) : null; if (data && series.length < 10) { series.push({ title: row.title || row.slug, data: data }); } }); if (!series.length) { return; } var n = series[0].data.length; var allVals = series.reduce(function (acc, s) { return acc.concat(s.data); }, []); var rawMax = Math.max.apply(null, allVals) || 1; var mag = Math.pow(10, Math.floor(Math.log(rawMax) / Math.LN10)); var maxV = Math.ceil(rawMax / mag) * mag; var nTicks = 4; var now = new Date(); var labels = series[0].data.map(function (_, i) { var d = new Date(now); d.setDate(d.getDate() - (n - 1 - i)); return d.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' }); }); function smoothPath(pts) { var d = 'M ' + pts[0].x.toFixed(1) + ' ' + pts[0].y.toFixed(1); for (var i = 0; i < pts.length - 1; i++) { var p0 = pts[i > 0 ? i - 1 : i]; var p1 = pts[i], p2 = pts[i + 1]; var p3 = pts[i + 2 < pts.length ? i + 2 : i + 1]; var t = 0.35; var cp1x = p1.x + t * (p2.x - p0.x) / 2, cp1y = p1.y + t * (p2.y - p0.y) / 2; var cp2x = p2.x - t * (p3.x - p1.x) / 2, cp2y = p2.y - t * (p3.y - p1.y) / 2; d += ' C ' + cp1x.toFixed(1) + ' ' + cp1y.toFixed(1) + ', ' + cp2x.toFixed(1) + ' ' + cp2y.toFixed(1) + ', ' + p2.x.toFixed(1) + ' ' + p2.y.toFixed(1); } return d; } var grid = '', yLabels = ''; for (var t = 0; t <= nTicks; t++) { var val = Math.round(maxV * t / nTicks); var gy = (mt + H - (val / maxV) * H).toFixed(1); grid += ''; yLabels += '' + val + ''; } var xLabels = ''; labels.forEach(function (lbl, i) { if (i % 3 === 0 || i === n - 1) { var x = (ml + i * W / (n - 1)).toFixed(1); xLabels += '' + lbl + ''; } }); var lines = series.map(function (s, si) { var color = COLORS[si % COLORS.length]; var pts = s.data.map(function (v, i) { return { x: ml + i * W / (n - 1), y: mt + H - (v / maxV) * H, v: v, l: labels[i] }; }); var dots = pts.map(function (p) { return '' + esc(p.l) + ' β€” ' + esc(s.title) + ' : ' + p.v + ' vis.' + ''; }).join(''); return '' + dots; }).join(''); var legend = series.map(function (s, si) { var color = COLORS[si % COLORS.length]; return '' + '' + '' + esc(trunc(s.title, 32)) + ''; }).join(''); el.innerHTML = '

Par article β€” 30 derniers jours

' + '' + grid + lines + yLabels + xLabels + '' + '
' + legend + '
'; } fetch('/trending?period=14d') .then(function (r) { return r.ok ? r.text() : Promise.reject(); }) .then(function (xml) { var doc = new DOMParser().parseFromString(xml, 'application/xml'); var items = Array.from(doc.querySelectorAll('item')); if (!items.length) { container.innerHTML = '

Aucune donnΓ©e.

'; return; } var rows = items.map(function (item) { var raw = (item.querySelector('title') || { textContent: '' }).textContent; var link = ((item.querySelector('link') || {}).textContent || '').trim(); var m = raw.match(/\((\d+)\s+visiteurs?\)$/); var vis = m ? parseInt(m[1], 10) : 0; var title = raw.replace(/\s*\(\d+\s+visiteurs?\)$/, ''); var slug = decodeURIComponent(link.replace(/.*\/post\//, '')); 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 nDays = Object.values(pagesByDay)[0] ? Object.values(pagesByDay)[0].length : 30; // Visiteurs uniques par jour β€” comptΓ© sur les IPs du top 200 (approximation) var dailyVisitors = new Array(nDays).fill(0); Object.keys(ipData).forEach(function (ip) { var daily = ipData[ip].daily || []; daily.forEach(function (v, i) { if (i < nDays && v > 0) { dailyVisitors[i]++; } }); }); trendChart(dailyVisitors); multiLineChart(pagesByDay, rows); var html = '
'; rows.forEach(function (row, i) { var vis = row.vis.toLocaleString('fr-FR'); var spk = row.daily ? sparkline(row.daily) : ''; html += '' + '' + '' + '' + '' + ''; }); html += '
' + (i + 1) + '' + esc(row.title || row.slug) + '' + spk + '' + vis + ' vis.
'; if (badge) { badge.textContent = rows.length + ' URLs'; } container.innerHTML = html; }) .catch(function () { container.innerHTML = '

Impossible de charger le flux.

'; }); }());