32 Commits

Author SHA1 Message Date
cedricAbonnel de8785d088 fix : déplacer config mises à jour Folio dans l'onglet Site
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 09:48:40 +02:00
cedricAbonnel 4b5943c0a4 feat : FOLIO_REPO_URL et branche configurables depuis l'admin (dashboard)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 09:48:40 +02:00
cedricAbonnel a552f105cd fix : masquer bouton Vérifier si FOLIO_REPO_URL non configuré, message explicatif
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 09:48:40 +02:00
cedricAbonnel 16afec3039 fix : APP_TIMEZONE configurable (défaut Europe/Paris), FOLIO_REPO_URL dans .env.example
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 09:48:40 +02:00
cedricAbonnel 2d2148079d Merge pull request 'docs: ajouter README avec guide d'installation' (#56) from docs/readme-installation into main
docs: ajouter README avec guide d'installation (v1.4.0)

Fixes #55.
2026-05-15 07:44:28 +00:00
cedricAbonnel 3965be6854 docs : mettre à jour README — DATA_PATH, permissions, setup.sh
- Ajouter DATA_PATH dans le tableau des variables .env avec note prod
- Étape 6 : permissions sur DATA_PATH (hors document root) au lieu de data/
- Étape 7 : référencer $DATA_PATH/site_settings.json
- Mentionner scripts/setup.sh
- Structure : retirer data/ (géré par DATA_PATH), ajouter scripts/

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 09:36:37 +02:00
cedricAbonnel e803d2d0a7 fix : DATA_PATH défini dans config/config.php (manquant à l'exécution)
bootstrap.php ne suffisait pas — index.php, feed.php et sitemap.php passent
par config/config.php. DATA_PATH est maintenant défini là, juste après le
chargement du .env. file.php charge désormais config/config.php.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 09:24:01 +02:00
cedricAbonnel 9069a64a0c Merge pull request 'feat : statistiques admin, livres, setup.sh, permissions rsync (v1.3.0)' (#66) from feat/books into main
feat/books → main
2026-05-15 07:18:49 +00:00
cedricAbonnel 819d6d1b8f chore : ajouter fichiers non versionnés (migrations SQL, 404, PROJET.md)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 09:18:34 +02:00
cedricAbonnel 16965ee8cb feat : DATA_PATH configurable, DataGit auto-commit, UpdateChecker branche (v1.4.0)
- DATA_PATH : chemin /data hors document root, configurable via .env
  (fallback sur BASE_PATH/data si absent)
- DataGit : auto-commit git sur toutes les écritures articles/livres
  (create, update, delete, meta, tags, fichiers, liens…) sauf autosave
- UpdateChecker : getBranch() / getLastChecked() / clearCache(),
  branche configurable via FOLIO_UPDATE_BRANCH (plus de main hardcodé)
- Admin dashboard : affiche la branche suivie, date du dernier contrôle,
  bouton Vérifier pour forcer le check sans attendre le TTL
- CLAUDE.md : architecture DATA_PATH et flux de déploiement documentés

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 09:17:55 +02:00
cedricAbonnel 55a2120be1 chore : CHANGELOG + bump version 1.3.0 (statistiques, permissions, setup.sh)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:53:33 +02:00
cedricAbonnel 8be56bc27f Merge pull request 'feat #64 : onglet Statistiques — pages, livres, répartition AS' (#65) from feat/books into main
Reviewed-on: #65
2026-05-14 22:50:47 +00:00
cedricAbonnel ce70daaa34 Merge pull request 'fix : vérification écriture settings + script setup.sh' (#63) from feat/wizard-multi-step into main
Reviewed-on: #63
2026-05-14 22:50:36 +00:00
cedricAbonnel 8cab6362a3 feat : onglet Statistiques — pages, livres, répartition AS avec groupes configurables
- AccessLogParser : parse COMBINED, agrège hits /post/ et /book/, cache 10 min
- AsnLookup : batch lookup ip-api.com, cache 30j, agrégation et groupes AS
- Onglet Statistiques dans l'admin : top pages, top livres, répartition réseau
- Filtrage par groupe AS (badges) + formulaire de configuration des groupes

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:48:34 +02:00
cedricAbonnel dbd76556fb feat : notion de livre — grouper des pages en série ordonnée
Ajoute un concept de "livre" (série de pages ordonnées) avec :
- BookManager : CRUD JSON dans data/books/<slug>.json
- Route /book/<slug> → page de sommaire (table des matières)
- Navigation chapitre ← → en bas de chaque article membre du livre
- Bandeau "Chapitre X/N — Nom du livre" en haut de l'article
- Admin → onglet Livres : créer, éditer, supprimer un livre, ajouter/ordonner les pages via textarea slug

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:47:41 +02:00
cedricAbonnel 3bb83b3ffd feat : SearchLogParser accepte un pattern glob pour les logs d'accès
Balaye tous les fichiers correspondant au pattern (ex: *-access.log)
et leurs rotations .gz/.tar.gz. Valeur par défaut : *-access.log.
Label renommé en "Pattern des logs d'accès".

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:35:19 +02:00
cedricAbonnel 981c9f6cb3 feat : SearchLogParser supporte tar.gz + config log dans onglet Recherches
- logFiles() utilise glob() au lieu d'un range fixe 1-14
- Support .tar.gz via PharData
- Champ apache_access_log déplacé du tab Site vers un bloc dédié
  dans le tab Recherches (action admin_save_searches_config)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:26:16 +02:00
cedricAbonnel d18f9abd16 feat : log Apache configurable via Administration → Site (apache_access_log)
Ajoute apacheAccessLog() dans SiteSettings — priorité au réglage admin,
fallback sur APACHE_ACCESS_LOG dans .env. Champ ajouté dans le formulaire
Site de l'administration.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:16:49 +02:00
cedricAbonnel d488bcd00c fix : setup.sh — rappel redémarrage PHP-FPM en plus d'Apache pour groupe adm
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:12:31 +02:00
cedricAbonnel 157c30f20c feat : setup.sh — ajout de www-data au groupe adm pour les logs Apache
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:11:51 +02:00
cedricAbonnel fd2397ff90 feat : script setup.sh pour le déploiement initial de Folio
Crée les dossiers requis, applique setgid sur data/ et _cache/ pour
que les fichiers héritent du groupe web (www-data) quelle que soit
leur origine (PHP ou rsync), installe les dépendances et lance les
migrations SQL.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:10:30 +02:00
cedricAbonnel 9091a00a32 fix : saveSiteSettings et saveSmtpSettings retournent bool, erreur affichée
file_put_contents() échouait silencieusement (permissions), provoquant
un saved=1 trompeur. Les deux fonctions retournent maintenant bool ;
les callers redirigent vers ?error=write et le template affiche un
message d'erreur explicite.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:02:54 +02:00
cedricAbonnel 370e1a9062 Merge pull request 'fix #61 : afficher les résultats de recherche au lieu de rediriger vers le 1er' (#62) from feat/wizard-multi-step into main
Reviewed-on: #62
2026-05-14 21:47:29 +00:00
cedricAbonnel d6b75d44e3 chore : version 1.2.2 + CHANGELOG (#61)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 23:47:04 +02:00
cedricAbonnel dbb4684d7c chore : version 1.3.0 + CHANGELOG (#61)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 23:46:32 +02:00
cedricAbonnel edb5f03956 fix #61 : afficher les résultats de recherche au lieu de rediriger vers le 1er
Remplace la redirection 301 vers le premier résultat par une redirection
302 vers /search?q=... pour laisser l'utilisateur choisir parmi les
résultats.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 23:45:24 +02:00
cedricAbonnel 99a7f2e790 Merge pull request 'feat : wizard multi-étapes, migrations contenu, versionnage semver (v1.2.1)' (#60) from feat/wizard-multi-step into main
Reviewed-on: #60
2026-05-14 21:17:19 +00:00
cedricAbonnel 72cb7acae4 fix 1.2.1 : cache index.md, H1 rendu, scroll wizard, titre Modifier
- ArticleManager : invalider le cache si index.md est plus récent que meta.json
- migration_001 : touch(meta.json) après maj index.md pour forcer l'invalidation
- post_view.php : masquer le H1 initial du contenu (déjà affiché par le template)
- step1.php : en-tête "Modifier" sans le titre de l'article
- wizard.js : retirer scrollToCursor (erroné sur auto-resize) ; Ctrl+Home/End via scrollIntoView

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 23:07:15 +02:00
cedricAbonnel 1dbe6d8dd3 feat : versionnage semver, migrations contenu, bandeau mise à jour admin
- CHANGELOG.md : structure semver (1.0.0 / 1.1.0 / 1.2.0) remplace le journal non versionné
- public/version.txt : généré à chaque push depuis la première entrée CHANGELOG
- scripts/push.sh : extrait la version CHANGELOG avant git add
- src/UpdateChecker.php : compare version déployée vs version Gitea (raw file), cache 1 h
- templates/layout.php : bandeau alerte admin (nouvelle version / migrations en attente)
- templates/admin.php : dashboard moteur Folio (version déployée / disponible)
- scripts/migrate_content.php + migration_001 : ajout # titre dans les articles existants
- templates/maintenance.php : page HTTP 503 pendant une migration
- src/helpers.php : extractMarkdownTitle(), normalisation \r\n dans lineDiff()
- templates/wizard/step1.php : suppression champ titre, plan TOC dynamique
- public/assets/js/wizard.js : scope titleEl, scrollToCursor, buildToc, handlers externalisés

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 22:45:35 +02:00
cedricAbonnel 6200444e6d Merge pull request 'feat #58 : wizard multi-étapes création/édition article' (#59) from feat/wizard-multi-step into main
Reviewed-on: #59
2026-05-14 19:50:33 +00:00
cedricAbonnel c503f1dd66 style : formatage PHP-CS-Fixer sur le wizard
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 21:48:33 +02:00
cedricAbonnel 5828aac4f5 docs: ajouter README avec guide d'installation
Couvre prérequis, installation pas-à-pas (clone, .env, BDD, migrations,
vhost Apache/Nginx, permissions), paramètres du site, mise à jour et
structure du projet. Fixes #55.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 09:58:05 +02:00
55 changed files with 2925 additions and 322 deletions
+16
View File
@@ -6,6 +6,7 @@
APP_URL=https://example.com
APP_ENV=prod
APP_DEBUG=0
APP_TIMEZONE=Europe/Paris
# Authentification admin (email de l'administrateur principal)
ADMIN_EMAIL=
@@ -39,3 +40,18 @@ SMTP_FROM_NAME=
# Formulaire de contact
CONTACT_EMAIL=
CONTACT_FROM_EMAIL=
# Dépôt Folio pour le vérificateur de mises à jour (UpdateChecker)
# URL de base du dépôt Gitea (sans slash final)
FOLIO_REPO_URL=https://git.abonnel.fr/cedricAbonnel/folio
# Branche suivie pour les mises à jour (défaut : main)
# FOLIO_UPDATE_BRANCH=main
# Chemin absolu vers le répertoire des articles (data/)
# Par défaut : BASE_PATH/data (dans le répertoire de l'application)
# Recommandé en production : chemin hors du répertoire web, ex. /srv/data/folio
DATA_PATH=/srv/data/folio
# Logs Apache (onglet Recherches dans /admin)
# Nom du fichier de log d'accès du vhost dans /var/log/apache2/
APACHE_ACCESS_LOG=lan.acegrp.varlog-access.log
+1 -1
View File
File diff suppressed because one or more lines are too long
+111 -127
View File
@@ -1,140 +1,124 @@
# Changelog — varlog
# Changelog
## [Unreleased] — 2026-05-13
Toutes les modifications notables sont documentées ici.
Format : [Keep a Changelog](https://keepachangelog.com/fr/1.0.0/) — versionnage [semver](https://semver.org/lang/fr/).
### Performances
---
- **Cache multi-niveaux pour les vues d'articles** : temps de chargement réduit
de +5 s à ~0,4 s sur 1 062 articles.
- Mémoïsation de `getAll()` et `getSearchIndex()` dans la requête PHP
(`$allCache`, `$searchIndexCache`) — évite les appels répétés.
- Cache disque par article (`_cache/articles/{uuid}.json`) avec invalidation
par comparaison `mtime` — 1 lecture au lieu de 2 par article.
- Slug index (`_cache/slug_index.json`) : `getBySlug()` en O(1) sans scanner
tous les articles ; construit depuis `search_index.json` en un seul fichier.
- `getCategories()` et `$_allPublished` chargés depuis `search_index.json`
au lieu de `getAll()` — 1 fichier lu quelle que soit la taille du catalogue.
- `search_index.json` enrichi avec `cover`, `created_at`, `author` ; rebuild
automatique si le format est obsolète.
- `SearchEngine::scorePool()` : tokenise chaque article une seule fois pour
N mots de titre (vs N passes séparées qui retokenisaient chaque article
N fois et calculaient la similarité trigramme sur le contenu).
- Le nombre de lectures de fichiers par vue d'article est désormais constant
(~4), indépendamment du nombre total d'articles.
- Documentation : `docs/cache-architecture.md`.
## [Unreleased]
---
## [1.4.0] - 2026-05-15
### Ajouté
- **`DATA_PATH`** : chemin des articles configurable via `.env`, indépendant du document root — permet de stocker `/data` hors de l'arborescence web (ex. `/srv/data/folio`)
- **`DataGit`** : auto-commit git sur toutes les écritures articles et livres (création, modification, suppression, métadonnées, tags, fichiers, liens…) sauf `autosave` — no-op silencieux si `DATA_PATH` n'est pas un dépôt git
- **Admin — Moteur Folio** : affiche la branche suivie pour les mises à jour (`FOLIO_UPDATE_BRANCH`, défaut `main`), la date du dernier contrôle, et un bouton **Vérifier** pour forcer la vérification sans attendre le TTL du cache (1 h)
### Modifié
- `UpdateChecker` : branche cible configurable via `FOLIO_UPDATE_BRANCH` (plus de `main` hardcodé dans l'URL Gitea)
---
## [1.3.0] - 2026-05-15
### Ajouté
- Onglet **Statistiques** dans l'admin : pages les plus visitées, livres consultés, répartition par AS (#64)
- `AccessLogParser` : lecture des logs Apache (plain, `.gz`, `.tar.gz`), cache 10 min
- `AsnLookup` : résolution ASN via ip-api.com (batch, cache 30 j), détection LAN automatique
- Filtrage des AS par groupes configurables (motifs case-insensitive, formulaire admin)
- Pattern de log configurable via l'UI (onglet Recherches) avec support glob
### Corrigé
- **Upload de fichiers (#48)** : les fichiers > 8 Mo étaient rejetés silencieusement.
Le serveur utilise `mod_php` (non PHP-FPM) ; les limites ont été corrigées dans
`/etc/php/8.3/apache2/php.ini` : `upload_max_filesize = 500M`, `post_max_size = 2048M`.
Le handler `add_files` détecte désormais le dépassement et affiche un message
d'erreur explicite au lieu de rediriger sans rien faire.
### Fonctionnalités
- **Réactions visiteurs** : trois boutons (👍 Utile / 🔥 Important / 🤔 À creuser)
affichés sous chaque article. Toggle : recliquer retire la réaction. Accessible sans
compte via un cookie UUID (`vl_vid`, 1 an, `HttpOnly`). Comportement async fetch avec
fallback formulaire natif (compatible CSP `script-src 'self'`). Routes :
`POST /react`. Table BDD : `article_reactions`.
- **Commentaires avec vérification email** : formulaire nom + email (non publié) +
texte (2 000 caractères max). Protection honeypot + CSRF en session. Un code à
6 chiffres est envoyé par email (expire 24 h) ; le commentaire est auto-publié au clic
sur le lien de confirmation. Routes : `POST /comment`,
`GET /verify-comment/<6chiffres>`. Table BDD : `comments`.
- **Modération commentaires** : onglet **Commentaires** dans `/admin/comments` listant
tous les commentaires avec statut (vérifié / publié) et actions masquer/republier.
Route : `POST /comment-moderate`.
- **Page de confirmation à l'enregistrement** : cliquer sur "Enregistrer" affiche une
page intermédiaire avec le diff du contenu, le slug (déplacé ici depuis le formulaire,
avec suggestion auto si le titre a changé), un commentaire de révision pré-rempli
d'après les modifications détectées, et un aperçu SEO (snippet Google). La
sauvegarde effective n'a lieu qu'après confirmation.
- **URLs propres** : toutes les routes internes migrent vers des chemins lisibles.
Les anciennes URLs `/?action=…` restent fonctionnelles (compatibilité).
| Ancienne URL | Nouvelle URL |
|---|---|
| `/?action=edit&uuid=<u>` | `/edit/<u>` |
| `/?action=sources&uuid=<u>` | `/sources/<u>` |
| `/?action=diff&uuid=<u>&rev=<n>` | `/diff/<u>/<n>` |
| `/?action=create` | `/new` |
| `/?action=admin[&tab=<t>]` | `/admin[/<t>]` |
| `/?action=categories` | `/categories` |
| `/?action=profile` | `/profile` |
| `/?action=about\|legal\|licenses\|contact` | `/about`, `/legal`… |
| `/?action=regen_thumbs` | `/admin/regen-thumbs` |
| `/?action=add_files&uuid=<u>` | `/files/<u>/add` |
| `/?action=import_image&uuid=<u>` | `/import/<u>` |
| `/?cat=<cat>` | `/categorie/<cat>` |
| `/?cursor=<uuid>` | `/page/<uuid>` |
- **Moteur de recherche** : index trigram+substring pré-construit (`search_index.json`,
reconstruit à chaque écriture), accessible depuis la navbar.
### Corrections
- **Métadonnées fichiers (sources)** : `addFileMeta()` ne sauvegardait pas l'auteur et
l'URL source en raison d'un guard `file_exists()` trop strict — supprimé.
- **Authentification OIDC** (`State invalide.`) : `session_start()` était appelé avant
`bootstrap.php` dans les fichiers OIDC, écrasant les paramètres de cookie
(`SameSite=Lax`, `Secure`, `HttpOnly`) — corrigé dans `start.php`, `callback.php`
et `me.php`.
- **Sidebar droite de l'article** : classe Bootstrap `flex-nowrap-lg` inexistante,
remplacée par `flex-lg-nowrap` — la sidebar ne tombe plus en bas de page.
- **Date d'affichage en liste** : `created_at` affiché à la place de `published_at`
— corrigé avec fallback approprié.
- **Formulaire d'édition** : "Fichiers existants" déplacé dans la colonne de droite ;
attribution auteur/source étendue à tous les types de fichiers (pas seulement images).
- **Historique des révisions** : plus de révision créée si le contenu et le titre
sont inchangés. Ajout des boutons de suppression par révision et suppression globale.
- **Canonical URL catégorie** : passe de `/?cat=…` à `/categorie/…`.
- **Flux RSS** : `/rss` et `/rss.xml` redirigent en 301 vers `/feed` (URL
canonique) ; les articles des catégories privées sont exclus du flux ;
la description est convertie depuis Markdown en texte brut.
- Permissions rsync : `--chmod=Fug+rw,Fo-w` assure la lisibilité groupe sur les fichiers déployés
- `saveSiteSettings()` et `saveSmtpSettings()` : retournent un `bool` et affichent une erreur si l'écriture échoue
- `scripts/setup.sh` : script d'initialisation Folio (composer, répertoires, droits, migrations, groupe `adm`)
---
## 2026-05-09
## [1.2.2] - 2026-05-14
### Fonctionnalités
- **SEO** : balises canonical, `sitemap.xml`, `robots.txt`, JSON-LD (`BlogPosting` /
`WebSite`), `noindex` sur les pages d'administration.
- **Recherche** : page de résultats avec score de pertinence, mise en évidence des
termes, lien vers la catégorie depuis les résultats.
- **Support HEIC/HEIF** : conversion automatique en JPEG à l'upload.
- **Support SVG** : upload autorisé, servi avec Content-Type correct.
- **Avant-première** : article visible en liste mais verrouillé avant sa date de
publication.
- **Pagination curseur** : navigation par UUID de dernier article vu, sans offset SQL.
- **Layout article 3 colonnes** : sidebar gauche (catégorie), contenu central,
sidebar droite (pièces jointes, liens externes, articles liés).
- **Import depuis URL** : téléchargement de fichiers distants avec extraction
automatique des métadonnées (EXIF, OpenGraph, PDF).
- **Gestion des pièces jointes** dans le formulaire d'édition, avec attribution
auteur/source affichée dans la vue article.
### Corrections
- Login intégré dans `layout.php`, chemins CSS en absolu.
- Redéclaration de `url()` dans `config.php` — fatal error corrigée.
- Correction permissions `www-data` sur `data/`.
### Corrigé
- URL introuvable : redirige vers la page de recherche (`/search?q=…`) au lieu du premier résultat (#61)
---
## 2026-04 et antérieur
## [1.2.1] - 2026-05-14
- Flux RSS paginé (`/feed`, `/rss`, `/rss.xml`) avec autodiscovery.
- Stockage des articles en fichiers Markdown (migration depuis base de données).
- SSO via Keycloak/OIDC avec PKCE.
- Images de couverture (liste, vue article, `og:image`).
- Brouillons visibles uniquement par l'auteur.
- Formulaire de contact (CSRF, honeypot, rate-limit).
- Pages : mentions légales (LCEN/RGPD), licences, à propos.
- Auto-hébergement Bootstrap 5, police Inter, favicon SVG.
- Headers HTTP de sécurité, CSP stricte.
### Corrigé
- Cache article invalidé si `index.md` est plus récent que `meta.json` (migration de contenu ne se reflétait pas)
- Migration 001 : `touch(meta.json)` après écriture de `index.md` pour invalider le cache
- `post_view.php` : le `# Titre` Markdown est retiré du rendu (déjà affiché par le template)
- Wizard étape 1 : en-tête affiche « Modifier » sans répéter le titre de l'article
- `wizard.js` : suppression de `scrollToCursor` (calcul erroné sur textarea auto-resize) ; Ctrl+Home / Ctrl+End scrollent correctement via `scrollIntoView`
---
## [1.2.0] - 2026-05-14
### Ajouté
- Wizard multi-étapes pour la création (5 écrans) et l'édition (6 écrans) d'articles (#58)
- Auto-sauvegarde en brouillon (debounce 3 s) avec indicateur visible
- Étape tags : champ plat avec détection automatique depuis le texte (abréviations, CamelCase, noms propres)
- Étape SEO : aperçu moteur de recherche en temps réel
- Étape 6 (édition) : diff ligne à ligne avant confirmation
- Plan Markdown dynamique (TOC) dans la colonne droite de l'éditeur
- Titre extrait du premier `# …` du contenu Markdown (plus de champ titre séparé)
- Système de migrations de contenu (`scripts/migrate_content.php`)
- Mode maintenance automatique (`data/.maintenance` → page HTTP 503)
- Migration `001` : ajout du titre Markdown dans les articles existants
- Bouton "Mettre à jour" dans l'administration (sans accès CLI)
- `UpdateChecker` : détection de mise à jour et migrations en attente
- Bandeau d'alerte pour les administrateurs sur toutes les pages
- Dashboard `/admin` : version déployée vs version disponible
### Modifié
- `ArticleManager` : +6 méthodes pour les brouillons overlay
- `lineDiff` : normalisation `\r\n``\n`, seuil relevé à 2 000 000, fallback ligne par ligne
- `push.sh` : génère `public/version.txt` (numéro de version semver) à chaque release
### Corrigé
- Diff étape 6 "violent" (tout supprimé/ajouté) dû aux fins de ligne `\r\n` du navigateur
---
## [1.1.0] - 2026-05-13
### Ajouté
- **Réactions visiteurs** : boutons 👍 / 🔥 / 🤔 sous chaque article, toggle async avec fallback formulaire natif
- **Commentaires avec vérification email** : code 6 chiffres, honeypot + CSRF, modération dans `/admin`
- **URLs propres** : `/edit/<u>`, `/new`, `/admin`, `/categorie/<cat>`, `/files/<u>/add`, `/import/<u>`, etc.
- **Moteur de recherche** : index trigramme+substring pré-construit, résultats scorés avec mise en évidence
### Amélioré
- **Cache multi-niveaux** : chargement réduit de ~5 s à ~0,4 s sur 1 000+ articles (mémoïsation, cache disque, slug index O(1))
- **Upload fichiers** : détection et message d'erreur explicite pour les fichiers > limite PHP
### Corrigé
- Métadonnées fichiers (`addFileMeta`) : guard `file_exists()` trop strict supprimé
- Sidebar droite article : classe Bootstrap `flex-nowrap-lg``flex-lg-nowrap`
- Flux RSS : exclusion catégories privées, redirection 301 `/rss``/feed`
---
## [1.0.0] - 2026-05-09
### Ajouté
- Moteur de blog PHP Folio — première release versionnée
- Articles en Markdown avec fichiers attachés, liens externes, images de couverture
- Authentification par lien magique envoyé par email (#29)
- SSO via Keycloak/OIDC avec PKCE
- Rôles, capacités et gestion des utilisateurs
- Catégories avec swatches couleur générées algorithmiquement
- Tags par type avec suggestions
- SEO : canonical, `sitemap.xml`, `robots.txt`, JSON-LD, `og:image`
- Avant-premières (articles futurs visibles aux utilisateurs autorisés)
- Pagination curseur (sans offset SQL)
- Import depuis URL (EXIF, OpenGraph, PDF)
- Historique des révisions avec diff
- Flux RSS (`/feed`) paginé avec autodiscovery
- Formulaire de contact (CSRF, honeypot, rate-limit)
- Pages légales (LCEN/RGPD), licences, à propos
- Migrations SQL versionnées (`database/migrate.php`)
- Système de déploiement par rsync
+62
View File
@@ -0,0 +1,62 @@
# CLAUDE.md
## Ce qu'est ce dépôt
**Folio** est un moteur de blog PHP.
Ce répertoire est la **copie locale du dépôt Git** (`https://git.abonnel.fr/cedricAbonnel/folio`), branche DEV.
Il contient uniquement le code du moteur — pas de données, pas de credentials.
## Architecture
| Répertoire local | Site distant | Rôle |
|-----------------|-------------|------|
| `~/Projects/folio/` | — | Copie du dépôt Folio (branche DEV). On code ici. |
| `~/Projects/varlog/` | varlog.a5l.fr | Sync bidirectionnelle des articles varlog. Sert de site de test pour le moteur. |
| `~/Projects/fr.abonnel.www/` | www.abonnel.fr | Sync bidirectionnelle des articles abonnel.fr. A aussi servi au déploiement initial. |
**abonnel.fr** utilise Folio mais se met à jour seul via son UpdateChecker interne (vérifie `version.txt` sur Gitea). Aucune action manuelle nécessaire côté serveur.
## Articles (`data/`)
Les articles ne sont pas versionnés dans ce dépôt. Ils ont leur propre git local dans chaque workspace site (`~/Projects/varlog/data/`, `~/Projects/fr.abonnel.www/data/`), synchronisé de façon bidirectionnelle avec le serveur distant.
## Modifier le moteur
Pour toute correction ou fonctionnalité : **créer un ticket et une PR**.
1. Coder ici dans `~/Projects/folio/` (branche feature)
2. **Tester sur varlog.a5l.fr** :
```bash
~/Projects/varlog/scripts/sync.sh
# puis tester sur http://varlog.acegrp.lan
```
3. Une fois validé, ouvrir une PR sur Gitea. Le commit doit inclure :
- `public/version.txt` (bump semver)
- `CHANGELOG.md` (entrée `### Ajouté / Corrigé / Modifié`)
4. Merger la PR → abonnel.fr se met à jour automatiquement.
## Données articles (`DATA_PATH`)
Les articles sont stockés dans un répertoire **hors du dépôt Folio**, configurable via `DATA_PATH` dans `.env`.
| Environnement | Chemin local | Chemin serveur |
|--------------|-------------|----------------|
| varlog | `~/Projects/varlog-data/` | `/srv/data/folio` |
| abonnel.fr | `~/Projects/fr.abonnel.www-data/` | `/srv/data/folio` |
Les scripts de sync (`pull-data.sh`, `push-data.sh`, `sync.sh`) utilisent `DATA_DIR` (overridable via env) pointant vers ces chemins locaux.
## Asymétrie de déploiement moteur
| Site | Mécanisme | Raison |
|------|-----------|--------|
| varlog (test) | rsync depuis `~/Projects/folio/` | Itération rapide, pas de contrainte de stabilité |
| abonnel.fr (prod) | `git pull origin main` sur le serveur | Contrôle via PR/merge, UpdateChecker autonome |
Pour initialiser git sur un serveur abonnel.fr déployé via rsync : `scripts/git-init-remote.sh`
## Ne pas mettre ici
- `.env` (credentials → dans chaque workspace site)
- `data/` (articles → dans chaque workspace site)
- `vendor/` (non versionné)
+69
View File
@@ -0,0 +1,69 @@
# FOLIO
Moteur de blog PHP — utilisé par plusieurs sites.
## Dépôt
`https://git.abonnel.fr/cedricAbonnel/folio` — branche `main`
## Sites utilisant Folio
| Site | Workspace local | Serveur |
|---|---|---|
| varlog.a5l.fr | `~/Projects/varlog/` | `ssh varlog` |
| www.abonnel.fr | `~/Projects/fr.abonnel.www/` | `ssh abonnel-wiki` |
## Structure du moteur
```
folio/
├── src/ Classes PHP (ArticleManager, PostManager, auth…)
├── public/ Point d'entrée web (index.php, route.php, assets/)
├── templates/ Vues PHP (layout, header, footer, post_*)
├── config/ Configuration (config.php)
├── database/ Schéma SQL + migrate.php
├── composer.json
└── CHANGELOG.md
```
## Workflow de modification du moteur
### 1. Développement et test sur varlog.a5l.fr
Modifier le code ici dans `~/Projects/folio/`, tester sur **varlog.a5l.fr** :
```bash
# Déployer sur varlog pour test
~/Projects/varlog/scripts/sync.sh
# Tester sur http://varlog.acegrp.lan (ou https://varlog.a5l.fr)
```
### 2. Validation
Une fois validé sur varlog.a5l.fr :
```bash
# Commiter sur le serveur varlog (git de déploiement)
~/Projects/varlog/scripts/commit.sh "description du changement"
```
### 3. Push vers le dépôt Folio
Pousser le code validé vers le dépôt canonique Folio :
```bash
cd ~/Projects/folio
./scripts/push.sh "description du changement"
```
### 4. Déployer sur les autres sites si nécessaire
```bash
~/Projects/fr.abonnel.www/scripts/sync.sh
~/Projects/fr.abonnel.www/scripts/commit.sh "même message"
```
## Credentials locaux
Aucun credential dans folio/ — les `.env` sont dans chaque workspace site.
+158
View File
@@ -0,0 +1,158 @@
# Folio
Moteur de blog PHP minimaliste — articles Markdown, authentification SSO (OIDC) ou lien magique, commentaires, recherche, flux RSS.
---
## Prérequis
- PHP ≥ 8.2 avec les extensions `pdo`, `pdo_pgsql`, `mbstring`, `openssl`
- PostgreSQL ≥ 14
- Composer
- Apache avec `mod_rewrite` (ou Nginx — voir ci-dessous)
## Installation
### 1. Cloner et installer les dépendances
```bash
git clone https://git.abonnel.fr/cedricAbonnel/folio mon-site
cd mon-site
composer install --no-dev
```
### 2. Configurer l'environnement
```bash
cp .env.example .env
```
Remplir les valeurs dans `.env` :
| Variable | Description |
|---|---|
| `APP_URL` | URL publique du site (`https://example.com`) |
| `ADMIN_EMAIL` | Email de l'administrateur principal |
| `SESSION_NAME` | Nom du cookie de session — doit être unique par instance |
| `DATA_PATH` | Chemin absolu vers le répertoire des articles (ex. `/srv/data/mon-site`). Par défaut : `<racine>/data` |
| `OIDC_ISSUER` / `OIDC_CLIENT_ID` / `OIDC_CLIENT_SECRET` | SSO OpenID Connect |
| `DB_DSN` / `DB_USER` / `DB_PASS` | Connexion PostgreSQL |
| `SMTP_*` | Serveur email sortant (commentaires, contact, lien magique) |
| `CONTACT_EMAIL` | Destinataire du formulaire de contact |
> En production, placer `DATA_PATH` **hors du document root** (ex. `/srv/data/mon-site`) pour que les articles ne soient pas accessibles directement via le serveur web.
### 3. Créer la base de données
```bash
createdb monsite
```
### 4. Initialiser le schéma et jouer les migrations
```bash
php database/migrate.php
```
Ce script crée toutes les tables et applique les migrations dans l'ordre. À relancer après chaque mise à jour.
### 5. Configurer le vhost Apache
```apache
<VirtualHost *:443>
ServerName example.com
DocumentRoot /var/www/mon-site/public
<Directory /var/www/mon-site/public>
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
```
Le fichier `public/.htaccess` gère le routage via `mod_rewrite`. `AllowOverride All` est requis.
<details>
<summary>Nginx</summary>
```nginx
server {
listen 443 ssl;
server_name example.com;
root /var/www/mon-site/public;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
}
```
</details>
### 6. Permissions fichiers
```bash
# Répertoire des articles
mkdir -p /srv/data/mon-site
chown -R www-data:www-data /srv/data/mon-site
# .env lisible par www-data uniquement
chown user:www-data .env
chmod 640 .env
```
PHP-FPM tourne en `www-data`. Le `.env` doit être lisible par `www-data` mais pas par les autres.
> Le script `scripts/setup.sh` automatise la vérification des prérequis, la création des répertoires et les droits.
### 7. Paramètres du site
Au premier lancement, se connecter en tant qu'admin et aller dans **Administration → Paramètres du site** pour définir le titre, le claim, la langue et la licence.
Ou créer directement `$DATA_PATH/site_settings.json` :
```json
{
"site_title": "Mon site",
"site_claim": "Un blog propulsé par Folio",
"site_lang": "fr-FR",
"site_license_label": "CC BY 4.0",
"site_license_url": "https://creativecommons.org/licenses/by/4.0/",
"posts_per_page": 12
}
```
---
## Mise à jour
```bash
git pull
composer install --no-dev
php database/migrate.php
```
## Structure du projet
```
├── config/ Configuration (charge .env, définit APP_URL et DATA_PATH)
├── database/ Schéma SQL et runner de migrations
├── docs/ Documentation technique
├── public/ Racine web (index.php, assets, .htaccess)
├── scripts/ Scripts utilitaires (setup.sh, migrations de contenu)
├── src/ Code applicatif
└── templates/ Vues PHP
```
Les articles sont stockés dans `DATA_PATH` (hors dépôt git).
## Licence
[MIT](LICENSE)
+10
View File
@@ -6,6 +6,16 @@ if (!defined('BASE_PATH')) {
define('BASE_PATH', __DIR__);
}
$__tz = $_ENV['APP_TIMEZONE'] ?? getenv('APP_TIMEZONE') ?: 'Europe/Paris';
date_default_timezone_set($__tz);
unset($__tz);
if (!defined('DATA_PATH')) {
$__dataPath = $_ENV['DATA_PATH'] ?? getenv('DATA_PATH') ?: '';
define('DATA_PATH', $__dataPath !== '' ? rtrim($__dataPath, '/') : BASE_PATH . '/data');
unset($__dataPath);
}
if (session_status() === PHP_SESSION_NONE) {
$isHttps = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
$sessionName = $_ENV['SESSION_NAME'] ?? (getenv('SESSION_NAME') ?: null);
+6
View File
@@ -20,6 +20,12 @@ if (!$_ENV['APP_URL']) {
// Normalise: toujours un trailing slash unique
define('APP_URL', rtrim($_ENV['APP_URL'], '/') . '/');
if (!defined('DATA_PATH')) {
$__dp = $_ENV['DATA_PATH'] ?? getenv('DATA_PATH') ?: '';
define('DATA_PATH', $__dp !== '' ? rtrim($__dp, '/') : BASE_PATH . '/data');
unset($__dp);
}
// (Optionnel) Expose dans $_ENV si besoin
$_ENV['APP_URL'] = APP_URL;
+49
View File
@@ -0,0 +1,49 @@
-- Schéma initial : tables créées avant la mise en place du système de migrations.
-- Remplace tables_create.sql et interactions_create.sql.
CREATE TABLE IF NOT EXISTS posts (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
content TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP,
is_published BOOLEAN DEFAULT FALSE
);
CREATE TABLE IF NOT EXISTS post_files (
id SERIAL PRIMARY KEY,
post_id INTEGER REFERENCES posts(id) ON DELETE CASCADE,
file_type TEXT,
file_path TEXT,
original_name TEXT,
uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS article_reactions (
id SERIAL PRIMARY KEY,
article_uuid TEXT NOT NULL,
reaction_type TEXT NOT NULL CHECK (reaction_type IN ('useful', 'important', 'interesting')),
visitor_hash TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
UNIQUE (article_uuid, reaction_type, visitor_hash)
);
CREATE INDEX IF NOT EXISTS article_reactions_article_uuid_idx ON article_reactions (article_uuid);
CREATE TABLE IF NOT EXISTS comments (
id SERIAL PRIMARY KEY,
article_uuid TEXT NOT NULL,
author_name TEXT NOT NULL,
author_email TEXT NOT NULL,
content TEXT NOT NULL CHECK (LENGTH(content) <= 2000),
verify_token TEXT,
verification_code TEXT,
verify_attempts INTEGER NOT NULL DEFAULT 0,
verified BOOLEAN NOT NULL DEFAULT FALSE,
published BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
ip_address TEXT,
user_agent TEXT
);
CREATE INDEX IF NOT EXISTS comments_article_uuid_idx ON comments (article_uuid, verified, published);
CREATE INDEX IF NOT EXISTS comments_verify_token_idx ON comments (verify_token)
WHERE verified = FALSE AND verify_token IS NOT NULL;
+10
View File
@@ -0,0 +1,10 @@
CREATE TABLE IF NOT EXISTS user_profiles (
email TEXT NOT NULL PRIMARY KEY,
display_name TEXT NOT NULL DEFAULT '',
updated_at TIMESTAMP DEFAULT now(),
profile_url TEXT NOT NULL DEFAULT '',
profile_slug TEXT NOT NULL DEFAULT '',
bio TEXT NOT NULL DEFAULT ''
);
CREATE UNIQUE INDEX IF NOT EXISTS user_profiles_profile_slug_idx
ON user_profiles (profile_slug) WHERE profile_slug <> '';
+16
View File
@@ -0,0 +1,16 @@
CREATE TABLE IF NOT EXISTS journal_smtp (
id SERIAL PRIMARY KEY,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
script_path VARCHAR(512),
to_email VARCHAR(255) NOT NULL,
subject VARCHAR(512),
content_html TEXT,
content_text TEXT,
status VARCHAR(20) NOT NULL DEFAULT 'queued',
ip VARCHAR(128),
user_agent VARCHAR(512),
error_message VARCHAR(1000),
sent_at TIMESTAMP WITH TIME ZONE
);
CREATE INDEX IF NOT EXISTS idx_journal_smtp_created_at ON journal_smtp (created_at DESC);
CREATE INDEX IF NOT EXISTS idx_journal_smtp_to_email ON journal_smtp (to_email);
@@ -0,0 +1,5 @@
CREATE TABLE IF NOT EXISTS role_capabilities (
role_id INTEGER NOT NULL REFERENCES roles(id) ON DELETE CASCADE,
capability VARCHAR(50) NOT NULL,
PRIMARY KEY (role_id, capability)
);
@@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS user_capabilities (
user_email TEXT NOT NULL,
capability TEXT NOT NULL,
granted_by TEXT,
granted_at TIMESTAMP WITH TIME ZONE DEFAULT now(),
PRIMARY KEY (user_email, capability)
);
+8
View File
@@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
updated_at TIMESTAMP,
password_changed_at TIMESTAMP
);
+9
View File
@@ -0,0 +1,9 @@
CREATE TABLE IF NOT EXISTS profiles (
id SERIAL PRIMARY KEY,
slug TEXT NOT NULL UNIQUE,
label TEXT NOT NULL DEFAULT '',
description TEXT,
permissions JSONB NOT NULL DEFAULT '[]',
is_system BOOLEAN NOT NULL DEFAULT FALSE,
is_active BOOLEAN NOT NULL DEFAULT TRUE
);
+13
View File
@@ -0,0 +1,13 @@
CREATE TABLE IF NOT EXISTS app_config (
id INTEGER PRIMARY KEY DEFAULT 1,
allow_password BOOLEAN NOT NULL DEFAULT TRUE,
allow_oidc BOOLEAN NOT NULL DEFAULT FALSE,
registrations_open BOOLEAN NOT NULL DEFAULT TRUE,
oidc_issuer TEXT,
oidc_name TEXT,
oidc_client_id TEXT,
oidc_client_secret TEXT,
oidc_redirect_uri TEXT,
updated_at TIMESTAMP,
CONSTRAINT app_config_single_row CHECK (id = 1)
);
+15
View File
@@ -0,0 +1,15 @@
CREATE TABLE IF NOT EXISTS mail_queue (
id SERIAL PRIMARY KEY,
to_email TEXT NOT NULL,
subject TEXT NOT NULL,
body TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
attempts INTEGER NOT NULL DEFAULT 0,
available_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
locked_at TIMESTAMP WITH TIME ZONE,
last_error TEXT,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_mail_queue_pending
ON mail_queue (available_at ASC, id ASC)
WHERE status = 'pending';
+44
View File
@@ -0,0 +1,44 @@
-- Tables du dictionnaire de données (formulaires dynamiques)
CREATE TABLE IF NOT EXISTS dd_entities (
id SERIAL PRIMARY KEY,
code TEXT NOT NULL UNIQUE,
label TEXT NOT NULL DEFAULT '',
is_active BOOLEAN NOT NULL DEFAULT TRUE
);
CREATE TABLE IF NOT EXISTS dd_fields (
id SERIAL PRIMARY KEY,
entity_id INTEGER NOT NULL REFERENCES dd_entities(id) ON DELETE CASCADE,
code TEXT NOT NULL,
label TEXT NOT NULL DEFAULT '',
field_type TEXT NOT NULL DEFAULT 'text',
ui_order INTEGER,
is_required BOOLEAN NOT NULL DEFAULT FALSE,
default_val TEXT,
UNIQUE (entity_id, code)
);
CREATE TABLE IF NOT EXISTS dd_rules (
id SERIAL PRIMARY KEY,
entity_id INTEGER NOT NULL REFERENCES dd_entities(id) ON DELETE CASCADE,
rule_type TEXT NOT NULL,
expression TEXT,
message TEXT,
active BOOLEAN NOT NULL DEFAULT TRUE
);
CREATE TABLE IF NOT EXISTS dd_enums (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL UNIQUE
);
CREATE TABLE IF NOT EXISTS dd_enum_values (
id SERIAL PRIMARY KEY,
enum_id INTEGER NOT NULL REFERENCES dd_enums(id) ON DELETE CASCADE,
code TEXT NOT NULL,
label TEXT NOT NULL DEFAULT '',
active BOOLEAN NOT NULL DEFAULT TRUE,
sort_order INTEGER NOT NULL DEFAULT 0,
UNIQUE (enum_id, code)
);
+1
View File
@@ -3,3 +3,4 @@
declare(strict_types=1);
define('BASE_PATH', __DIR__);
define('DATA_PATH', BASE_PATH . '/data');
+3
View File
@@ -15,6 +15,9 @@ RewriteRule ^ - [L]
# URL propre pour les articles : /post/<slug>
RewriteRule ^post/([a-z0-9][a-z0-9-]*)/?$ /index.php?action=view&slug=$1 [L,QSA]
# Livres : /book/<slug>
RewriteRule ^book/([a-z0-9][a-z0-9-]*)/?$ /index.php?action=book&book_slug=$1 [L,QSA]
# Filtre par catégorie : /categorie/<nom>
RewriteRule ^categorie/(.+?)/?$ /index.php?cat=$1 [L,QSA,B]
+168
View File
@@ -1807,3 +1807,171 @@ footer.mt-5 { margin-top: 0 !important; }
color: var(--vl-muted);
margin-top: 0.15rem;
}
/* ─── Livres ─────────────────────────────────────────────────────── */
/* Bandeau dans un article appartenant à un livre */
.book-article-banner {
border-radius: var(--vl-radius);
background: var(--vl-accent-soft);
border: 1px solid rgba(79,70,229,.18);
overflow: hidden;
}
.book-article-banner-link {
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.6rem 1rem;
text-decoration: none;
color: var(--vl-accent);
transition: background 0.15s;
}
.book-article-banner-link:hover {
background: rgba(79,70,229,.08);
color: var(--vl-accent-dark);
}
.book-article-banner-icon { font-size: 1.1rem; flex-shrink: 0; }
.book-article-banner-text { flex: 1; font-size: 0.875rem; }
.book-article-banner-cta { font-size: 0.8rem; opacity: .75; white-space: nowrap; }
/* Navigation précédent/suivant en bas d'article */
.book-chapter-nav {
border-top: 1px solid var(--vl-border);
margin-top: 1.5rem;
padding-top: 1rem;
}
.book-chapter-nav-inner {
display: flex;
gap: 0.75rem;
align-items: stretch;
}
.book-nav-btn {
flex: 1;
display: flex;
flex-direction: column;
padding: 0.65rem 0.875rem;
background: var(--vl-surface);
border: 1px solid var(--vl-border);
border-radius: var(--vl-radius);
text-decoration: none;
color: var(--vl-text);
transition: border-color 0.15s, box-shadow 0.15s;
min-width: 0;
}
.book-nav-btn:hover {
border-color: var(--vl-accent);
box-shadow: var(--vl-shadow-sm);
color: var(--vl-text);
}
.book-nav-btn--disabled {
opacity: .45;
cursor: default;
pointer-events: none;
}
.book-nav-btn--next { text-align: right; }
.book-nav-dir {
font-size: 0.72rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: .04em;
color: var(--vl-muted);
display: block;
}
.book-nav-title {
font-size: 0.875rem;
font-weight: 500;
display: block;
margin-top: 0.15rem;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.book-nav-toc {
display: flex;
align-items: center;
justify-content: center;
padding: 0.5rem 0.75rem;
border: 1px solid var(--vl-border);
border-radius: var(--vl-radius);
color: var(--vl-muted);
text-decoration: none;
font-size: 1.1rem;
transition: border-color 0.15s, color 0.15s;
flex-shrink: 0;
}
.book-nav-toc:hover {
border-color: var(--vl-accent);
color: var(--vl-accent);
}
/* Page sommaire d'un livre (/book/<slug>) */
.book-page { max-width: 720px; margin: 0 auto; padding: 2rem 0; }
.book-label {
font-size: 0.75rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: .08em;
color: var(--vl-accent);
}
.book-chapters {
list-style: none;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.book-chapter-link {
display: flex;
align-items: center;
gap: 0.875rem;
padding: 0.75rem 1rem;
background: var(--vl-surface);
border: 1px solid var(--vl-border);
border-radius: var(--vl-radius);
text-decoration: none;
color: var(--vl-text);
transition: border-color 0.15s, box-shadow 0.15s;
}
.book-chapter-link:hover {
border-color: var(--vl-accent);
box-shadow: var(--vl-shadow-sm);
color: var(--vl-text);
}
.book-chapter-num {
width: 1.75rem;
height: 1.75rem;
display: flex;
align-items: center;
justify-content: center;
background: var(--vl-accent-soft);
color: var(--vl-accent);
border-radius: 50%;
font-size: 0.8rem;
font-weight: 700;
flex-shrink: 0;
}
.book-chapter-thumb {
width: 56px;
height: 44px;
border-radius: 6px;
flex-shrink: 0;
background: var(--vl-accent-soft);
background-size: cover;
background-position: center;
}
.book-chapter-body { flex: 1; min-width: 0; }
.book-chapter-title {
font-size: 0.9375rem;
font-weight: 600;
line-height: 1.3;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.book-chapter-meta {
font-size: 0.78rem;
color: var(--vl-muted);
margin-top: 0.15rem;
}
+17 -53
View File
@@ -13,20 +13,13 @@ document.addEventListener('DOMContentLoaded', function () {
ta.addEventListener('input', resizeTa);
resizeTa();
function scrollToCursor() {
var lineH = parseFloat(getComputedStyle(ta).lineHeight) || 20;
var padT = parseFloat(getComputedStyle(ta).paddingTop) || 8;
var lines = ta.value.substr(0, ta.selectionStart).split('\n').length;
var cursorY = ta.getBoundingClientRect().top + padT + lines * lineH;
var margin = lineH * 3;
if (cursorY > window.innerHeight - margin) {
window.scrollBy({ top: cursorY - window.innerHeight + margin, behavior: 'instant' });
} else if (cursorY < margin) {
window.scrollBy({ top: cursorY - margin, behavior: 'instant' });
}
}
ta.addEventListener('keyup', scrollToCursor);
ta.addEventListener('click', scrollToCursor);
// Ctrl+Home / Ctrl+End : scroller la fenêtre vers le début/fin du textarea
ta.addEventListener('keydown', function (e) {
if (!(e.ctrlKey || e.metaKey) || (e.key !== 'Home' && e.key !== 'End')) return;
requestAnimationFrame(function () {
ta.scrollIntoView({ block: e.key === 'Home' ? 'start' : 'end', behavior: 'smooth' });
});
});
}
// ─── Ctrl+Enter soumet le formulaire ────────────────────────────────────
@@ -37,40 +30,12 @@ document.addEventListener('DOMContentLoaded', function () {
});
}
// ─── Génération slug automatique (étape 1 / création) ───────────────────
var titleInput = document.getElementById('wz-title');
var slugField = document.getElementById('slug');
var slugPreview = document.getElementById('slug-preview');
function slugify(s) {
var map = {'à':'a','â':'a','ä':'a','é':'e','è':'e','ê':'e','ë':'e','î':'i','ï':'i','ô':'o','ö':'o','ù':'u','û':'u','ü':'u','ç':'c','æ':'ae','œ':'oe'};
return s.toLowerCase()
.replace(/[àâäéèêëîïôöùûüçæœ]/g, function(c) { return map[c] || c; })
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
}
if (titleInput && slugField) {
if (slugField.value !== '') slugField._auto = false;
titleInput.addEventListener('input', function () {
if (slugField._auto !== false) {
var gen = slugify(this.value);
slugField.value = gen;
if (slugPreview) slugPreview.textContent = gen;
}
});
slugField.addEventListener('input', function () {
this._auto = (this.value === '');
if (slugPreview) slugPreview.textContent = this.value;
});
}
var slugField = document.getElementById('slug');
// ─── Autosave ────────────────────────────────────────────────────────────
var indicator = document.getElementById('autosave-indicator');
if (indicator && uuid && autosaveUrl) {
var timer = null;
var titleEl = document.getElementById('wz-title');
var contentEl = document.getElementById('wz-content');
var timer = null;
function scheduleAutosave() {
clearTimeout(timer);
@@ -78,27 +43,26 @@ document.addEventListener('DOMContentLoaded', function () {
}
async function doAutosave() {
if (!titleEl || !contentEl) return;
if (!ta) return;
indicator.textContent = 'Sauvegarde…';
try {
var res = await fetch(autosaveUrl, {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({
title: titleEl.value,
content: contentEl.value,
slug: slugField ? slugField.value : '',
}),
body: new URLSearchParams({ content: ta.value }),
});
var data = await res.json();
indicator.textContent = data.ok ? 'Brouillon sauvegardé à ' + data.time : 'Erreur de sauvegarde';
if (data.ok) {
indicator.textContent = 'Sauvegardé à ' + data.time;
} else {
indicator.textContent = 'Erreur de sauvegarde';
}
} catch (err) {
indicator.textContent = 'Erreur de sauvegarde';
}
}
if (titleEl) titleEl.addEventListener('input', scheduleAutosave);
if (ta) ta.addEventListener('input', scheduleAutosave);
if (ta) ta.addEventListener('input', scheduleAutosave);
}
// ─── Insertion Markdown depuis miniatures ────────────────────────────────
+1 -1
View File
@@ -12,7 +12,7 @@ require_once BASE_PATH . '/src/Parsedown.php';
const FEED_PAGE_SIZE = 20;
$articles = new ArticleManager(BASE_PATH . '/data');
$articles = new ArticleManager(DATA_PATH);
$privateCats = $articles->getPrivateCategories();
$Parsedown = new Parsedown();
+4 -1
View File
@@ -4,6 +4,9 @@ declare(strict_types=1);
define('BASE_PATH', realpath(__DIR__ . '/../'));
require_once BASE_PATH . '/vendor/autoload.php';
require_once BASE_PATH . '/config/config.php';
$uuid = $_GET['uuid'] ?? '';
$name = $_GET['name'] ?? '';
@@ -20,7 +23,7 @@ if ($name === '' || $name[0] === '.') {
exit;
}
$path = BASE_PATH . '/data/' . $uuid . '/files/' . $name;
$path = DATA_PATH . '/' . $uuid . '/files/' . $name;
if (!is_file($path)) {
http_response_code(404);
+310 -70
View File
@@ -23,14 +23,29 @@ require_once BASE_PATH . '/src/helpers.php';
require_once BASE_PATH . '/src/auth.php';
require_once BASE_PATH . '/src/SiteSettings.php';
require_once BASE_PATH . '/src/ArticleManager.php';
require_once BASE_PATH . '/src/BookManager.php';
require_once BASE_PATH . '/src/DataGit.php';
$articles = new ArticleManager(BASE_PATH . '/data');
$_dataGit = new DataGit(DATA_PATH);
$articles = new ArticleManager(DATA_PATH, $_dataGit);
$books = new BookManager(DATA_PATH . '/books', $_dataGit);
// ─── Mode maintenance ──────────────────────────────────────────────────────
if (file_exists(DATA_PATH . '/.maintenance')) {
http_response_code(503);
header('Retry-After: 60');
include BASE_PATH . '/templates/maintenance.php';
exit;
}
require_once BASE_PATH . '/src/UpdateChecker.php';
$_updateChecker = new UpdateChecker(DATA_PATH, BASE_PATH);
$action = $_GET['action'] ?? 'list';
$uuid = $_GET['uuid'] ?? '';
$slug = $_GET['slug'] ?? '';
$_noindexActions = ['create', 'edit', 'admin', 'categories', 'diff', 'add_files', 'import_image', 'import_image_step2', 'sources', 'profile', 'delete_file', 'delete_external_link', 'rename_category', 'delete_category', 'toggle_private_category', 'admin_save_site', 'not_found', 'add_feed', 'delete_feed', 'add_link', 'delete_link', 'reorder_links', 'react', 'comment', 'verify_comment', 'comment_moderate', 'comment_delete', 'comment_resend', 'create_tag_type', 'delete_tag_type', 'edit_tags'];
$_noindexActions = ['create', 'edit', 'admin', 'categories', 'diff', 'add_files', 'import_image', 'import_image_step2', 'sources', 'profile', 'delete_file', 'delete_external_link', 'rename_category', 'delete_category', 'toggle_private_category', 'admin_save_site', 'not_found', 'add_feed', 'delete_feed', 'add_link', 'delete_link', 'reorder_links', 'react', 'comment', 'verify_comment', 'comment_moderate', 'comment_delete', 'comment_resend', 'create_tag_type', 'delete_tag_type', 'edit_tags', 'book_save', 'book_delete', 'admin_save_as_groups', 'admin_save_folio_config'];
$metaRobots = in_array($action, $_noindexActions, true) ? 'noindex, nofollow' : null;
unset($_noindexActions);
@@ -57,7 +72,7 @@ function searchAndRedirect(string $rawPath, ArticleManager $articles): void
));
$results = (new SearchEngine())->search($query, $pool);
if (!empty($results)) {
header('Location: /post/' . rawurlencode($results[0]['article']['slug'] ?? ''), true, 301);
header('Location: /search?q=' . urlencode($query), true, 302);
exit;
}
}
@@ -65,7 +80,7 @@ function searchAndRedirect(string $rawPath, ArticleManager $articles): void
// ─── Pages statiques depuis data/site/ ──────────────────────────────────────
function loadSitePageData(string $slug): array
{
$base = BASE_PATH . '/data/site';
$base = DATA_PATH . '/site';
$meta = [];
$raw = @file_get_contents($base . '/' . $slug . '.json');
if ($raw !== false) {
@@ -512,28 +527,24 @@ switch ($action) {
case 1:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$title = trim($_POST['title'] ?? '');
$content = $_POST['content'] ?? '';
$content = str_replace("\r\n", "\n", $_POST['content'] ?? '');
$title = extractMarkdownTitle($content) ?: ($draft['title'] ?? 'Sans titre');
$postSlug = trim($_POST['slug'] ?? '');
if ($title === '') {
$errors[] = 'Le titre est obligatoire.';
} else {
if ($draft === null) {
$uuid = $articles->create($title, $content, false, $postSlug, date('Y-m-d H:i:s'), currentUserEmail() ?? '', '', '', '', '', []);
foreach ($_FILES['files']['tmp_name'] ?? [] as $_fi => $_tmpName) {
if ($_FILES['files']['error'][$_fi] === UPLOAD_ERR_OK) {
$articles->addFile($uuid, ['name' => $_FILES['files']['name'][$_fi], 'tmp_name' => $_tmpName, 'error' => UPLOAD_ERR_OK]);
}
if ($draft === null) {
$uuid = $articles->create($title, $content, false, $postSlug, date('Y-m-d H:i:s'), currentUserEmail() ?? '', '', '', '', '', []);
foreach ($_FILES['files']['tmp_name'] ?? [] as $_fi => $_tmpName) {
if ($_FILES['files']['error'][$_fi] === UPLOAD_ERR_OK) {
$articles->addFile($uuid, ['name' => $_FILES['files']['name'][$_fi], 'tmp_name' => $_tmpName, 'error' => UPLOAD_ERR_OK]);
}
$_SESSION['wizard_create'] = $uuid;
} else {
$articles->autosave($uuid, $title, $content, $postSlug);
}
header('Location: /new/' . rawurlencode($uuid) . '/2');
exit;
$_SESSION['wizard_create'] = $uuid;
} else {
$articles->autosave($uuid, $title, $content, $postSlug);
}
header('Location: /new/' . rawurlencode($uuid) . '/2');
exit;
}
$title = $draft['title'] ?? ($_POST['title'] ?? '');
$title = $draft['title'] ?? '';
$content = $draft['content'] ?? '';
$postSlug = $draft['slug'] ?? '';
$existingFiles = $uuid !== '' ? $articles->getFiles($uuid) : [];
@@ -544,7 +555,10 @@ switch ($action) {
break;
case 2:
if ($draft === null) { header('Location: /new'); exit; }
if ($draft === null) {
header('Location: /new');
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$articles->updatePartialMeta($uuid, [
'published' => isset($_POST['published']) && $_POST['published'] !== '',
@@ -559,7 +573,10 @@ switch ($action) {
break;
case 3:
if ($draft === null) { header('Location: /new'); exit; }
if ($draft === null) {
header('Location: /new');
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$articles->updatePartialMeta($uuid, ['category' => trim($_POST['category'] ?? '')]);
header('Location: /new/' . rawurlencode($uuid) . '/4');
@@ -572,7 +589,10 @@ switch ($action) {
break;
case 4:
if ($draft === null) { header('Location: /new'); exit; }
if ($draft === null) {
header('Location: /new');
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$_vals = array_values(array_filter(array_map('trim', explode(',', (string)($_POST['tags_flat'] ?? ''))), fn ($_v) => $_v !== ''));
$articles->updatePartialMeta($uuid, ['tags' => $_vals !== [] ? ['tags' => $_vals] : []]);
@@ -582,14 +602,22 @@ switch ($action) {
$_tagTypes = $articles->getTagTypes();
$flatTagValues = [];
foreach ($_tagTypes as $_tk => $_) {
foreach ($articles->getAllTagValues($_tk) as $_v) { $flatTagValues[$_v] = true; }
foreach ($articles->getAllTagValues($_tk) as $_v) {
$flatTagValues[$_v] = true;
}
}
foreach ($articles->getAllTagValues('tags') as $_v) {
$flatTagValues[$_v] = true;
}
foreach ($articles->getAllTagValues('tags') as $_v) { $flatTagValues[$_v] = true; }
ksort($flatTagValues);
$flatTagValues = array_keys($flatTagValues);
$flatArticleTags = [];
foreach (($draft['tags'] ?? []) as $_tagVals) {
foreach ((array)$_tagVals as $_v) { if (!in_array($_v, $flatArticleTags, true)) $flatArticleTags[] = $_v; }
foreach ((array)$_tagVals as $_v) {
if (!in_array($_v, $flatArticleTags, true)) {
$flatArticleTags[] = $_v;
}
}
}
$draftContent = (string)($draft['content'] ?? '');
require_once BASE_PATH . '/src/TagSuggester.php';
@@ -597,7 +625,10 @@ switch ($action) {
break;
case 5:
if ($draft === null) { header('Location: /new'); exit; }
if ($draft === null) {
header('Location: /new');
exit;
}
require_once BASE_PATH . '/src/Parsedown.php';
$_pd = new Parsedown();
$autoSeoDesc = mb_strimwidth(trim((string)preg_replace('/\s+/', ' ', strip_tags($_pd->text((string)($draft['content'] ?? ''))))), 0, 155, '…');
@@ -798,6 +829,13 @@ switch ($action) {
$comments = $commentMgr->forArticle($article['uuid']);
}
// Contexte livre (navigation précédent/suivant si l'article fait partie d'un livre)
$bookContext = $books->findForArticle($article['slug'] ?? '');
if ($bookContext !== null) {
$bookContext['prev_article'] = $bookContext['prev'] !== null ? $articles->getBySlug($bookContext['prev']) : null;
$bookContext['next_article'] = $bookContext['next'] !== null ? $articles->getBySlug($bookContext['next']) : null;
}
include BASE_PATH . '/templates/post_view.php';
break;
@@ -845,15 +883,11 @@ switch ($action) {
case 1:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$title = trim($_POST['title'] ?? '');
$content = $_POST['content'] ?? '';
if ($title === '') {
$errors[] = 'Le titre est obligatoire.';
} else {
$articles->saveDraftOverlay($uuid, ['title' => $title, 'slug' => trim($_POST['slug'] ?? $draft['slug'])], $content);
header('Location: /edit/' . rawurlencode($uuid) . '/2');
exit;
}
$content = str_replace("\r\n", "\n", $_POST['content'] ?? '');
$title = extractMarkdownTitle($content) ?: ($draft['title'] ?? 'Sans titre');
$articles->saveDraftOverlay($uuid, ['title' => $title, 'slug' => trim($_POST['slug'] ?? $draft['slug'] ?? '')], $content);
header('Location: /edit/' . rawurlencode($uuid) . '/2');
exit;
}
$title = $draft['title'];
$content = $draft['content'];
@@ -903,14 +937,22 @@ switch ($action) {
$_tagTypes = $articles->getTagTypes();
$flatTagValues = [];
foreach ($_tagTypes as $_tk => $_) {
foreach ($articles->getAllTagValues($_tk) as $_v) { $flatTagValues[$_v] = true; }
foreach ($articles->getAllTagValues($_tk) as $_v) {
$flatTagValues[$_v] = true;
}
}
foreach ($articles->getAllTagValues('tags') as $_v) {
$flatTagValues[$_v] = true;
}
foreach ($articles->getAllTagValues('tags') as $_v) { $flatTagValues[$_v] = true; }
ksort($flatTagValues);
$flatTagValues = array_keys($flatTagValues);
$flatArticleTags = [];
foreach (($draft['tags'] ?? []) as $_tagVals) {
foreach ((array)$_tagVals as $_v) { if (!in_array($_v, $flatArticleTags, true)) $flatArticleTags[] = $_v; }
foreach ((array)$_tagVals as $_v) {
if (!in_array($_v, $flatArticleTags, true)) {
$flatArticleTags[] = $_v;
}
}
}
$draftContent = (string)($draft['content'] ?? '');
require_once BASE_PATH . '/src/TagSuggester.php';
@@ -962,10 +1004,18 @@ switch ($action) {
$autoSlug = slugify($draftData['title'] ?? '');
$postSlug = $draftData['slug'] ?? $article['slug'];
$changes = [];
if ($titleChanged) { $changes[] = 'titre modifié'; }
if (($draftData['category'] ?? '') !== ($article['category'] ?? '')) { $changes[] = 'catégorie modifiée'; }
if (($draftData['tags'] ?? []) !== ($article['tags'] ?? [])) { $changes[] = 'tags modifiés'; }
if (($draftData['content'] ?? '') !== ($article['content'] ?? '')) { $changes[] = 'contenu modifié'; }
if ($titleChanged) {
$changes[] = 'titre modifié';
}
if (($draftData['category'] ?? '') !== ($article['category'] ?? '')) {
$changes[] = 'catégorie modifiée';
}
if (($draftData['tags'] ?? []) !== ($article['tags'] ?? [])) {
$changes[] = 'tags modifiés';
}
if (($draftData['content'] ?? '') !== ($article['content'] ?? '')) {
$changes[] = 'contenu modifié';
}
if ((bool)($draftData['published'] ?? false) !== (bool)($article['published'] ?? false)) {
$changes[] = ($draftData['published'] ?? false) ? 'article publié' : 'article dépublié';
}
@@ -1335,7 +1385,7 @@ switch ($action) {
case 'flux':
require_once BASE_PATH . '/src/FeedFetcher.php';
$fetcher = new FeedFetcher(BASE_PATH . '/data/_cache/feeds');
$fetcher = new FeedFetcher(DATA_PATH . '/_cache/feeds');
$fluxItems = [];
$pdo = dbPdo();
if ($pdo) {
@@ -1429,15 +1479,13 @@ switch ($action) {
echo json_encode(['ok' => false]);
exit;
}
$asTitle = trim($_POST['title'] ?? '');
$asContent = $_POST['content'] ?? '';
$asContent = str_replace("\r\n", "\n", $_POST['content'] ?? '');
$asSlug = trim($_POST['slug'] ?? '');
if ($asTitle === '') {
echo json_encode(['ok' => false]);
exit;
}
$_asCurrent = $articles->getByUuid($uuid);
$asTitle = extractMarkdownTitle($asContent) ?: ($_asCurrent['title'] ?? 'Sans titre');
$ok = $articles->autosave($uuid, $asTitle, $asContent, $asSlug);
echo json_encode(['ok' => $ok, 'time' => date('H:i:s')]);
$_asSlugFinal = $ok ? ($articles->getByUuid($uuid)['slug'] ?? '') : '';
echo json_encode(['ok' => $ok, 'time' => date('H:i:s'), 'title' => $asTitle, 'slug' => $_asSlugFinal]);
exit;
case 'autosave_draft':
@@ -1452,14 +1500,12 @@ switch ($action) {
echo json_encode(['ok' => false]);
exit;
}
$_adTitle = trim($_POST['title'] ?? '');
$_adContent = $_POST['content'] ?? null;
if ($_adTitle === '') {
echo json_encode(['ok' => false]);
exit;
}
$_adContent = isset($_POST['content']) ? str_replace("\r\n", "\n", $_POST['content']) : null;
$_adTitle = $_adContent !== null
? (extractMarkdownTitle($_adContent) ?: ($_adArticle['title'] ?? 'Sans titre'))
: ($_adArticle['title'] ?? 'Sans titre');
$articles->saveDraftOverlay($uuid, ['title' => $_adTitle], $_adContent);
echo json_encode(['ok' => true, 'time' => date('H:i:s')]);
echo json_encode(['ok' => true, 'time' => date('H:i:s'), 'title' => $_adTitle]);
exit;
case 'edit_discard_draft':
@@ -1491,8 +1537,8 @@ switch ($action) {
echo json_encode(['ok' => false, 'error' => 'Paramètres invalides']);
exit;
}
$cfSrc = BASE_PATH . '/data/' . $cfFrom . '/files/' . $cfName;
$cfDstDir = BASE_PATH . '/data/' . $cfTo . '/files';
$cfSrc = DATA_PATH . '/' . $cfFrom . '/files/' . $cfName;
$cfDstDir = DATA_PATH . '/' . $cfTo . '/files';
$cfDst = $cfDstDir . '/' . $cfName;
if (!file_exists($cfSrc)) {
echo json_encode(['ok' => false, 'error' => 'Fichier source introuvable']);
@@ -1605,7 +1651,7 @@ switch ($action) {
// Capture d'écran pour prévisualisation (pages HTML uniquement, URL externes uniquement)
$step2Screenshot = null;
if (!$step2IsInternal && str_starts_with($step2Meta['mime'] ?? '', 'text/html')) {
$filesDir = BASE_PATH . '/data/' . $uuid . '/files';
$filesDir = DATA_PATH . '/' . $uuid . '/files';
if (!is_dir($filesDir)) {
mkdir($filesDir, 0755, true);
}
@@ -1681,7 +1727,7 @@ switch ($action) {
header('Location: /import/' . rawurlencode($urlUuid) . '?error=1');
exit;
}
$filesDir = BASE_PATH . '/data/' . $urlUuid . '/files';
$filesDir = DATA_PATH . '/' . $urlUuid . '/files';
$previewPath = $filesDir . '/' . $screenshotFile;
if (!file_exists($previewPath)) {
header('Location: /import/' . rawurlencode($urlUuid) . '?error=1');
@@ -1700,7 +1746,7 @@ switch ($action) {
}
if ($mode === 'link') {
$filesDir = BASE_PATH . '/data/' . $urlUuid . '/files';
$filesDir = DATA_PATH . '/' . $urlUuid . '/files';
if (!is_dir($filesDir)) {
mkdir($filesDir, 0755, true);
}
@@ -1851,7 +1897,7 @@ switch ($action) {
$done = $fail = $skip = 0;
foreach ($articles->getAll() as $article) {
$artUuid = $article['uuid'];
$filesDir = BASE_PATH . '/data/' . $artUuid . '/files';
$filesDir = DATA_PATH . '/' . $artUuid . '/files';
foreach ($article['external_links'] ?? [] as $link) {
$lMeta = $link['meta'] ?? [];
$lMime = $lMeta['mime'] ?? 'text/html';
@@ -2258,6 +2304,7 @@ switch ($action) {
$tab = $_GET['tab'] ?? (isAdmin() ? 'dashboard' : 'articles');
$adminData = [];
$siteSettingsSaved = isset($_GET['saved']);
$siteSettingsError = ($_GET['error'] ?? '') === 'write';
if ($tab === 'dashboard') {
if (!isAdmin()) {
@@ -2492,17 +2539,53 @@ switch ($action) {
exit;
}
require_once BASE_PATH . '/src/SearchLogParser.php';
$parser = new SearchLogParser();
$parser = new SearchLogParser('/var/log/apache2', apacheAccessLog());
$adminData['search_terms'] = $parser->topTerms(100);
$adminData['search_log_readable'] = $parser->isReadable();
}
if ($tab === 'stats') {
if (!isAdmin()) {
http_response_code(403);
exit;
}
require_once BASE_PATH . '/src/AccessLogParser.php';
require_once BASE_PATH . '/src/AsnLookup.php';
$accessParser = new AccessLogParser('/var/log/apache2', apacheAccessLog());
$accessStats = $accessParser->stats();
$adminData['stats_readable'] = $accessParser->isReadable();
$adminData['stats_pages'] = array_slice($accessStats['pages'], 0, 30, true);
$adminData['stats_books'] = array_slice($accessStats['books'], 0, 20, true);
// Lookup AS pour les top 200 IPs
$topIps = array_slice($accessStats['ips'], 0, 200, true);
$asnMap = (new AsnLookup())->batchLookup(array_keys($topIps));
$asList = AsnLookup::aggregateByAs($topIps, $asnMap);
$adminData['stats_as'] = $asList;
$adminData['stats_as_groups'] = AsnLookup::applyGroups($asList, asGroups());
$adminData['as_groups'] = asGroups();
}
if ($tab === 'categories') {
$adminData['cats'] = $articles->getCategories();
$adminData['privateCats'] = $articles->getPrivateCategories();
$adminData['tagTypes'] = $articles->getTagTypes();
}
if ($tab === 'books') {
if (!isAdmin()) {
http_response_code(403);
exit;
}
$adminData['books'] = $books->getAll();
$adminData['edit_book'] = null;
$adminData['all_articles'] = $articles->getAll();
usort($adminData['all_articles'], static fn ($a, $b) => strcmp($a['title'] ?? '', $b['title'] ?? ''));
$editBookSlug = trim($_GET['edit'] ?? '');
if ($editBookSlug !== '') {
$adminData['edit_book'] = $books->getBySlug($editBookSlug);
}
}
include BASE_PATH . '/templates/admin.php';
break;
@@ -2514,7 +2597,7 @@ switch ($action) {
}
require_once BASE_PATH . '/src/SmtpSettings.php';
saveSmtpSettings([
$ok = saveSmtpSettings([
'host' => $_POST['smtp_host'] ?? '',
'port' => $_POST['smtp_port'] ?? '',
'secure' => $_POST['smtp_secure'] ?? '',
@@ -2523,7 +2606,7 @@ switch ($action) {
'from' => $_POST['smtp_from'] ?? '',
'from_name' => $_POST['smtp_from_name'] ?? '',
]);
header('Location: /admin/smtp?saved=1');
header('Location: /admin/smtp?' . ($ok ? 'saved=1' : 'error=write'));
exit;
case 'admin_smtp_test':
@@ -2697,13 +2780,73 @@ switch ($action) {
header('Location: /admin/users');
exit;
case 'run_content_migrations':
requireAuth();
if (!isAdmin() || $_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(403);
exit;
}
$_cmDataDir = DATA_PATH;
$_cmTrack = $_cmDataDir . '/.content_migrations.json';
$_cmFlag = $_cmDataDir . '/.maintenance';
$_cmApplied = file_exists($_cmTrack) ? (json_decode((string) file_get_contents($_cmTrack), true) ?? []) : [];
$_cmFiles = glob(BASE_PATH . '/scripts/content/migration_*.php') ?: [];
sort($_cmFiles);
$_cmPending = array_values(array_filter($_cmFiles, fn ($f) => !isset($_cmApplied[basename($f)])));
if (empty($_cmPending)) {
header('Location: /admin?tab=dashboard&notice=no_migrations');
exit;
}
file_put_contents($_cmFlag, date('Y-m-d H:i:s'));
$_cmErrors = 0;
$dataDir = $_cmDataDir;
foreach ($_cmPending as $_cmFile) {
try {
require $_cmFile;
$_cmApplied[basename($_cmFile)] = date('Y-m-d H:i:s');
file_put_contents($_cmTrack, json_encode($_cmApplied, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n");
} catch (Throwable $_cmEx) {
$_cmErrors++;
break;
}
}
if (file_exists($_cmFlag)) {
unlink($_cmFlag);
}
header('Location: /admin?tab=dashboard&notice=' . ($_cmErrors ? 'migration_error' : 'migrated'));
exit;
case 'force_update_check':
requireAuth();
if (!isAdmin() || $_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(403);
exit;
}
$_updateChecker->clearCache();
header('Location: /admin?tab=dashboard');
exit;
case 'admin_save_folio_config':
requireAuth();
if (!isAdmin() || $_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(403);
exit;
}
$ok = saveSiteSettings([
'folio_repo_url' => $_POST['folio_repo_url'] ?? '',
'folio_update_branch' => $_POST['folio_update_branch'] ?? '',
]);
$_updateChecker->clearCache();
header('Location: /admin/site?notice=' . ($ok ? 'folio_saved' : 'folio_error'));
exit;
case 'admin_save_site':
requireAuth();
if (!isAdmin() || $_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(403);
exit;
}
saveSiteSettings([
$ok = saveSiteSettings([
'site_title' => $_POST['site_title'] ?? '',
'site_claim' => $_POST['site_claim'] ?? '',
'site_lang' => $_POST['site_lang'] ?? '',
@@ -2711,7 +2854,41 @@ switch ($action) {
'site_license_label' => $_POST['site_license_label'] ?? '',
'site_license_url' => $_POST['site_license_url'] ?? '',
]);
header('Location: /admin/site?saved=1');
header('Location: /admin/site?' . ($ok ? 'saved=1' : 'error=write'));
exit;
case 'admin_save_searches_config':
requireAuth();
if (!isAdmin() || $_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(403);
exit;
}
$ok = saveSiteSettings(['apache_access_log' => $_POST['apache_access_log'] ?? '']);
header('Location: /admin/searches?' . ($ok ? 'saved=1' : 'error=write'));
exit;
case 'admin_save_as_groups':
requireAuth();
if (!isAdmin() || $_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(403);
exit;
}
$rawLabels = $_POST['as_group_label'] ?? [];
$rawPatterns = $_POST['as_group_patterns'] ?? [];
$groups = [];
foreach ((array) $rawLabels as $i => $label) {
$label = trim((string) $label);
if ($label === '') {
continue;
}
$patterns = array_values(array_filter(array_map(
'trim',
explode("\n", (string) ($rawPatterns[$i] ?? ''))
)));
$groups[] = ['label' => $label, 'patterns' => $patterns];
}
$ok = saveSiteSettings(['as_groups' => $groups]);
header('Location: /admin/stats?' . ($ok ? 'saved=1' : 'error=write'));
exit;
case 'admin_create_role':
@@ -3048,6 +3225,69 @@ switch ($action) {
include BASE_PATH . '/templates/search.php';
break;
case 'book':
$bookSlug = trim($_GET['book_slug'] ?? '');
$book = $books->getBySlug($bookSlug);
if (!$book) {
http_response_code(404);
ob_start();
?>
<div class="container py-5 text-center">
<h1 class="h2 mb-3">Livre introuvable</h1>
<p class="text-muted mb-4">Ce livre n'existe pas ou a été supprimé.</p>
<a href="/" class="btn btn-primary">← Retour à l'accueil</a>
</div>
<?php
$content = ob_get_clean();
$title = '404 — ' . siteTitle();
$metaRobots = 'noindex, nofollow';
include BASE_PATH . '/templates/layout.php';
break;
}
$bookArticles = [];
foreach ($book['articles'] ?? [] as $aSlug) {
$a = $articles->getBySlug($aSlug);
if (!$a) {
continue;
}
if (!$a['published'] && !canDoOnArticle('view_drafts', $a)) {
continue;
}
$bookArticles[] = $a;
}
$allCats = $articles->getCategories();
include BASE_PATH . '/templates/book.php';
break;
case 'book_save':
requireAuth();
if (!isAdmin() || $_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(403);
exit;
}
$bSlug = trim($_POST['slug'] ?? '');
$bTitle = trim($_POST['title'] ?? '');
$bDesc = trim($_POST['description'] ?? '');
$bArts = array_values(array_filter(array_map('trim', preg_split('/[\r\n]+/', $_POST['articles'] ?? ''))));
if ($bSlug !== '' && $bTitle !== '') {
$books->save(['slug' => $bSlug, 'title' => $bTitle, 'description' => $bDesc, 'articles' => $bArts]);
}
header('Location: /admin/books?saved=1&edit=' . rawurlencode($bSlug));
exit;
case 'book_delete':
requireAuth();
if (!isAdmin() || $_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(403);
exit;
}
$bSlug = trim($_POST['slug'] ?? '');
if ($bSlug !== '') {
$books->delete($bSlug);
}
header('Location: /admin/books?deleted=1');
exit;
case 'not_found':
$notFoundPath = trim(
(string)(parse_url($_SERVER['REDIRECT_URL'] ?? $_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH) ?? ''),
+1 -1
View File
@@ -8,7 +8,7 @@ require_once BASE_PATH . '/src/helpers.php';
require_once BASE_PATH . '/config/config.php';
require_once BASE_PATH . '/src/ArticleManager.php';
$articles = new ArticleManager(BASE_PATH . '/data');
$articles = new ArticleManager(DATA_PATH);
$privateCats = $articles->getPrivateCategories();
$published = array_filter($articles->getAll(true), static function (array $a) use ($privateCats): bool {
+1
View File
@@ -0,0 +1 @@
1.4.0
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
// Migration 001 : préfixe chaque article avec `# Titre` si aucun titre
// Markdown de niveau 1 n'est déjà présent dans le contenu.
//
// Variables disponibles depuis le runner : $dataDir
/** @var string $dataDir */
$updated = 0;
$skipped = 0;
foreach (glob($dataDir . '/*/meta.json') as $metaPath) {
$dir = dirname($metaPath);
$mdPath = $dir . '/index.md';
if (!file_exists($mdPath)) {
$skipped++;
continue;
}
$meta = json_decode((string) file_get_contents($metaPath), true);
if (!is_array($meta)) {
$skipped++;
continue;
}
$title = trim($meta['title'] ?? '');
$content = (string) file_get_contents($mdPath);
$content = str_replace("\r\n", "\n", $content);
// Déjà un titre Markdown niveau 1 → on ne touche pas
if (preg_match('/^\s*#\s+\S/', $content)) {
$skipped++;
continue;
}
if ($title === '') {
$skipped++;
continue;
}
file_put_contents($mdPath, '# ' . $title . "\n\n" . ltrim($content));
touch($metaPath);
$updated++;
}
echo " $updated article(s) mis à jour, $skipped ignoré(s)\n";
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env php
<?php
declare(strict_types=1);
// Runner de migrations de contenu (fichiers articles).
// Analogie avec database/migrate.php, mais pour les fichiers data/.
//
// Usage : php scripts/migrate_content.php [/chemin/vers/data]
//
// - Lit data/.content_migrations.json pour savoir ce qui a déjà tourné.
// - Active data/.maintenance pendant l'exécution (→ page 503 aux visiteurs).
// - Applique les scripts scripts/content/migration_*.php non encore appliqués.
$baseDir = dirname(__DIR__);
$dataDir = $argv[1] ?? ($baseDir . '/data');
if (!is_dir($dataDir)) {
fwrite(STDERR, "Répertoire data introuvable : $dataDir\n");
exit(1);
}
$trackFile = $dataDir . '/.content_migrations.json';
$maintenanceFlag = $dataDir . '/.maintenance';
$applied = [];
if (file_exists($trackFile)) {
$applied = json_decode((string) file_get_contents($trackFile), true) ?? [];
}
$files = glob(__DIR__ . '/content/migration_*.php') ?: [];
sort($files);
$pending = array_values(array_filter($files, fn ($f) => !isset($applied[basename($f)])));
if (empty($pending)) {
echo " (aucune migration de contenu en attente)\n";
exit(0);
}
file_put_contents($maintenanceFlag, date('Y-m-d H:i:s'));
echo "→ Mode maintenance activé\n";
$count = 0;
$errors = 0;
foreach ($pending as $file) {
$name = basename($file);
echo "$name ... ";
try {
require $file;
$applied[$name] = date('Y-m-d H:i:s');
file_put_contents(
$trackFile,
json_encode($applied, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n"
);
echo "\n";
$count++;
} catch (Throwable $e) {
echo "" . $e->getMessage() . "\n";
$errors++;
break;
}
}
if (file_exists($maintenanceFlag)) {
unlink($maintenanceFlag);
}
echo "→ Mode maintenance désactivé\n";
echo "$count migration(s) appliquée(s)" . ($errors ? ", $errors erreur(s)" : '') . ".\n";
exit($errors > 0 ? 1 : 0);
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env bash
# Pousse le code Folio vers git.abonnel.fr/cedricAbonnel/folio
# Usage : ./scripts/push.sh "message de commit"
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$SCRIPT_DIR/.."
MSG="${1:-}"
if [[ -z "$MSG" ]]; then
echo "Usage: $0 \"message de commit\""
exit 1
fi
cd "$ROOT"
if [ ! -d .git ]; then
git init -b main
git remote add origin https://git.abonnel.fr/cedricAbonnel/folio.git
echo "→ Dépôt git initialisé"
fi
# Extraire la version depuis CHANGELOG.md (première entrée ## [X.Y.Z])
FOLIO_VERSION=$(grep -m1 '^\#\# \[[0-9]' CHANGELOG.md | sed 's/.*\[\([^]]*\)\].*/\1/')
if [[ -z "$FOLIO_VERSION" ]]; then
echo "✗ Impossible d'extraire la version depuis CHANGELOG.md"
exit 1
fi
echo "$FOLIO_VERSION" > public/version.txt
echo "→ Version : $FOLIO_VERSION"
git add -A
git diff --cached --quiet && echo "(rien à committer)" && exit 0
git commit -m "$MSG"
git push origin main
echo "✓ Poussé vers folio"
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env bash
# setup.sh — déploiement initial de Folio sur un serveur
#
# Usage : sudo ./scripts/setup.sh [--web-group www-data] [--data-dir /chemin/data]
#
# Ce script est idempotent : il peut être relancé sans risque.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$SCRIPT_DIR/.."
# ─── Paramètres ──────────────────────────────────────────────────────────────
WEB_GROUP="www-data"
DATA_DIR="$ROOT/data"
while [[ $# -gt 0 ]]; do
case "$1" in
--web-group) WEB_GROUP="$2"; shift 2 ;;
--data-dir) DATA_DIR="$2"; shift 2 ;;
*) echo "Option inconnue : $1"; exit 1 ;;
esac
done
# ─── Vérifications préalables ─────────────────────────────────────────────────
if [[ ! -f "$ROOT/.env" ]]; then
echo "✗ Fichier .env manquant. Copier .env.example en .env et remplir les valeurs."
exit 1
fi
if ! getent group "$WEB_GROUP" > /dev/null 2>&1; then
echo "✗ Groupe '$WEB_GROUP' introuvable. Utiliser --web-group <groupe>."
exit 1
fi
# ─── Dépendances PHP ──────────────────────────────────────────────────────────
echo "→ Installation des dépendances PHP..."
composer install --no-dev --optimize-autoloader --working-dir="$ROOT"
# ─── Dossiers requis ─────────────────────────────────────────────────────────
echo "→ Création des dossiers..."
mkdir -p "$DATA_DIR"
mkdir -p "$ROOT/public/_cache"
mkdir -p "$ROOT/.sessions"
# ─── Permissions ─────────────────────────────────────────────────────────────
echo "→ Configuration des permissions (groupe : $WEB_GROUP)..."
# data/ : setgid pour héritage de groupe + lecture/écriture propriétaire et groupe
chown -R :"$WEB_GROUP" "$DATA_DIR"
chmod g+s "$DATA_DIR"
find "$DATA_DIR" -type d -exec chmod g+s {} +
find "$DATA_DIR" -exec chmod ug+rw {} +
# public/_cache/ : créé et écrit par PHP
chown -R :"$WEB_GROUP" "$ROOT/public/_cache"
chmod g+s "$ROOT/public/_cache"
find "$ROOT/public/_cache" -exec chmod ug+rw {} +
# .sessions/ : écrit par PHP
chown -R :"$WEB_GROUP" "$ROOT/.sessions"
chmod 770 "$ROOT/.sessions"
# ─── Groupe adm pour lecture des logs Apache ─────────────────────────────────
echo "→ Ajout de $WEB_GROUP au groupe adm (logs Apache)..."
if getent group adm > /dev/null 2>&1; then
usermod -aG adm "$WEB_GROUP"
echo " Redémarrer Apache et PHP-FPM pour que le changement prenne effet :"
echo " systemctl restart apache2 php8.3-fpm"
else
echo " Groupe adm absent, ignoré."
fi
# ─── Migrations SQL ───────────────────────────────────────────────────────────
echo "→ Migrations SQL..."
php "$ROOT/database/migrate.php"
echo ""
echo "✓ Folio est prêt."
echo " Vérifier que APP_URL et ADMIN_EMAIL sont corrects dans .env."
+178
View File
@@ -0,0 +1,178 @@
<?php
declare(strict_types=1);
class AccessLogParser
{
private string $logDir;
private string $pattern;
private string $cacheFile;
private int $cacheTtl;
private int $days;
private static ?array $memo = null;
// Apache COMBINED : IP - - [timestamp] "METHOD /path HTTP/x" STATUS bytes "ref" "ua"
private const RE = '/^(\S+) \S+ \S+ \[(\d{2}\/\w+\/\d{4}:\d{2}:\d{2}:\d{2} [+-]\d{4})\] "[A-Z-]+ ([^\s"?]+)[^"]*" (\d{3}) /';
public function __construct(
string $logDir = '/var/log/apache2',
string $pattern = '*-access.log',
string $cacheFile = '',
int $cacheTtl = 600,
int $days = 14
) {
$this->logDir = rtrim($logDir, '/');
$this->pattern = $pattern;
$this->cacheFile = $cacheFile !== '' ? $cacheFile : dirname(__DIR__) . '/_cache/access_stats.json';
$this->cacheTtl = $cacheTtl;
$this->days = $days;
}
/**
* @return array{pages:array<string,int>,books:array<string,int>,ips:array<string,int>}
*/
public function stats(): array
{
if (self::$memo !== null) {
return self::$memo;
}
if ($this->cacheValid()) {
$d = json_decode((string) file_get_contents($this->cacheFile), true);
if (is_array($d)) {
return self::$memo = $d;
}
}
$cutoff = strtotime("-{$this->days} days midnight") ?: (time() - $this->days * 86400);
$pages = [];
$books = [];
$ips = [];
foreach ($this->logFiles() as $file) {
$this->parseFile($file, $cutoff, $pages, $books, $ips);
}
arsort($pages);
arsort($books);
arsort($ips);
$result = compact('pages', 'books', 'ips');
@mkdir(dirname($this->cacheFile), 0755, true);
@file_put_contents($this->cacheFile, json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
return self::$memo = $result;
}
public function isReadable(): bool
{
return count($this->logFiles()) > 0;
}
private function cacheValid(): bool
{
return file_exists($this->cacheFile)
&& (time() - filemtime($this->cacheFile)) < $this->cacheTtl;
}
/** @return list<array{path:string,type:string}> */
private function logFiles(): array
{
$files = [];
$cutoff = time() - ($this->days + 1) * 86400;
foreach (glob($this->logDir . '/' . $this->pattern) ?: [] as $base) {
if (str_ends_with($base, '.gz') || preg_match('/\.\d+$/', $base)) {
continue;
}
foreach (array_merge([$base], glob($base . '.*') ?: []) as $path) {
if ($path !== $base && filemtime($path) < $cutoff) {
continue;
}
if (!is_readable($path)) {
continue;
}
if (str_ends_with($path, '.tar.gz')) {
$files[] = ['path' => $path, 'type' => 'tgz'];
} elseif (str_ends_with($path, '.gz')) {
$files[] = ['path' => $path, 'type' => 'gz'];
} else {
$files[] = ['path' => $path, 'type' => 'plain'];
}
}
}
return $files;
}
private static function parseTimestamp(string $raw): int
{
// "15/May/2026:00:41:01 +0200"
if (!preg_match('/(\d{2})\/(\w{3})\/(\d{4}):(\d{2}:\d{2}:\d{2}) ([+-]\d{4})/', $raw, $m)) {
return 0;
}
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
{
if (!preg_match(self::RE, $line, $m)) {
return;
}
[, $ip, $ts, $path, $status] = $m;
if ($status !== '200') {
return;
}
if (self::parseTimestamp($ts) < $cutoff) {
return;
}
if (str_starts_with($path, '/post/') && strlen($path) > 6) {
$pages[$path] = ($pages[$path] ?? 0) + 1;
$ips[$ip] = ($ips[$ip] ?? 0) + 1;
} elseif (str_starts_with($path, '/book/') && strlen($path) > 6) {
$books[$path] = ($books[$path] ?? 0) + 1;
$ips[$ip] = ($ips[$ip] ?? 0) + 1;
}
}
private function parseFile(array $file, int $cutoff, array &$pages, array &$books, array &$ips): void
{
if ($file['type'] === 'tgz') {
try {
$phar = new PharData($file['path']);
foreach ($phar as $entry) {
$content = @file_get_contents('phar://' . $file['path'] . '/' . $entry->getFilename());
if ($content === false) {
continue;
}
foreach (explode("\n", $content) as $line) {
$this->parseLine($line, $cutoff, $pages, $books, $ips);
}
}
} catch (\Exception $e) {
}
} elseif ($file['type'] === 'gz') {
$h = @gzopen($file['path'], 'rb');
if (!$h) {
return;
}
while (!gzeof($h)) {
$line = gzgets($h, 8192);
if ($line !== false) {
$this->parseLine($line, $cutoff, $pages, $books, $ips);
}
}
gzclose($h);
} else {
$h = @fopen($file['path'], 'rb');
if (!$h) {
return;
}
while (($line = fgets($h)) !== false) {
$this->parseLine($line, $cutoff, $pages, $books, $ips);
}
fclose($h);
}
}
}
+55 -13
View File
@@ -9,7 +9,7 @@ class ArticleManager
private ?array $allCache = null;
private ?array $searchIndexCache = null;
public function __construct(private string $dataDir)
public function __construct(private string $dataDir, private ?DataGit $git = null)
{
}
@@ -132,11 +132,12 @@ class ArticleManager
file_put_contents($dir . '/index.md', ltrim($content));
$this->rebuildSearchIndex();
$this->rebuildBacklinksCache();
$this->git?->commit("add: $title");
return $uuid;
}
public function update(string $uuid, string $title, string $content, bool $published, string $slug, string $publishedAt, string $revisionComment = '', string $seoTitle = '', string $seoDescription = '', string $ogImage = '', string $category = '', ?array $tags = null): void
public function update(string $uuid, string $title, string $content, bool $published, string $slug, string $publishedAt, string $revisionComment = '', string $seoTitle = '', string $seoDescription = '', string $ogImage = '', string $category = '', ?array $tags = null, bool $skipGit = false): void
{
$article = $this->getByUuid($uuid);
if (!$article) {
@@ -199,6 +200,9 @@ class ArticleManager
file_put_contents($dir . '/index.md', ltrim($content));
$this->rebuildSearchIndex();
$this->rebuildBacklinksCache();
if (!$skipGit) {
$this->git?->commit("update: $title");
}
}
public function autosave(string $uuid, string $title, string $content, string $slug): bool
@@ -247,6 +251,7 @@ class ArticleManager
}
$meta['updated_at'] = date('Y-m-d H:i:s');
$this->writeMeta($dir, $meta);
$this->git?->commit("meta: " . ($meta['title'] ?? $uuid));
}
public function saveDraftOverlay(string $uuid, array $metaFields, ?string $content = null): void
@@ -269,6 +274,9 @@ class ArticleManager
if ($content !== null) {
file_put_contents($dir . '/draft_overlay.md', $content);
}
$raw2 = @file_get_contents($dir . '/meta.json');
$title = is_string($raw2) ? (json_decode($raw2, true)['title'] ?? $uuid) : $uuid;
$this->git?->commit("draft: $title");
}
public function getDraftOverlay(string $uuid): ?array
@@ -315,14 +323,22 @@ class ArticleManager
return file_exists($this->dataDir . '/' . $uuid . '/draft_overlay.json');
}
public function discardDraftOverlay(string $uuid): void
public function discardDraftOverlay(string $uuid, bool $skipGit = false): void
{
if (!$this->isValidUuid($uuid)) {
return;
}
$dir = $this->dataDir . '/' . $uuid;
$dir = $this->dataDir . '/' . $uuid;
$title = null;
if (!$skipGit && $this->git !== null) {
$raw = @file_get_contents($dir . '/meta.json');
$title = is_string($raw) ? (json_decode($raw, true)['title'] ?? $uuid) : $uuid;
}
@unlink($dir . '/draft_overlay.json');
@unlink($dir . '/draft_overlay.md');
if ($title !== null) {
$this->git?->commit("discard-draft: $title");
}
}
public function commitDraftOverlay(string $uuid, string $revisionComment = ''): void
@@ -331,9 +347,10 @@ class ArticleManager
if (!$draft) {
return;
}
$title = $draft['title'];
$this->update(
$uuid,
$draft['title'],
$title,
$draft['content'],
(bool)$draft['published'],
$draft['slug'] ?? '',
@@ -343,12 +360,14 @@ class ArticleManager
$draft['seo_description'] ?? '',
$draft['og_image'] ?? '',
$draft['category'] ?? '',
$draft['tags'] ?? []
$draft['tags'] ?? [],
true // skipGit — commit unique ci-dessous
);
$this->discardDraftOverlay($uuid);
$this->discardDraftOverlay($uuid, skipGit: true);
$this->git?->commit("publish: $title");
}
public function addFileMeta(string $uuid, string $filename, string $author, string $sourceUrl, string $title = '', array $extraMeta = []): void
public function addFileMeta(string $uuid, string $filename, string $author, string $sourceUrl, string $title = '', array $extraMeta = [], bool $skipGit = false): void
{
if (!$this->isValidUuid($uuid)) {
return;
@@ -377,6 +396,9 @@ class ArticleManager
}
$meta['files_meta'][$filename] = $entry;
$this->writeMeta($this->dataDir . '/' . $uuid, $meta);
if (!$skipGit) {
$this->git?->commit("file-meta: {$uuid}/{$filename}");
}
}
public function setCover(string $uuid, string $filename): void
@@ -424,6 +446,7 @@ class ArticleManager
}
$meta['cover'] = $coverName;
$this->writeMeta($this->dataDir . '/' . $uuid, $meta);
$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
@@ -499,7 +522,7 @@ class ArticleManager
rename($tmp, $filesDir . '/' . $filename);
if ($author !== '' || $sourceUrl !== '' || $title !== '' || !empty($extraMeta)) {
$this->addFileMeta($uuid, $filename, $author, $sourceUrl, $title, $extraMeta);
$this->addFileMeta($uuid, $filename, $author, $sourceUrl, $title, $extraMeta, skipGit: true);
}
if ($isCover && $isImage) {
@@ -513,6 +536,7 @@ class ArticleManager
}
}
$this->git?->commit("add-file: {$uuid}/{$filename}");
return $filename;
}
@@ -553,6 +577,7 @@ class ArticleManager
$meta['external_links'][] = $entry;
$this->writeMeta($dir, $meta);
$this->rebuildBacklinksCache();
$this->git?->commit("link: {$uuid}");
return true;
}
@@ -583,6 +608,7 @@ class ArticleManager
return false;
}
$this->writeMeta($dir, $meta);
$this->git?->commit("link-meta: {$uuid}");
return true;
}
@@ -606,6 +632,7 @@ class ArticleManager
));
$this->writeMeta($dir, $meta);
$this->rebuildBacklinksCache();
$this->git?->commit("unlink: {$uuid}");
return true;
}
@@ -623,7 +650,7 @@ class ArticleManager
return $cats;
}
public function renameCategory(string $old, string $new): void
public function renameCategory(string $old, string $new, bool $skipGit = false): void
{
if (!is_dir($this->dataDir)) {
return;
@@ -647,11 +674,15 @@ class ArticleManager
$meta['category'] = $new;
$this->writeMeta($this->dataDir . '/' . $entry, $meta);
}
if (!$skipGit) {
$this->git?->commit("rename-cat: $old$new");
}
}
public function deleteCategory(string $name): void
{
$this->renameCategory($name, '');
$this->renameCategory($name, '', skipGit: true);
$this->git?->commit("delete-cat: $name");
}
public function getPrivateCategories(): array
@@ -676,6 +707,7 @@ class ArticleManager
$this->dataDir . '/private_cats.json',
json_encode(array_values($cats), JSON_UNESCAPED_UNICODE)
);
$this->git?->commit("private-cat: $cat");
}
// ─── Tag types ──────────────────────────────────────────────────────────────
@@ -701,6 +733,7 @@ class ArticleManager
$this->tagTypesPath(),
json_encode($types, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n"
);
$this->git?->commit("tag-types");
}
/** Enregistre les tags d'un article directement (utile pour les scripts de migration). */
@@ -720,6 +753,7 @@ class ArticleManager
$meta['tags'] = $this->normalizeTags($tags);
$this->writeMeta($dir, $meta);
$this->rebuildSearchIndex();
$this->git?->commit("tags: " . ($meta['title'] ?? $uuid));
}
/** @return list<string> Toutes les valeurs distinctes d'un type de tag, triées. */
@@ -769,6 +803,7 @@ class ArticleManager
$this->writeMeta($dir, $meta);
$this->allCache = null;
@unlink($this->articleCachePath($uuid));
$this->git?->commit("featured: " . ($meta['title'] ?? $uuid) . " (" . ($featured ? 'on' : 'off') . ")");
}
public function delete(string $uuid): void
@@ -777,6 +812,11 @@ class ArticleManager
return;
}
$dir = $this->dataDir . '/' . $uuid;
$title = null;
if ($this->git !== null && is_dir($dir)) {
$raw = @file_get_contents($dir . '/meta.json');
$title = is_string($raw) ? (json_decode($raw, true)['title'] ?? null) : null;
}
if (is_dir($dir)) {
$this->allCache = null;
@unlink($this->articleCachePath($uuid));
@@ -785,6 +825,7 @@ class ArticleManager
}
$this->rebuildSearchIndex();
$this->rebuildBacklinksCache();
$this->git?->commit("delete: " . ($title ?? $uuid));
}
// ------------------------------------------------------------------ //
@@ -1164,8 +1205,9 @@ class ArticleManager
$uuid = basename($dir);
$cachePath = $this->articleCachePath($uuid);
// Utiliser le cache si plus récent que meta.json
if (file_exists($cachePath) && filemtime($cachePath) >= filemtime($metaPath)) {
// Utiliser le cache si plus récent que meta.json ET index.md
$contentMtime = file_exists($dir . '/index.md') ? filemtime($dir . '/index.md') : 0;
if (file_exists($cachePath) && filemtime($cachePath) >= filemtime($metaPath) && filemtime($cachePath) >= $contentMtime) {
$cached = json_decode((string) file_get_contents($cachePath), true);
if (is_array($cached) && !empty($cached['uuid'])) {
return $cached;
+190
View File
@@ -0,0 +1,190 @@
<?php
declare(strict_types=1);
class AsnLookup
{
private string $cacheDir;
private int $ttl;
public function __construct(string $cacheDir = '', int $ttl = 86400 * 30)
{
$this->cacheDir = $cacheDir !== '' ? $cacheDir : dirname(__DIR__) . '/_cache/asn';
$this->ttl = $ttl;
}
/**
* Lookup AS info pour une liste d'IPs.
* IPs privées : retournées avec name='LAN', pas d'appel API.
*
* @param list<string> $ips
* @return array<string, array{asn:string,name:string,country:string}>
*/
public function batchLookup(array $ips): array
{
$results = [];
$missing = [];
foreach (array_unique($ips) as $ip) {
if ($this->isPrivate($ip)) {
$results[$ip] = ['asn' => '', 'name' => 'LAN', 'country' => ''];
continue;
}
$cached = $this->fromCache($ip);
if ($cached !== null) {
$results[$ip] = $cached;
} else {
$missing[] = $ip;
}
}
foreach (array_chunk($missing, 100) as $chunk) {
foreach ($this->fetchBatch($chunk) as $ip => $info) {
$this->toCache($ip, $info);
$results[$ip] = $info;
}
}
return $results;
}
public function isPrivate(string $ip): bool
{
return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false;
}
/**
* Agrège les hits par AS depuis un tableau [ip => hits] et les infos AS.
* Retourne [asKey => [asn, name, country, hits]] trié par hits desc.
*
* @param array<string,int> $ipHits
* @param array<string, array{asn:string,name:string,country:string}> $asnMap
* @return list<array{asn:string,name:string,country:string,hits:int}>
*/
public static function aggregateByAs(array $ipHits, array $asnMap): array
{
$byAs = [];
foreach ($ipHits as $ip => $hits) {
$info = $asnMap[$ip] ?? ['asn' => '?', 'name' => '?', 'country' => ''];
$key = $info['asn'] !== '' ? $info['asn'] : $info['name'];
if (!isset($byAs[$key])) {
$byAs[$key] = ['asn' => $info['asn'], 'name' => $info['name'], 'country' => $info['country'], 'hits' => 0];
}
$byAs[$key]['hits'] += $hits;
}
usort($byAs, static fn ($a, $b) => $b['hits'] <=> $a['hits']);
return array_values($byAs);
}
/**
* Applique les groupes définis par l'admin.
* Chaque groupe : ['label' => string, 'patterns' => [string, ...]]
* Un AS est affecté au premier groupe dont un pattern est contenu dans son nom (case-insensitive).
*
* @param list<array{asn:string,name:string,country:string,hits:int}> $asList
* @param list<array{label:string,patterns:list<string>}> $groups
* @return array<string, list<array{asn:string,name:string,country:string,hits:int}>>
* clés : labels des groupes + 'Autres'
*/
public static function applyGroups(array $asList, array $groups): array
{
$result = [];
foreach ($groups as $g) {
$result[$g['label']] = [];
}
$result['Autres'] = [];
foreach ($asList as $as) {
$matched = false;
foreach ($groups as $g) {
foreach ($g['patterns'] as $pattern) {
if ($pattern !== '' && mb_stripos($as['name'], $pattern) !== false) {
$result[$g['label']][] = $as;
$matched = true;
break 2;
}
}
}
if (!$matched) {
$result['Autres'][] = $as;
}
}
return $result;
}
// ─── Cache ────────────────────────────────────────────────────────────────
private function cacheFile(string $ip): string
{
return $this->cacheDir . '/' . md5($ip) . '.json';
}
/** @return array{asn:string,name:string,country:string}|null */
private function fromCache(string $ip): ?array
{
$f = $this->cacheFile($ip);
if (!file_exists($f) || (time() - filemtime($f)) > $this->ttl) {
return null;
}
$d = json_decode((string) file_get_contents($f), true);
return is_array($d) ? $d : null;
}
/** @param array{asn:string,name:string,country:string} $data */
private function toCache(string $ip, array $data): void
{
@mkdir($this->cacheDir, 0755, true);
@file_put_contents($this->cacheFile($ip), json_encode($data));
}
// ─── API ip-api.com ───────────────────────────────────────────────────────
/**
* @param list<string> $ips
* @return array<string, array{asn:string,name:string,country:string}>
*/
private function fetchBatch(array $ips): array
{
$body = json_encode($ips);
$context = stream_context_create(['http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\nContent-Length: " . strlen((string) $body) . "\r\n",
'content' => $body,
'timeout' => 10,
]]);
$resp = @file_get_contents(
'http://ip-api.com/batch?fields=query,as,org,country,countryCode',
false,
$context
);
if ($resp === false) {
return [];
}
$rows = json_decode($resp, true);
if (!is_array($rows)) {
return [];
}
$results = [];
foreach ($rows as $row) {
$ip = $row['query'] ?? '';
if ($ip === '') {
continue;
}
$asRaw = $row['as'] ?? '';
$asn = '';
if (preg_match('/^AS(\d+)/', $asRaw, $m)) {
$asn = $m[1];
}
$name = $row['org'] !== '' ? ($row['org'] ?? '') : preg_replace('/^AS\d+\s*/', '', $asRaw);
$country = $row['countryCode'] ?? '';
$results[$ip] = ['asn' => $asn, 'name' => (string) $name, 'country' => $country];
}
return $results;
}
}
+134
View File
@@ -0,0 +1,134 @@
<?php
declare(strict_types=1);
class BookManager
{
public function __construct(private string $booksDir, private ?DataGit $git = null)
{
}
// ------------------------------------------------------------------ //
// Lecture
// ------------------------------------------------------------------ //
public function getAll(): array
{
$books = [];
if (!is_dir($this->booksDir)) {
return $books;
}
foreach (scandir($this->booksDir) as $file) {
if (!str_ends_with($file, '.json')) {
continue;
}
$raw = file_get_contents($this->booksDir . '/' . $file);
if ($raw === false) {
continue;
}
$book = json_decode($raw, true);
if (!is_array($book) || empty($book['slug'])) {
continue;
}
$books[] = $book;
}
usort($books, static fn ($a, $b) => strcmp($a['title'] ?? '', $b['title'] ?? ''));
return $books;
}
public function getBySlug(string $slug): ?array
{
$path = $this->bookPath($slug);
if (!file_exists($path)) {
return null;
}
$raw = file_get_contents($path);
if ($raw === false) {
return null;
}
$book = json_decode($raw, true);
return is_array($book) && !empty($book['slug']) ? $book : null;
}
/**
* Cherche dans quel livre se trouve un article (par son slug).
* Retourne le contexte complet ou null si l'article n'appartient à aucun livre.
*
* @return array{book: array, position: int, total: int, prev: ?string, next: ?string}|null
*/
public function findForArticle(string $articleSlug): ?array
{
foreach ($this->getAll() as $book) {
$arts = $book['articles'] ?? [];
$pos = array_search($articleSlug, $arts, true);
if ($pos === false) {
continue;
}
$pos = (int) $pos;
return [
'book' => $book,
'position' => $pos + 1,
'total' => count($arts),
'prev' => $pos > 0 ? $arts[$pos - 1] : null,
'next' => $pos < count($arts) - 1 ? $arts[$pos + 1] : null,
];
}
return null;
}
// ------------------------------------------------------------------ //
// Écriture
// ------------------------------------------------------------------ //
public function save(array $book): void
{
$slug = $this->sanitizeSlug($book['slug'] ?? '');
if ($slug === '') {
return;
}
$book['slug'] = $slug;
$book['articles'] = array_values(array_filter(array_map('strval', $book['articles'] ?? [])));
if (!is_dir($this->booksDir)) {
mkdir($this->booksDir, 0755, true);
}
file_put_contents(
$this->bookPath($slug),
json_encode($book, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n"
);
$this->git?->commit("book: " . ($book['title'] ?? $slug));
}
public function delete(string $slug): void
{
$title = $this->getBySlug($slug)['title'] ?? $slug;
$path = $this->bookPath($slug);
if (file_exists($path)) {
@unlink($path);
}
$this->git?->commit("delete-book: $title");
}
// ------------------------------------------------------------------ //
// Helpers
// ------------------------------------------------------------------ //
private function bookPath(string $slug): string
{
return $this->booksDir . '/' . $slug . '.json';
}
private function sanitizeSlug(string $slug): string
{
$map = [
'à' => 'a', 'â' => 'a', 'ä' => 'a',
'é' => 'e', 'è' => 'e', 'ê' => 'e', 'ë' => 'e',
'î' => 'i', 'ï' => 'i',
'ô' => 'o', 'ö' => 'o',
'ù' => 'u', 'û' => 'u', 'ü' => 'u',
'ç' => 'c', 'æ' => 'ae', 'œ' => 'oe',
];
$slug = mb_strtolower(strtr(trim($slug), $map), 'UTF-8');
$slug = (string) preg_replace('/[^a-z0-9]+/', '-', $slug);
return trim($slug, '-');
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
class DataGit
{
public function __construct(private string $dataDir) {}
public function commit(string $message): void
{
if (!is_dir($this->dataDir . '/.git')) {
return;
}
$dir = escapeshellarg($this->dataDir);
$msg = escapeshellarg($message);
shell_exec("git -C $dir add -A 2>/dev/null");
exec("git -C $dir diff --cached --quiet 2>/dev/null", $_, $rc);
if ($rc !== 0) {
shell_exec("git -C $dir commit -m $msg 2>/dev/null");
}
}
}
+41 -18
View File
@@ -11,7 +11,7 @@ class SearchLogParser
public function __construct(
string $logDir = '/var/log/apache2',
string $vhostBase = 'lan.acegrp.varlog-access.log',
string $vhostBase = '*-access.log',
string $cacheFile = '',
int $cacheTtl = 600
) {
@@ -47,8 +47,7 @@ class SearchLogParser
public function isReadable(): bool
{
$f = $this->logDir . '/' . $this->vhostBase;
return file_exists($f) && is_readable($f);
return count($this->logFiles()) > 0;
}
private function cacheValid(): bool
@@ -57,23 +56,32 @@ class SearchLogParser
&& (time() - filemtime($this->cacheFile)) < $this->cacheTtl;
}
/** @return list<array{path:string,gz:bool}> */
/** @return list<array{path:string,type:string}> type: plain|gz|tgz */
private function logFiles(): array
{
$base = $this->logDir . '/' . $this->vhostBase;
$files = [];
$pattern = $this->logDir . '/' . $this->vhostBase;
$files = [];
if (file_exists($base) && is_readable($base)) {
$files[] = ['path' => $base, 'gz' => false];
}
for ($i = 1; $i <= 14; $i++) {
$plain = $base . '.' . $i;
$gz = $plain . '.gz';
if (file_exists($plain) && is_readable($plain)) {
$files[] = ['path' => $plain, 'gz' => false];
} elseif (file_exists($gz) && is_readable($gz)) {
$files[] = ['path' => $gz, 'gz' => true];
// Fichiers correspondant au pattern de base (courants + rotations incluses si glob)
$bases = glob($pattern) ?: [];
// Ajouter aussi les rotations (.N, .N.gz, .N.tar.gz) pour chaque base trouvée
foreach ($bases as $base) {
// Exclure les rotations déjà capturées par le pattern glob
if (str_ends_with($base, '.gz') || preg_match('/\.\d+$/', $base)) {
continue;
}
$candidates = array_merge([$base], glob($base . '.*') ?: []);
foreach ($candidates as $path) {
if (!is_readable($path)) {
continue;
}
if (str_ends_with($path, '.tar.gz')) {
$files[] = ['path' => $path, 'type' => 'tgz'];
} elseif (str_ends_with($path, '.gz')) {
$files[] = ['path' => $path, 'type' => 'gz'];
} else {
$files[] = ['path' => $path, 'type' => 'plain'];
}
}
}
@@ -82,7 +90,22 @@ class SearchLogParser
private function parseFile(array $file, array &$counts): void
{
if ($file['gz']) {
if ($file['type'] === 'tgz') {
try {
$phar = new PharData($file['path']);
foreach ($phar as $entry) {
$content = @file_get_contents('phar://' . $file['path'] . '/' . $entry->getFilename());
if ($content === false) {
continue;
}
foreach (explode("\n", $content) as $line) {
$this->parseLine($line, $counts);
}
}
} catch (\Exception $e) {
// archive illisible, on ignore
}
} elseif ($file['type'] === 'gz') {
$h = @gzopen($file['path'], 'rb');
if (!$h) {
return;
+43 -5
View File
@@ -4,7 +4,7 @@ declare(strict_types=1);
function siteSettingsPath(): string
{
return BASE_PATH . '/data/site_settings.json';
return DATA_PATH . '/site_settings.json';
}
function siteSettings(): array
@@ -59,10 +59,44 @@ function siteLicenseUrl(): string
return siteSettings()['site_license_url'] ?? 'https://creativecommons.org/licenses/by/4.0/';
}
function saveSiteSettings(array $data): void
function apacheAccessLog(): string
{
$fromSettings = siteSettings()['apache_access_log'] ?? '';
if ($fromSettings !== '') {
return $fromSettings;
}
return (string)($_ENV['APACHE_ACCESS_LOG'] ?? getenv('APACHE_ACCESS_LOG') ?: '*-access.log');
}
function folioRepoUrl(): string
{
$fromSettings = siteSettings()['folio_repo_url'] ?? '';
if ($fromSettings !== '') {
return rtrim($fromSettings, '/');
}
return rtrim((string)($_ENV['FOLIO_REPO_URL'] ?? getenv('FOLIO_REPO_URL') ?: ''), '/');
}
function folioUpdateBranch(): string
{
$fromSettings = siteSettings()['folio_update_branch'] ?? '';
if ($fromSettings !== '') {
return $fromSettings;
}
return (string)($_ENV['FOLIO_UPDATE_BRANCH'] ?? getenv('FOLIO_UPDATE_BRANCH') ?: 'main');
}
/** @return list<array{label:string,patterns:list<string>}> */
function asGroups(): array
{
$raw = siteSettings()['as_groups'] ?? [];
return is_array($raw) ? $raw : [];
}
function saveSiteSettings(array $data): bool
{
$current = siteSettings();
$stringKeys = ['site_title', 'site_claim', 'site_lang', 'site_license_label', 'site_license_url'];
$stringKeys = ['site_title', 'site_claim', 'site_lang', 'site_license_label', 'site_license_url', 'apache_access_log', 'folio_repo_url', 'folio_update_branch'];
foreach ($stringKeys as $key) {
if (array_key_exists($key, $data)) {
$val = trim((string)$data[$key]);
@@ -77,8 +111,12 @@ function saveSiteSettings(array $data): void
$current['posts_per_page'] = $val;
}
}
file_put_contents(
if (array_key_exists('as_groups', $data) && is_array($data['as_groups'])) {
$current['as_groups'] = $data['as_groups'];
}
return file_put_contents(
siteSettingsPath(),
json_encode($current, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
);
) !== false;
}
+4 -4
View File
@@ -4,7 +4,7 @@ declare(strict_types=1);
function smtpSettingsPath(): string
{
return BASE_PATH . '/data/smtp_settings.json';
return DATA_PATH . '/smtp_settings.json';
}
function smtpSettings(): array
@@ -35,7 +35,7 @@ function smtpCfg(string $key, string $envKey, string $default = ''): string
return ($v !== false && $v !== '') ? (string)$v : $default;
}
function saveSmtpSettings(array $data): void
function saveSmtpSettings(array $data): bool
{
$current = smtpSettings();
foreach (['host', 'port', 'secure', 'user', 'from', 'from_name'] as $key) {
@@ -46,8 +46,8 @@ function saveSmtpSettings(array $data): void
if (!empty($data['pass']) && trim((string)$data['pass']) !== '') {
$current['pass'] = trim((string)$data['pass']);
}
file_put_contents(
return file_put_contents(
smtpSettingsPath(),
json_encode($current, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
);
) !== false;
}
+162
View File
@@ -0,0 +1,162 @@
<?php
declare(strict_types=1);
/**
* Vérifie si une mise à jour de Folio est disponible sur le dépôt Git,
* et si des migrations de contenu sont en attente.
*
* Aucune dépendance externe : utilise file_get_contents() + cache JSON.
*/
class UpdateChecker
{
private string $dataDir;
private string $baseDir;
public function __construct(string $dataDir, string $baseDir)
{
$this->dataDir = $dataDir;
$this->baseDir = $baseDir;
}
/** Retourne la liste des alertes à afficher aux administrateurs. */
public function adminNotices(): array
{
$notices = [];
if ($this->hasPendingContentMigrations()) {
$notices[] = [
'type' => 'warning',
'message' => 'Des migrations de contenu sont en attente.',
];
}
$update = $this->checkRemoteVersion();
if ($update !== null) {
$notices[] = [
'type' => 'info',
'message' => 'Une nouvelle version de Folio est disponible : <strong>v' . htmlspecialchars($update) . '</strong>.',
];
}
return $notices;
}
// ─── Migrations de contenu en attente ────────────────────────────────────
private function hasPendingContentMigrations(): bool
{
$trackFile = $this->dataDir . '/.content_migrations.json';
$applied = [];
if (file_exists($trackFile)) {
$applied = json_decode((string) file_get_contents($trackFile), true) ?? [];
}
foreach (glob($this->baseDir . '/scripts/content/migration_*.php') ?: [] as $f) {
if (!isset($applied[basename($f)])) {
return true;
}
}
return false;
}
// ─── Vérification version distante (Gitea) ───────────────────────────────
/**
* Retourne le numéro de la version disponible si elle est supérieure
* à la version déployée, null sinon.
*/
private function checkRemoteVersion(): ?string
{
$repoUrl = folioRepoUrl();
if ($repoUrl === '') {
return null;
}
$deployedFile = $this->baseDir . '/public/version.txt';
if (!file_exists($deployedFile)) {
return null;
}
$deployedVer = trim((string) file_get_contents($deployedFile));
if ($deployedVer === '' || !preg_match('/^\d+\.\d+\.\d+/', $deployedVer)) {
return null;
}
$remoteVer = $this->fetchRemoteVersion($repoUrl);
if ($remoteVer === null) {
return null;
}
return version_compare($remoteVer, $deployedVer, '>') ? $remoteVer : null;
}
public function getBranch(): string
{
return folioUpdateBranch();
}
public function getLastChecked(): ?int
{
$cacheFile = $this->dataDir . '/.version_check_cache.json';
if (!file_exists($cacheFile)) {
return null;
}
$cache = json_decode((string) file_get_contents($cacheFile), true) ?? [];
return isset($cache['fetched_at']) ? (int) $cache['fetched_at'] : null;
}
public function clearCache(): void
{
$cacheFile = $this->dataDir . '/.version_check_cache.json';
if (file_exists($cacheFile)) {
unlink($cacheFile);
}
}
/**
* Récupère `public/version.txt` depuis le dépôt Gitea.
* Résultat mis en cache 1 h dans `data/.version_check_cache.json`.
*/
private function fetchRemoteVersion(string $repoUrl): ?string
{
$cacheFile = $this->dataDir . '/.version_check_cache.json';
$ttl = 3600;
if (file_exists($cacheFile)) {
$cache = json_decode((string) file_get_contents($cacheFile), true) ?? [];
if (isset($cache['fetched_at'], $cache['version'])
&& (time() - (int) $cache['fetched_at']) < $ttl
) {
return (string) $cache['version'];
}
}
$branch = $this->getBranch();
// URL du fichier brut : {repo}/raw/branch/{branch}/public/version.txt
$rawUrl = $repoUrl . '/raw/branch/' . $branch . '/public/version.txt';
$token = (string) ($_ENV['GITEA_TOKEN'] ?? getenv('GITEA_TOKEN') ?: '');
$opts = [
'http' => [
'timeout' => 5,
'header' => $token !== '' ? "Authorization: token $token" : '',
],
];
$body = @file_get_contents($rawUrl, false, stream_context_create($opts));
if ($body === false) {
return null;
}
$version = trim($body);
if (!preg_match('/^\d+\.\d+\.\d+/', $version)) {
return null;
}
file_put_contents(
$cacheFile,
json_encode(['fetched_at' => time(), 'version' => $version]) . "\n"
);
return $version;
}
}
+22 -6
View File
@@ -19,19 +19,35 @@ function slugify(string $s): string
return trim($s, '-');
}
/** Extrait le titre depuis le premier titre Markdown `# ...` du contenu. */
function extractMarkdownTitle(string $content): string
{
foreach (explode("\n", str_replace("\r\n", "\n", $content)) as $line) {
if (preg_match('/^#\s+(.+)/', rtrim($line), $m)) {
return trim($m[1]);
}
}
return '';
}
/**
* Diff ligne-à-ligne via LCS. Retourne un tableau de [op, line] où
* op est '=' (inchangé), '-' (supprimé), '+' (ajouté).
*/
function lineDiff(string $old, string $new): array
{
$a = explode("\n", $old);
$b = explode("\n", $new);
$n = count($a);
$m = count($b);
$old = str_replace("\r\n", "\n", $old);
$new = str_replace("\r\n", "\n", $new);
$a = explode("\n", $old);
$b = explode("\n", $new);
$n = count($a);
$m = count($b);
if ($n * $m > 300000) {
return [['!', "Diff trop grand ({$n}×{$m} lignes), affichage brut."], ['-', $old], ['+', $new]];
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]; }
return $diff;
}
$dp = array_fill(0, $n + 1, array_fill(0, $m + 1, 0));
+19
View File
@@ -0,0 +1,19 @@
<?php
// Page d'erreur 404 — à inclure après http_response_code(404).
// Aucune variable externe requise.
$title = '404 — ' . siteTitle();
$metaRobots = 'noindex, nofollow';
ob_start();
?>
<div class="container py-5 text-center">
<p class="display-1 fw-bold text-muted mb-0">404</p>
<h1 class="h3 mb-3">Page introuvable</h1>
<p class="text-muted mb-4">
Cette adresse ne correspond à aucun contenu.<br>
Vous avez peut-être suivi un ancien lien.
</p>
<a href="/" class="btn btn-primary">← Retour à l'accueil</a>
</div>
<?php
$content = ob_get_clean();
include __DIR__ . '/layout.php';
+292
View File
@@ -65,6 +65,14 @@ function adminStatusBadge(array $a, int $now): string
<a class="nav-link <?= $tab === 'searches' ? 'active' : '' ?>"
href="/admin/searches">Recherches</a>
</li>
<li class="nav-item">
<a class="nav-link <?= $tab === 'books' ? 'active' : '' ?>"
href="/admin/books">Livres</a>
</li>
<li class="nav-item">
<a class="nav-link <?= $tab === 'stats' ? 'active' : '' ?>"
href="/admin/stats">Statistiques</a>
</li>
<?php endif; ?>
</ul>
@@ -91,6 +99,71 @@ function adminStatusBadge(array $a, int $now): string
<?php endforeach; ?>
</div>
<!-- Version Folio ──────────────────────────────────────────────────────── -->
<?php
$_deployedVer = trim((string) @file_get_contents(BASE_PATH . '/public/version.txt'));
$_deployedLabel = $_deployedVer !== '' ? $_deployedVer : '—';
$_notices = isset($_updateChecker) ? $_updateChecker->adminNotices() : [];
$_branch = isset($_updateChecker) ? $_updateChecker->getBranch() : 'main';
$_lastChecked = isset($_updateChecker) ? $_updateChecker->getLastChecked() : null;
$_repoConfigured = folioRepoUrl() !== '';
$_remoteLabel = '—';
foreach ($_notices as $_n) {
if ($_n['type'] === 'info' && preg_match('/v([\d]+\.[\d]+\.[\d]+)/', $_n['message'], $_m)) {
$_remoteLabel = $_m[1];
}
}
?>
<div class="card mb-4">
<div class="card-header bg-transparent py-2 small fw-semibold">Moteur Folio</div>
<div class="card-body py-2">
<table class="table table-sm table-borderless mb-0 small">
<tbody>
<tr>
<th class="text-muted fw-normal ps-0 pe-2 text-nowrap" style="width:160px">Version déployée</th>
<td><?= htmlspecialchars($_deployedLabel) ?></td>
</tr>
<tr>
<th class="text-muted fw-normal ps-0 pe-2 text-nowrap">Dernière version disponible</th>
<td class="d-flex align-items-center gap-2 flex-wrap">
<span><?= htmlspecialchars($_remoteLabel) ?><?= $_remoteLabel !== '—' && $_remoteLabel !== $_deployedLabel ? ' <span class="badge bg-warning text-dark ms-1">Mise à jour disponible</span>' : '' ?></span>
<?php if ($_repoConfigured): ?>
<form method="POST" action="/?action=force_update_check" class="d-inline">
<button type="submit" class="btn btn-outline-secondary btn-sm py-0">Vérifier</button>
</form>
<?php else: ?>
<span class="text-muted small">(<code>FOLIO_REPO_URL</code> non configuré)</span>
<?php endif; ?>
</td>
</tr>
<tr>
<th class="text-muted fw-normal ps-0 pe-2 text-nowrap">Branche suivie</th>
<td><code><?= htmlspecialchars($_branch) ?></code><?= $_lastChecked !== null ? ' <span class="text-muted ms-2">· vérifié le ' . date('d/m/Y à H:i', $_lastChecked) . '</span>' : '' ?></td>
</tr>
<?php if (!empty($_notices)): ?>
<tr>
<th class="text-muted fw-normal ps-0 pe-2 align-top">Actions requises</th>
<td class="d-flex flex-wrap gap-2 align-items-center">
<?php foreach ($_notices as $_n): ?>
<?php if ($_n['type'] === 'warning'): ?>
<form method="POST" action="/?action=run_content_migrations">
<button type="submit" class="btn btn-warning btn-sm">Mettre à jour le contenu</button>
</form>
<?php endif; ?>
<?php endforeach; ?>
</td>
</tr>
<?php endif; ?>
<?php if (($_GET['notice'] ?? '') === 'migrated'): ?>
<tr><td colspan="2"><div class="alert alert-success py-1 mb-0 small">Migrations appliquées avec succès.</div></td></tr>
<?php elseif (($_GET['notice'] ?? '') === 'migration_error'): ?>
<tr><td colspan="2"><div class="alert alert-danger py-1 mb-0 small">Une erreur est survenue pendant la migration.</div></td></tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
<h5>Activité récente</h5>
<table class="table table-sm table-hover">
<thead>
@@ -415,6 +488,8 @@ function adminStatusBadge(array $a, int $now): string
<?php if (!empty($siteSettingsSaved)): ?>
<div class="alert alert-success py-2 mb-3">Paramètres enregistrés.</div>
<?php elseif (!empty($siteSettingsError)): ?>
<div class="alert alert-danger py-2 mb-3">Impossible d'enregistrer : le fichier n'est pas accessible en écriture.</div>
<?php endif; ?>
<div class="card" style="max-width:540px">
@@ -472,6 +547,33 @@ function adminStatusBadge(array $a, int $now): string
</div>
</div>
<?php if (($_GET['notice'] ?? '') === 'folio_saved'): ?>
<div class="alert alert-success py-2 mt-3 small">Configuration Folio enregistrée.</div>
<?php elseif (($_GET['notice'] ?? '') === 'folio_error'): ?>
<div class="alert alert-danger py-2 mt-3 small">Impossible d'enregistrer.</div>
<?php endif; ?>
<div class="card mt-4" style="max-width:540px">
<div class="card-header bg-transparent py-2 small fw-semibold">Mises à jour du moteur</div>
<div class="card-body">
<form method="POST" action="/?action=admin_save_folio_config">
<div class="mb-3">
<label class="form-label small fw-semibold mb-1">URL du dépôt Folio</label>
<input type="url" name="folio_repo_url" class="form-control form-control-sm font-monospace"
placeholder="https://git.abonnel.fr/cedricAbonnel/folio"
value="<?= htmlspecialchars(folioRepoUrl()) ?>">
<div class="form-text">Sans slash final. Laissez vide pour utiliser <code>FOLIO_REPO_URL</code> du .env.</div>
</div>
<div class="mb-3">
<label class="form-label small fw-semibold mb-1">Branche suivie</label>
<input type="text" name="folio_update_branch" class="form-control form-control-sm font-monospace"
placeholder="main"
value="<?= htmlspecialchars(folioUpdateBranch()) ?>">
</div>
<button type="submit" class="btn btn-primary btn-sm">Enregistrer</button>
</form>
</div>
</div>
<?php endif; ?>
<!-- ─────────────────────────── CATÉGORIES & TAGS ─────────────────── -->
@@ -627,6 +729,8 @@ foreach (COLOR_PALETTE_16 as $_i => $_rgb):
<?php if (isset($_GET['saved'])): ?>
<div class="alert alert-success py-2 mb-3">Paramètres SMTP enregistrés.</div>
<?php elseif (($_GET['error'] ?? '') === 'write'): ?>
<div class="alert alert-danger py-2 mb-3">Impossible d'enregistrer : le fichier n'est pas accessible en écriture.</div>
<?php endif; ?>
<div class="row g-4">
@@ -1005,6 +1109,29 @@ foreach (COLOR_PALETTE_16 as $_i => $_rgb):
<!-- ─────────────────────────── RECHERCHES ─────────────────────────── -->
<?php if ($tab === 'searches' && isAdmin()): ?>
<?php if (isset($_GET['saved'])): ?>
<div class="alert alert-success py-2 mb-3">Configuration enregistrée.</div>
<?php elseif (($_GET['error'] ?? '') === 'write'): ?>
<div class="alert alert-danger py-2 mb-3">Impossible d'enregistrer : le fichier n'est pas accessible en écriture.</div>
<?php endif; ?>
<div class="card mb-4" style="max-width:540px">
<div class="card-header bg-transparent py-2 small fw-semibold">Configuration des logs</div>
<div class="card-body py-3">
<form method="post" action="/?action=admin_save_searches_config">
<div class="mb-3">
<label for="apache-access-log" class="form-label small fw-semibold">Pattern des logs d'accès</label>
<input type="text" id="apache-access-log" name="apache_access_log"
class="form-control form-control-sm font-monospace"
value="<?= htmlspecialchars(apacheAccessLog()) ?>"
maxlength="200" placeholder="ex : *-access.log">
<div class="form-text">Pattern glob dans <code>/var/log/apache2/</code>. Les rotations (<code>.gz</code>, <code>.tar.gz</code>) sont automatiquement incluses.</div>
</div>
<button type="submit" class="btn btn-primary btn-sm">Enregistrer</button>
</form>
</div>
</div>
<div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
<h5 class="mb-0">Termes recherchés
<span class="badge bg-secondary ms-1"><?= count($adminData['search_terms'] ?? []) ?></span>
@@ -1061,6 +1188,171 @@ foreach (COLOR_PALETTE_16 as $_i => $_rgb):
<?php endif; ?>
<!-- ─────────────────────────── LIVRES ─────────────────────────── -->
<?php if ($tab === 'books' && isAdmin()): ?>
<?php if (($_GET['deleted'] ?? '') === '1'): ?>
<div class="alert alert-success py-2 small mb-3">Livre supprimé.</div>
<?php endif; ?>
<div class="row g-4">
<!-- Liste des livres -->
<div class="col-md-4">
<div class="d-flex justify-content-between align-items-center mb-3">
<h5 class="mb-0">
Livres
<span class="badge bg-secondary ms-1"><?= count($adminData['books']) ?></span>
</h5>
<a href="/admin/books?new=1" class="btn btn-sm btn-primary">+ Nouveau</a>
</div>
<?php if (empty($adminData['books'])): ?>
<p class="text-muted small">Aucun livre pour l'instant.</p>
<?php else: ?>
<div class="list-group">
<?php foreach ($adminData['books'] as $bk):
$isEdited = ($adminData['edit_book']['slug'] ?? '') === $bk['slug'];
?>
<a href="/admin/books?edit=<?= rawurlencode($bk['slug']) ?>"
class="list-group-item list-group-item-action<?= $isEdited ? ' active' : '' ?>">
<div class="fw-medium"><?= htmlspecialchars($bk['title']) ?></div>
<div class="small <?= $isEdited ? 'text-white-50' : 'text-muted' ?>">
<?= count($bk['articles'] ?? []) ?> page<?= count($bk['articles'] ?? []) > 1 ? 's' : '' ?>
· <a href="/book/<?= rawurlencode($bk['slug']) ?>" target="_blank"
class="<?= $isEdited ? 'text-white-50' : 'text-muted' ?>">Voir ↗</a>
</div>
</a>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<!-- Formulaire édition / création -->
<div class="col-md-8">
<?php if (($adminData['edit_book'] ?? null) !== null): ?>
<?php $eb = $adminData['edit_book']; ?>
<h5>Modifier le livre</h5>
<?php if (($_GET['saved'] ?? '') === '1'): ?>
<div class="alert alert-success py-2 small">Livre sauvegardé.</div>
<?php endif; ?>
<form method="POST" action="/?action=book_save">
<input type="hidden" name="slug" value="<?= htmlspecialchars($eb['slug']) ?>">
<div class="mb-3">
<label class="form-label small fw-medium">Slug (identifiant URL)</label>
<input type="text" class="form-control bg-light" value="<?= htmlspecialchars($eb['slug']) ?>" readonly>
<div class="form-text">Le slug ne peut pas être modifié après création.</div>
</div>
<div class="mb-3">
<label class="form-label small fw-medium">Titre</label>
<input type="text" name="title" class="form-control" required
value="<?= htmlspecialchars($eb['title'] ?? '') ?>">
</div>
<div class="mb-3">
<label class="form-label small fw-medium">Description</label>
<textarea name="description" class="form-control" rows="2"><?= htmlspecialchars($eb['description'] ?? '') ?></textarea>
</div>
<div class="mb-3">
<label class="form-label small fw-medium">Pages (slugs dans l'ordre, un par ligne)</label>
<textarea name="articles" class="form-control font-monospace"
id="book-articles-ta"
rows="<?= max(6, count($eb['articles'] ?? []) + 2) ?>"><?= htmlspecialchars(implode("\n", $eb['articles'] ?? [])) ?></textarea>
<div class="form-text">Un slug par ligne. L'ordre définit la navigation précédent/suivant.</div>
</div>
<div class="mb-3">
<label class="form-label small fw-medium">Ajouter une page existante</label>
<select class="form-select" onchange="bookAddArticle(this)">
<option value="">— Choisir un article —</option>
<?php
$alreadyIn = $eb['articles'] ?? [];
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)' : '' ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="d-flex gap-2">
<button type="submit" class="btn btn-primary">Sauvegarder</button>
<a href="/book/<?= rawurlencode($eb['slug']) ?>" target="_blank"
class="btn btn-outline-secondary">Voir le livre ↗</a>
</div>
</form>
<hr class="my-4">
<form method="POST" action="/?action=book_delete"
data-confirm="Supprimer le livre « <?= htmlspecialchars($eb['title']) ?> » ? Les pages resteront intactes.">
<input type="hidden" name="slug" value="<?= htmlspecialchars($eb['slug']) ?>">
<button type="submit" class="btn btn-outline-danger btn-sm">🗑 Supprimer ce livre</button>
</form>
<script>
function bookAddArticle(sel) {
var slug = sel.value;
if (!slug) return;
var ta = document.getElementById('book-articles-ta');
var lines = ta.value.split('\n').map(function(s) { return s.trim(); }).filter(Boolean);
if (lines.indexOf(slug) === -1) {
lines.push(slug);
ta.value = lines.join('\n');
}
sel.value = '';
}
</script>
<?php elseif (isset($_GET['new'])): ?>
<h5>Nouveau livre</h5>
<form method="POST" action="/?action=book_save">
<div class="mb-3">
<label class="form-label small fw-medium">Slug (identifiant URL)</label>
<input type="text" name="slug" class="form-control" required
placeholder="mon-livre" pattern="[a-z0-9][a-z0-9-]*">
<div class="form-text">Minuscules, chiffres, tirets. Exemple : <code>esp8266</code></div>
</div>
<div class="mb-3">
<label class="form-label small fw-medium">Titre</label>
<input type="text" name="title" class="form-control" required placeholder="Titre du livre">
</div>
<div class="mb-3">
<label class="form-label small fw-medium">Description (optionnelle)</label>
<textarea name="description" class="form-control" rows="2" placeholder="Courte description…"></textarea>
</div>
<input type="hidden" name="articles" value="">
<div class="d-flex gap-2">
<button type="submit" class="btn btn-primary">Créer le livre</button>
<a href="/admin/books" class="btn btn-outline-secondary">Annuler</a>
</div>
</form>
<?php else: ?>
<p class="text-muted mt-2">
<?php if (!empty($adminData['books'])): ?>
Sélectionnez un livre à gauche pour le modifier, ou créez-en un nouveau.
<?php else: ?>
Cliquez sur <strong>+ Nouveau</strong> pour créer votre premier livre.
<?php endif; ?>
</p>
<?php endif; ?>
</div>
</div>
<?php endif; ?>
<?php if ($tab === 'stats' && isAdmin()): ?>
<?php include __DIR__ . '/admin_stats.php'; ?>
<?php endif; ?>
<?php
$content = ob_get_clean();
$title = 'Administration — ' . siteTitle();
+241
View File
@@ -0,0 +1,241 @@
<?php
$_statsSaved = isset($_GET['saved']);
$_statsError = ($_GET['error'] ?? '') === 'write';
$_readable = $adminData['stats_readable'] ?? false;
$_pages = $adminData['stats_pages'] ?? [];
$_books = $adminData['stats_books'] ?? [];
$_asList = $adminData['stats_as'] ?? [];
$_asGroups = $adminData['stats_as_groups'] ?? [];
$_groups = $adminData['as_groups'] ?? [];
$_activeGroup = trim($_GET['group'] ?? '');
?>
<?php if ($_statsSaved): ?>
<div class="alert alert-success py-2 mb-3">Configuration enregistrée.</div>
<?php elseif ($_statsError): ?>
<div class="alert alert-danger py-2 mb-3">Impossible d'enregistrer : fichier non accessible en écriture.</div>
<?php endif; ?>
<?php if (!$_readable): ?>
<div class="alert alert-warning">
Les logs ne sont pas lisibles. Vérifiez le pattern dans l'onglet <a href="/admin/searches">Recherches</a>
et que <code>www-data</code> appartient au groupe <code>adm</code>.
</div>
<?php else: ?>
<p class="text-muted small mb-4">14 derniers jours · cache 10 min</p>
<div class="row g-4">
<!-- Pages -->
<div class="col-lg-6">
<div class="card h-100">
<div class="card-header bg-transparent py-2 small fw-semibold d-flex justify-content-between">
<span>Pages les plus visitées</span>
<span class="text-muted"><?= count($_pages) ?> URLs</span>
</div>
<div class="card-body p-0">
<?php if (empty($_pages)): ?>
<p class="text-muted p-3 mb-0">Aucune donnée.</p>
<?php else: ?>
<div class="table-responsive">
<table class="table table-sm table-hover mb-0 small">
<tbody>
<?php
$maxP = max($_pages) ?: 1;
$rankP = 0;
foreach ($_pages as $url => $hits):
$rankP++;
$slug = rawurldecode(substr($url, 6));
$pct = round($hits / $maxP * 100);
?>
<tr>
<td class="text-muted ps-3" style="width:2rem"><?= $rankP ?></td>
<td>
<a href="<?= htmlspecialchars($url) ?>" target="_blank"
class="text-decoration-none text-truncate d-block" style="max-width:260px"
title="<?= htmlspecialchars($slug) ?>">
<?= htmlspecialchars($slug) ?>
</a>
<div class="progress mt-1" style="height:3px">
<div class="progress-bar" style="width:<?= $pct ?>%"></div>
</div>
</td>
<td class="text-end fw-semibold pe-3"><?= number_format($hits, 0, ',', '\u{202F}') ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div>
</div>
</div>
<!-- Livres -->
<div class="col-lg-6">
<div class="card h-100">
<div class="card-header bg-transparent py-2 small fw-semibold d-flex justify-content-between">
<span>Livres consultés</span>
<span class="text-muted"><?= count($_books) ?> livres</span>
</div>
<div class="card-body p-0">
<?php if (empty($_books)): ?>
<p class="text-muted p-3 mb-0">Aucun accès à <code>/book/</code> dans les logs.</p>
<?php else: ?>
<div class="table-responsive">
<table class="table table-sm table-hover mb-0 small">
<tbody>
<?php
$maxB = max($_books) ?: 1;
$rankB = 0;
foreach ($_books as $url => $hits):
$rankB++;
$slug = rawurldecode(substr($url, 6));
$pct = round($hits / $maxB * 100);
?>
<tr>
<td class="text-muted ps-3" style="width:2rem"><?= $rankB ?></td>
<td>
<a href="<?= htmlspecialchars($url) ?>" target="_blank"
class="text-decoration-none text-truncate d-block" style="max-width:260px"
title="<?= htmlspecialchars($slug) ?>">
<?= htmlspecialchars($slug) ?>
</a>
<div class="progress mt-1" style="height:3px">
<div class="progress-bar bg-success" style="width:<?= $pct ?>%"></div>
</div>
</td>
<td class="text-end fw-semibold pe-3"><?= number_format($hits, 0, ',', '\u{202F}') ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div>
</div>
</div>
</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 ?>
<!-- Groupes de réseaux -->
<div class="card mt-4" style="max-width:600px">
<div class="card-header bg-transparent py-2 small fw-semibold">Groupes de réseaux</div>
<div class="card-body">
<p class="text-muted small">Regroupez plusieurs réseaux sous un label. Chaque ligne est un motif cherché dans le nom du réseau (insensible à la casse).</p>
<form method="post" action="/?action=admin_save_as_groups" id="as-groups-form">
<div id="as-groups-list">
<?php foreach ($_groups as $gi => $g): ?>
<div class="as-group-row border rounded p-3 mb-3">
<div class="d-flex align-items-center gap-2 mb-2">
<input type="text" name="as_group_label[]" class="form-control form-control-sm"
placeholder="Label (ex : Opérateurs FR)"
value="<?= htmlspecialchars($g['label']) ?>" required>
<button type="button" class="btn btn-outline-danger btn-sm as-group-delete" title="Supprimer">✕</button>
</div>
<textarea name="as_group_patterns[]" class="form-control form-control-sm font-monospace"
rows="3" placeholder="Un motif par ligne&#10;ex : Free SAS&#10;Orange&#10;SFR"><?= htmlspecialchars(implode("\n", $g['patterns'])) ?></textarea>
</div>
<?php endforeach; ?>
</div>
<div class="d-flex gap-2 mt-2">
<button type="button" id="as-group-add" class="btn btn-outline-secondary btn-sm">+ Ajouter un groupe</button>
<button type="submit" class="btn btn-primary btn-sm">Enregistrer</button>
</div>
</form>
</div>
</div>
<template id="as-group-tpl">
<div class="as-group-row border rounded p-3 mb-3">
<div class="d-flex align-items-center gap-2 mb-2">
<input type="text" name="as_group_label[]" class="form-control form-control-sm"
placeholder="Label (ex : Moteurs de recherche)" required>
<button type="button" class="btn btn-outline-danger btn-sm as-group-delete" title="Supprimer">✕</button>
</div>
<textarea name="as_group_patterns[]" class="form-control form-control-sm font-monospace"
rows="3" placeholder="Un motif par ligne&#10;ex : Googlebot&#10;Bingbot"></textarea>
</div>
</template>
<script>
document.getElementById('as-group-add').addEventListener('click', () => {
const tpl = document.getElementById('as-group-tpl').content.cloneNode(true);
document.getElementById('as-groups-list').appendChild(tpl);
});
document.getElementById('as-groups-list').addEventListener('click', e => {
if (e.target.classList.contains('as-group-delete')) {
e.target.closest('.as-group-row').remove();
}
});
</script>
+62
View File
@@ -0,0 +1,62 @@
<?php ob_start(); ?>
<div class="book-page">
<div class="book-header mb-4">
<p class="book-label">Livre</p>
<h1 class="h2 mb-2"><?= htmlspecialchars($book['title']) ?></h1>
<?php if (!empty($book['description'])): ?>
<p class="lead text-muted"><?= htmlspecialchars($book['description']) ?></p>
<?php endif; ?>
<p class="text-muted small"><?= count($bookArticles) ?> page<?= count($bookArticles) > 1 ? 's' : '' ?></p>
</div>
<?php if (empty($bookArticles)): ?>
<p class="text-muted">Ce livre ne contient pas encore de pages publiées.</p>
<?php else: ?>
<ol class="book-chapters">
<?php foreach ($bookArticles as $i => $a):
$cat = trim($a['category'] ?? '');
$gradient = coverGradient($cat !== '' ? $cat : $a['uuid'], $allCats);
$cover = $a['cover'] ?? '';
$date = $a['published_at'] ? date('d/m/Y', strtotime((string)$a['published_at'])) : '';
?>
<li class="book-chapter">
<a href="/post/<?= rawurlencode($a['slug'] ?? '') ?>" class="book-chapter-link">
<span class="book-chapter-num"><?= $i + 1 ?></span>
<div class="book-chapter-thumb" style="<?= $cover !== ''
? 'background-image:url(/file?uuid=' . rawurlencode($a['uuid']) . '&name=' . rawurlencode($cover) . ');background-size:cover;background-position:center'
: 'background:' . htmlspecialchars($gradient) ?>">
</div>
<div class="book-chapter-body">
<div class="book-chapter-title"><?= htmlspecialchars($a['title'] ?? '') ?></div>
<div class="book-chapter-meta">
<?php if ($cat !== ''): ?><?= htmlspecialchars($cat) ?><?php endif; ?>
<?php if ($cat !== '' && $date !== ''): ?> · <?php endif; ?>
<?php if ($date !== ''): ?><?= $date ?><?php endif; ?>
</div>
<?php if (!$a['published']): ?>
<span class="badge bg-secondary small">Brouillon</span>
<?php endif; ?>
</div>
</a>
</li>
<?php endforeach; ?>
</ol>
<?php endif; ?>
<?php if (function_exists('isAdmin') && isAdmin()): ?>
<div class="mt-4 text-end">
<a href="/admin/books?edit=<?= rawurlencode($book['slug']) ?>" class="btn btn-sm btn-outline-secondary">
✎ Modifier ce livre
</a>
</div>
<?php endif; ?>
</div>
<?php
$content = ob_get_clean();
$title = htmlspecialchars($book['title']) . ' — ' . siteTitle();
$canonical = rtrim(APP_URL, '/') . '/book/' . rawurlencode($book['slug']);
include __DIR__ . '/layout.php';
+1 -1
View File
@@ -60,7 +60,7 @@ $preSource = $step2Meta['canonical'] ?? $step2Meta['source'] ?? $step2Url;
<div class="mb-4">
<p class="fw-semibold small mb-2">Aperçu de la page</p>
<?php
$previewMtime = @filemtime(BASE_PATH . '/data/' . $step2Article['uuid'] . '/files/' . $step2Screenshot) ?: time();
$previewMtime = @filemtime(DATA_PATH . '/' . $step2Article['uuid'] . '/files/' . $step2Screenshot) ?: time();
?>
<img src="/file?uuid=<?= rawurlencode($step2Article['uuid']) ?>&name=<?= rawurlencode($step2Screenshot) ?>&v=<?= $previewMtime ?>"
class="img-fluid rounded shadow-sm d-block"
+19
View File
@@ -106,6 +106,25 @@ $_layoutCurrentCat = trim($_GET['cat'] ?? '');
</nav>
</header>
<?php if (function_exists('isAdmin') && isAdmin() && isset($_updateChecker)):
$_adminNotices = $_updateChecker->adminNotices();
foreach ($_adminNotices as $_notice):
$_isWarning = $_notice['type'] === 'warning'; ?>
<div class="alert alert-<?= $_isWarning ? 'warning' : 'info' ?> alert-dismissible rounded-0 border-0 border-bottom py-2 mb-0 small" role="alert">
<div class="container-fluid d-flex align-items-center gap-2 flex-wrap">
<span><?= $_notice['message'] ?></span>
<?php if ($_isWarning): ?>
<form method="POST" action="/?action=run_content_migrations" class="d-inline">
<button type="submit" class="btn btn-warning btn-sm py-0">Mettre à jour</button>
</form>
<?php else: ?>
<a href="/admin?tab=dashboard" class="btn btn-outline-primary btn-sm py-0">Voir dans l'admin</a>
<?php endif; ?>
<button type="button" class="btn-close ms-auto" data-bs-dismiss="alert" aria-label="Fermer"></button>
</div>
</div>
<?php endforeach; endif; ?>
<main class="<?= htmlspecialchars($mainClass ?? 'container') ?>" role="main">
<?= $content ?>
</main>
+23
View File
@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mise à jour en cours</title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:system-ui,sans-serif;min-height:100vh;display:flex;align-items:center;justify-content:center;background:#f8f9fa;color:#212529}
.box{text-align:center;padding:2.5rem 2rem;max-width:420px}
.icon{font-size:2.5rem;margin-bottom:1rem}
h1{font-size:1.4rem;font-weight:600;margin-bottom:.6rem}
p{color:#6c757d;line-height:1.6}
</style>
</head>
<body>
<div class="box">
<div class="icon">⚙️</div>
<h1>Mise à jour en cours</h1>
<p>Le site est temporairement indisponible pendant une mise à jour.<br>Merci de réessayer dans quelques instants.</p>
</div>
</body>
</html>
+51 -1
View File
@@ -9,6 +9,8 @@ $_accentMap = [
];
$_tocItems = [];
$_tocSeen = [];
// Le titre H1 est déjà affiché par le template ; on le retire du rendu.
$_rawForRender = preg_replace('/^\s*# [^\n]*\n*/u', '', $rawContent);
$_renderedContent = preg_replace_callback(
'/<(h[23])>(.+?)<\/h[23]>/i',
function ($m) use (&$_tocItems, &$_tocSeen, $_accentMap) {
@@ -31,7 +33,7 @@ $_renderedContent = preg_replace_callback(
$_tocItems[] = ['level' => $level, 'text' => $plain, 'id' => $id];
return "<{$tag} id=\"" . htmlspecialchars($id) . "\">{$inner}</{$tag}>";
},
$Parsedown->text($rawContent)
$Parsedown->text($_rawForRender)
);
ob_start();
@@ -68,6 +70,19 @@ $externalLinks = $article['external_links'] ?? [];
<!-- Colonne principale -->
<div class="col">
<?php if (!empty($bookContext)): ?>
<div class="book-article-banner mb-3">
<a href="/book/<?= rawurlencode($bookContext['book']['slug']) ?>" class="book-article-banner-link">
<span class="book-article-banner-icon">📖</span>
<span class="book-article-banner-text">
Chapitre <?= $bookContext['position'] ?>/<?= $bookContext['total'] ?> —
<strong><?= htmlspecialchars($bookContext['book']['title']) ?></strong>
</span>
<span class="book-article-banner-cta">Voir le sommaire →</span>
</a>
</div>
<?php endif; ?>
<div class="card mb-4">
<?php if (!$article['published']): ?>
<div class="draft-ribbon">Brouillon</div>
@@ -161,6 +176,41 @@ $hasSources = (!empty($externalLinks) || !empty($files))
<div class="card-text post-content">
<?= $_renderedContent ?>
</div>
<?php if (!empty($bookContext)): ?>
<nav class="book-chapter-nav">
<div class="book-chapter-nav-inner">
<?php if (!empty($bookContext['prev_article'])): ?>
<a href="/post/<?= rawurlencode($bookContext['prev_article']['slug'] ?? '') ?>"
class="book-nav-btn book-nav-btn--prev">
<span class="book-nav-dir">← Précédent</span>
<span class="book-nav-title"><?= htmlspecialchars($bookContext['prev_article']['title'] ?? '') ?></span>
</a>
<?php else: ?>
<span class="book-nav-btn book-nav-btn--prev book-nav-btn--disabled">
<span class="book-nav-dir">Premier chapitre</span>
</span>
<?php endif; ?>
<a href="/book/<?= rawurlencode($bookContext['book']['slug']) ?>"
class="book-nav-toc" title="Sommaire du livre">
</a>
<?php if (!empty($bookContext['next_article'])): ?>
<a href="/post/<?= rawurlencode($bookContext['next_article']['slug'] ?? '') ?>"
class="book-nav-btn book-nav-btn--next">
<span class="book-nav-dir">Suivant →</span>
<span class="book-nav-title"><?= htmlspecialchars($bookContext['next_article']['title'] ?? '') ?></span>
</a>
<?php else: ?>
<span class="book-nav-btn book-nav-btn--next book-nav-btn--disabled">
<span class="book-nav-dir">Dernier chapitre</span>
</span>
<?php endif; ?>
</div>
</nav>
<?php endif; ?>
</div>
</div>
+1 -1
View File
@@ -12,7 +12,7 @@ $_base = $mode === 'create' ? '/new/' . rawurlencode($uuid ?? '') : '/edit/' . r
$_wActive = ($_wn === $step);
$_wDone = ($_wn < $step);
$_wHref = ($_wDone && ($uuid ?? '') !== '') ? htmlspecialchars($_base . '/' . $_wn) : null;
?>
?>
<?php if ($_wi > 0): ?>
<span class="wizard-sep text-muted px-1"></span>
<?php endif; ?>
+5 -12
View File
@@ -19,7 +19,7 @@ $_hasUuid = $_wizUuid !== '';
<!-- En-tête avec boutons ────────────────────────────────────────────────── -->
<div class="d-flex align-items-center justify-content-between gap-3 mb-4 flex-wrap">
<div>
<h1 class="h4 mb-0"><?= $mode === 'create' ? 'Nouvel article' : htmlspecialchars('Modifier — ' . ($article['title'] ?? '')) ?></h1>
<h1 class="h4 mb-0" id="wz-page-title"><?= $mode === 'create' ? 'Nouvel article' : 'Modifier' ?></h1>
<?php if ($_hasUuid): ?>
<span id="autosave-indicator" class="text-muted small"></span>
<?php endif; ?>
@@ -39,19 +39,12 @@ $_hasUuid = $_wizUuid !== '';
<div class="row g-3 align-items-start">
<div class="col-lg-9">
<!-- Titre ─────────────────────────────────────────────────────────────── -->
<div class="mb-3">
<label for="wz-title" class="form-label fw-semibold">Titre</label>
<input type="text" class="form-control form-control-lg" id="wz-title" name="title" required
value="<?= htmlspecialchars($title ?? '') ?>"
placeholder="Titre de l'article…">
</div>
<!-- Contenu ──────────────────────────────────────────────────────────── -->
<div class="mb-3">
<label for="wz-content" class="form-label fw-semibold">Contenu <small class="text-muted fw-normal">(Markdown)</small></label>
<textarea class="form-control font-monospace" id="wz-content" name="content" rows="18"
style="min-height:320px"><?= htmlspecialchars($content ?? '') ?></textarea>
style="min-height:320px"
placeholder="# Titre de l'article&#10;&#10;Votre contenu ici…"><?= htmlspecialchars($content ?? '') ?></textarea>
</div>
</div><!-- /col-lg-9 -->
@@ -92,7 +85,7 @@ $_hasUuid = $_wizUuid !== '';
<?php foreach ($existingFiles as $_fi => $_f):
$_fUrl = '/file?uuid=' . rawurlencode($_wizUuid) . '&name=' . rawurlencode($_f['name']);
$_isCover = ($_f['name'] === $_coverFile);
?>
?>
<div class="border rounded p-1 d-flex align-items-center gap-2" style="max-width:220px">
<?php if ($_f['is_image']): ?>
<img src="<?= htmlspecialchars($_fUrl) ?>" alt="" style="width:36px;height:36px;object-fit:cover;border-radius:3px;flex-shrink:0<?= $_isCover ? ';outline:2px solid #0d6efd' : '' ?>">
@@ -129,7 +122,7 @@ $_hasUuid = $_wizUuid !== '';
<div class="d-flex flex-wrap gap-2">
<?php foreach ($_sidebarImgs as $_img):
$_iUrl = '/file?uuid=' . rawurlencode($_wizUuid) . '&name=' . rawurlencode($_img['name']);
?>
?>
<img src="<?= htmlspecialchars($_iUrl) ?>"
alt="<?= htmlspecialchars($_img['name']) ?>"
title="<?= htmlspecialchars($_img['name']) ?>"
+1 -1
View File
@@ -39,7 +39,7 @@ $_formAction = $mode === 'create' ? '/new/' . rawurlencode($uuid) . '/3' : '/edi
<div class="d-flex flex-wrap gap-2">
<?php foreach ($allCategories as $_cat => $_count):
$_isPriv = in_array($_cat, $privateCats ?? [], true);
?>
?>
<button type="button" class="btn btn-sm btn-outline-secondary wz-cat-pick<?= ($_cat === ($category ?? '')) ? ' active' : '' ?>"
data-cat="<?= htmlspecialchars($_cat) ?>">
<?= htmlspecialchars($_cat) ?>
+2 -2
View File
@@ -53,7 +53,7 @@ $_detectedInText = array_keys(array_filter($_candidates, fn ($_c) => !$_c['known
<?php foreach ($flatTagValues as $_v):
$_isActive = in_array($_v, $flatArticleTags, true);
$_inText = in_array($_v, $_knownInText, true);
?>
?>
<button type="button"
class="btn btn-sm <?= $_isActive ? 'btn-secondary' : 'btn-outline-secondary' ?> wz-tag-pill py-0"
data-value="<?= htmlspecialchars($_v) ?>"
@@ -80,7 +80,7 @@ $_detectedInText = array_keys(array_filter($_candidates, fn ($_c) => !$_c['known
'proper' => 'NP',
default => '',
};
?>
?>
<button type="button"
class="btn btn-sm <?= $_isActive ? 'btn-info' : 'btn-outline-info' ?> wz-tag-pill py-0"
data-value="<?= htmlspecialchars($_v) ?>"
+1 -1
View File
@@ -106,7 +106,7 @@ $_catVal = trim($category ?? '');
<div class="d-flex flex-wrap gap-2">
<?php foreach ($_imgFiles as $_f):
$_fUrl = '/file?uuid=' . rawurlencode($uuid) . '&name=' . rawurlencode($_f['name']);
?>
?>
<label class="position-relative" style="cursor:pointer">
<input type="radio" name="cover_file" value="<?= htmlspecialchars($_f['name']) ?>"
class="position-absolute" style="opacity:0" <?= ($_f['name'] === $_coverFile) ? 'checked' : '' ?>>
+4 -3
View File
@@ -60,7 +60,7 @@ $_slugFinal = ($titleChanged && $autoSlug !== $postSlug) ? $autoSlug : $postSlu
}
}
}
?>
?>
<div class="d-flex gap-3 mb-1 small">
<span class="diff-del px-2 py-1 rounded"> Supprimé</span>
<span class="diff-ins px-2 py-1 rounded">+ Ajouté</span>
@@ -69,11 +69,12 @@ $_slugFinal = ($titleChanged && $autoSlug !== $postSlug) ? $autoSlug : $postSlu
<?php $inEllipsis = false;
for ($i = 0; $i < $total; $i++):
[$op, $line] = $diffLines[$i];
?>
?>
<?php if (!isset($show[$i])): ?>
<?php if (!$inEllipsis): $inEllipsis = true; ?>
<div class="diff-ellipsis text-muted px-2">⋯</div>
<?php endif; continue; ?>
<?php endif;
continue; ?>
<?php else: $inEllipsis = false; endif; ?>
<?php if ($op === '-'): ?>
<div class="diff-del px-2">&nbsp;<?= htmlspecialchars($line) ?></div>