diff --git a/app/Controllers/AuthController.php b/app/Controllers/AuthController.php
index 58b7421..c70227b 100644
--- a/app/Controllers/AuthController.php
+++ b/app/Controllers/AuthController.php
@@ -21,8 +21,12 @@ class AuthController extends BaseController
$username = trim((string) ($this->f3->get('POST.username') ?? ''));
$password = (string) ($this->f3->get('POST.password') ?? '');
- $user = (new User($this->db))->findByUsername($username);
- if ($user === null || !password_verify($password, $user['password_hash'])) {
+ // User étend DB\SQL\Mapper — inutile de recréer un Mapper générique.
+ // Le 3e argument du constructeur Auth est le callback de comparaison.
+ $user = new User();
+ $auth = new \Auth($user, ['id' => 'username', 'pw' => 'password_hash'], 'password_verify');
+
+ if (!$auth->login($username, $password)) {
usleep(1_500_000); // 1,5 s — ralentit le brute-force
$this->flash('error', 'Identifiants invalides.');
$this->f3->reroute('@login');
@@ -30,7 +34,7 @@ class AuthController extends BaseController
}
session_regenerate_id(true); // Prévient la fixation de session.
- $this->f3->set('SESSION.user_id', $user['id']);
+ $this->f3->set('SESSION.user_id', $user->id);
$this->flash('success', 'Connexion réussie.');
$this->f3->reroute('@dashboard');
}
diff --git a/app/Controllers/BaseController.php b/app/Controllers/BaseController.php
index db1922a..ee5f4a3 100644
--- a/app/Controllers/BaseController.php
+++ b/app/Controllers/BaseController.php
@@ -5,53 +5,51 @@ declare(strict_types=1);
abstract class BaseController
{
protected Base $f3;
- protected DB\SQL $db;
-
- // false = pas encore résolu, null = résolu sans utilisateur.
- private array|false|null $resolvedUser = false;
public function __construct()
{
$this->f3 = Base::instance();
- $this->db = $this->f3->get('DB');
}
protected function render(string $view, array $data = [], int $cacheTtl = 0): void
{
- $user = $this->currentUser();
-
// Les pages publiques restent cacheables avec le TTL demandé.
// Si un utilisateur est connecté, le layout dépend de la session
// (navigation admin, déconnexion + CSRF) : on force expire(0)
// pour ne pas servir ce rendu à d'autres visiteurs.
- $this->f3->expire($user !== null ? 0 : $cacheTtl);
+ $this->f3->expire($this->currentUser() !== null ? 0 : $cacheTtl);
$flash = array_key_exists('flash', $data) && is_array($data['flash'])
? $data['flash']
: $this->pullFlash();
+ // currentUser est déjà dans le hive (posé par currentUser()).
+ // Le template y accède directement via {{ @currentUser }}.
$this->f3->mset($data + [
'view' => $view,
- 'currentUser' => $user,
'flash' => $flash,
'metaDescription' => null,
'adminMode' => false,
]);
- // Recopier @CSRF en session pour que verifyCsrf() puisse
- // vérifier le jeton soumis au POST suivant.
- $this->f3->copy('CSRF', 'SESSION.csrf');
+ // F3 régénère @CSRF à chaque requête (variable hive uniquement).
+ // On le persiste en session pour que verifyCsrf() puisse comparer
+ // le jeton soumis au POST suivant.
+ $this->f3->copy('CSRF', 'SESSION.csrf_token');
echo Template::instance()->render('layout.html');
}
+ // Résout l'utilisateur courant une seule fois par requête et le
+ // stocke dans le hive — accessible partout, y compris les templates.
protected function currentUser(): ?array
{
- if ($this->resolvedUser === false) {
+ if (!$this->f3->exists('currentUser', $user)) {
$userId = (int) ($this->f3->get('SESSION.user_id') ?? 0);
- $this->resolvedUser = $userId > 0 ? (new User($this->db))->findById($userId) : null;
+ $user = $userId > 0 ? (new User())->findById($userId) : null;
+ $this->f3->set('currentUser', $user);
}
- return $this->resolvedUser;
+ return $user;
}
protected function requireAuth(): void
@@ -64,12 +62,13 @@ abstract class BaseController
$this->f3->reroute('@login');
}
+ // F3 copy() persiste le jeton CSRF en session au rendu (voir render()).
+ // On compare ici le jeton soumis par le formulaire avec celui en session.
protected function verifyCsrf(): void
{
$submitted = (string) ($this->f3->get('POST.csrf_token') ?? '');
- $expected = (string) ($this->f3->get('SESSION.csrf') ?? '');
+ $expected = (string) ($this->f3->get('SESSION.csrf_token') ?? '');
- // hash_equals : comparaison en temps constant contre les attaques temporelles.
if ($submitted !== '' && $expected !== '' && hash_equals($expected, $submitted)) {
return;
}
@@ -77,15 +76,14 @@ abstract class BaseController
$this->f3->error(400, 'Jeton CSRF invalide.');
}
+ // Empile un message flash — permet plusieurs messages par requête.
protected function flash(string $type, string $message): void
{
- $this->f3->set('SESSION.flash', ['type' => $type, 'message' => $message]);
+ $this->f3->push('SESSION.flash', ['type' => $type, 'message' => $message]);
}
- private function pullFlash(): ?array
+ private function pullFlash(): array
{
- $flash = $this->f3->get('SESSION.flash');
- $this->f3->clear('SESSION.flash');
- return is_array($flash) ? $flash : null;
+ return $this->f3->pull('SESSION.flash') ?: [];
}
}
diff --git a/app/Controllers/DashboardController.php b/app/Controllers/DashboardController.php
index 5b59753..b1aeae7 100644
--- a/app/Controllers/DashboardController.php
+++ b/app/Controllers/DashboardController.php
@@ -12,8 +12,8 @@ class DashboardController extends BaseController
public function index(): void
{
$page = max(1, (int) ($this->f3->get('GET.page') ?? 1));
- $media = new Media($this->db);
- $result = (new Post($this->db))->paginateList($page, 24, $media);
+ $media = new Media();
+ $result = (new Post())->paginateList($page, 24, $media);
$this->render('admin/dashboard.html', [
'pageTitle' => 'Tableau de bord',
diff --git a/app/Controllers/MediaController.php b/app/Controllers/MediaController.php
index abd91d8..4fc8d7d 100644
--- a/app/Controllers/MediaController.php
+++ b/app/Controllers/MediaController.php
@@ -16,7 +16,7 @@ class MediaController extends BaseController
public function index(): void
{
$page = max(1, (int) ($this->f3->get('GET.page') ?? 1));
- $result = (new Media($this->db))->paginateLibrary($page, self::PER_PAGE);
+ $result = (new Media())->paginateLibrary($page, self::PER_PAGE);
$this->render('admin/media.html', [
'pageTitle' => 'Médiathèque',
@@ -50,7 +50,7 @@ class MediaController extends BaseController
}
foreach ($accepted as $destPath) {
- (new Media($this->db))->upload($destPath, $originalName);
+ (new Media())->upload($destPath, $originalName);
}
$this->flash('success', 'Image ajoutée.');
@@ -66,8 +66,9 @@ class MediaController extends BaseController
$this->verifyCsrf();
try {
- $alt = trim((string) ($this->f3->get('POST.alt') ?? ''));
- (new Media($this->db))->updateAlt((int) $this->f3->get('PARAMS.id'), $alt);
+ $alt = (string) ($this->f3->get('POST.alt') ?? '');
+ $this->f3->scrub($alt);
+ (new Media())->updateAlt((int) $this->f3->get('PARAMS.id'), trim($alt));
$this->flash('success', 'Texte alternatif mis à jour.');
} catch (RuntimeException $e) {
$this->flash('error', $e->getMessage());
@@ -82,14 +83,14 @@ class MediaController extends BaseController
try {
$id = (int) $this->f3->get('PARAMS.id');
- $media = new Media($this->db);
+ $media = new Media();
$item = $media->findById($id);
if ($item === null) {
throw new RuntimeException('Image introuvable.');
}
- if ((new Post($this->db))->isMediaUsed($item['id'], $item['file_name'])) {
+ if ((new Post())->isMediaUsed($item['id'], $item['file_name'])) {
throw new RuntimeException('Cette image est encore utilisée par un article.');
}
diff --git a/app/Controllers/PostController.php b/app/Controllers/PostController.php
index 95b4bbd..db9aa42 100644
--- a/app/Controllers/PostController.php
+++ b/app/Controllers/PostController.php
@@ -20,11 +20,11 @@ class PostController extends BaseController
{
$this->verifyCsrf();
- $media = new Media($this->db);
+ $media = new Media();
$input = $this->postInput();
try {
- (new Post($this->db))->create($input, $media);
+ (new Post())->create($input, $media);
$this->flash('success', 'Article créé.');
$this->f3->reroute('@dashboard');
} catch (RuntimeException $e) {
@@ -34,7 +34,7 @@ class PostController extends BaseController
public function edit(): void
{
- $post = (new Post($this->db))->findForEdit((int) $this->f3->get('PARAMS.id'));
+ $post = (new Post())->findForEdit((int) $this->f3->get('PARAMS.id'));
if ($post === null) {
$this->f3->error(404, 'Article introuvable.');
return;
@@ -47,12 +47,12 @@ class PostController extends BaseController
{
$this->verifyCsrf();
- $media = new Media($this->db);
+ $media = new Media();
$id = (int) $this->f3->get('PARAMS.id');
$input = $this->postInput() + ['id' => $id];
try {
- $updated = (new Post($this->db))->updatePost($id, $input, $media);
+ $updated = (new Post())->updatePost($id, $input, $media);
if (!$updated) {
$this->f3->error(404, 'Article introuvable.');
return;
@@ -70,7 +70,7 @@ class PostController extends BaseController
$this->verifyCsrf();
try {
- (new Post($this->db))->delete((int) $this->f3->get('PARAMS.id'));
+ (new Post())->delete((int) $this->f3->get('PARAMS.id'));
$this->flash('success', 'Article supprimé.');
} catch (RuntimeException $e) {
$this->flash('error', $e->getMessage());
@@ -81,7 +81,7 @@ class PostController extends BaseController
private function renderForm(string $pageTitle, string $formAction, array $post, ?string $error = null, ?Media $media = null): void
{
- $media ??= new Media($this->db);
+ $media ??= new Media();
$coverPreview = null;
if (!empty($post['cover_media_id'])) {
@@ -90,7 +90,7 @@ class PostController extends BaseController
$mediaItems = $media->latest(self::MEDIA_PICKER_LIMIT);
$mediaCount = $media->count();
- $flash = $error !== null ? ['type' => 'error', 'message' => $error] : null;
+ $flash = $error !== null ? [['type' => 'error', 'message' => $error]] : [];
$this->render('admin/post_form.html', [
'pageTitle' => $pageTitle,
@@ -109,9 +109,17 @@ class PostController extends BaseController
private function postInput(): array
{
+ $title = (string) ($this->f3->get('POST.title') ?? '');
+ $excerpt = (string) ($this->f3->get('POST.excerpt') ?? '');
+
+ // scrub() supprime les tags HTML/PHP — défense en profondeur
+ // pour les champs rendus en texte brut dans les templates.
+ $this->f3->scrub($title);
+ $this->f3->scrub($excerpt);
+
return [
- 'title' => trim((string) ($this->f3->get('POST.title') ?? '')),
- 'excerpt' => trim((string) ($this->f3->get('POST.excerpt') ?? '')),
+ 'title' => trim($title),
+ 'excerpt' => trim($excerpt),
'cover_media_id' => (string) ($this->f3->get('POST.cover_media_id') ?? ''),
'body_markdown' => trim((string) ($this->f3->get('POST.body_markdown') ?? '')),
];
diff --git a/app/Controllers/SiteController.php b/app/Controllers/SiteController.php
index 96725d7..039c096 100644
--- a/app/Controllers/SiteController.php
+++ b/app/Controllers/SiteController.php
@@ -7,8 +7,8 @@ class SiteController extends BaseController
public function home(): void
{
$page = max(1, (int) ($this->f3->get('GET.page') ?? 1));
- $media = new Media($this->db);
- $result = (new Post($this->db))->paginateList($page, 12, $media);
+ $media = new Media();
+ $result = (new Post())->paginateList($page, 12, $media);
$this->render('site/home.html', [
'pageTitle' => 'Accueil',
@@ -20,8 +20,8 @@ class SiteController extends BaseController
public function show(): void
{
- $media = new Media($this->db);
- $post = (new Post($this->db))->findBySlug((string) $this->f3->get('PARAMS.slug'), $media);
+ $media = new Media();
+ $post = (new Post())->findBySlug((string) $this->f3->get('PARAMS.slug'), $media);
if ($post === null) {
$this->f3->error(404, 'Article introuvable.');
return;
diff --git a/app/Models/Media.php b/app/Models/Media.php
index 07bd2ad..3dcdd2a 100644
--- a/app/Models/Media.php
+++ b/app/Models/Media.php
@@ -8,14 +8,18 @@ class Media extends DB\SQL\Mapper
private const MAX_HEIGHT = 8000;
private const MAX_PIXELS = 40_000_000;
- public function __construct(DB\SQL $db)
+ public function __construct()
{
- parent::__construct($db, 'media');
+ parent::__construct(Base::instance()->get('DB'), 'media');
}
public static function bootstrap(DB\SQL $db): void
{
- $db->exec('CREATE TABLE IF NOT EXISTS media (
+ if ($db->schema('media', null, 0)) {
+ return;
+ }
+
+ $db->exec('CREATE TABLE media (
id INTEGER PRIMARY KEY AUTOINCREMENT,
file_name TEXT NOT NULL UNIQUE,
alt TEXT NOT NULL DEFAULT \'\',
@@ -23,7 +27,7 @@ class Media extends DB\SQL\Mapper
height INTEGER NOT NULL,
created_at TEXT NOT NULL
)');
- $db->exec('CREATE INDEX IF NOT EXISTS idx_media_created_at ON media(created_at DESC)');
+ $db->exec('CREATE INDEX idx_media_created_at ON media(created_at DESC)');
}
public function paginateLibrary(int $page = 1, int $perPage = 24): array
@@ -89,19 +93,30 @@ class Media extends DB\SQL\Mapper
public function upload(string $srcPath, string $originalName = ''): int
{
$target = null;
- $image = null;
$committed = false; // Contrôle le nettoyage de $target dans finally.
try {
$meta = self::inspectUpload($srcPath);
- $image = self::openImageResource($srcPath, $meta['mime']);
- [$format, $extension] = self::targetFormat($meta['mime']);
+ // F3 Image : load() utilise imagecreatefromstring + imagesavealpha.
+ $img = new \Image();
+ if (!$img->load(file_get_contents($srcPath))) {
+ throw new RuntimeException('Fichier image invalide ou format source non supporté.');
+ }
+
+ // PNG/WebP → PNG (préserve la transparence), JPG → JPG.
+ $isJpeg = ($meta['mime'] === 'image/jpeg');
+ $extension = $isJpeg ? 'jpg' : 'png';
+
// Nom aléatoire : empêche le path traversal et la devinabilité des URLs.
$fileName = bin2hex(random_bytes(16)) . '.' . $extension;
$target = app_public_media_dir() . '/' . $fileName;
- self::writeImage($image, $target, $format);
+ // dump() appelle image{format}($data, NULL, $quality).
+ $binary = $isJpeg ? $img->dump('jpeg', 85) : $img->dump('png', 6);
+ if ($binary === '' || file_put_contents($target, $binary) === false) {
+ throw new RuntimeException('Impossible d\'enregistrer cette image.');
+ }
$this->db->begin();
try {
@@ -123,9 +138,7 @@ class Media extends DB\SQL\Mapper
} catch (Throwable $e) {
throw $e instanceof RuntimeException ? $e : new RuntimeException('Impossible d\'enregistrer cette image.');
} finally {
- if ($image instanceof GdImage) {
- imagedestroy($image);
- }
+ // Le destructeur de F3 Image libère la ressource GD.
if (is_file($srcPath)) {
@unlink($srcPath);
}
@@ -202,51 +215,6 @@ class Media extends DB\SQL\Mapper
];
}
- private static function openImageResource(string $srcPath, string $mime): GdImage
- {
- $image = match ($mime) {
- 'image/jpeg' => @imagecreatefromjpeg($srcPath),
- 'image/png' => @imagecreatefrompng($srcPath),
- 'image/webp' => @imagecreatefromwebp($srcPath),
- default => false,
- };
-
- if (!$image instanceof GdImage) {
- throw new RuntimeException('Fichier image invalide ou format source non supporté.');
- }
-
- return $image;
- }
-
- // PNG/WebP → PNG pour préserver la transparence de manière fiable.
- // JPG reste en JPG (pas de canal alpha).
- private static function targetFormat(string $mime): array
- {
- return match ($mime) {
- 'image/jpeg' => ['jpeg', 'jpg'],
- 'image/png', 'image/webp' => ['png', 'png'],
- default => throw new RuntimeException('Format non supporté. Utilise JPG, PNG ou WebP.'),
- };
- }
-
- private static function writeImage(GdImage $image, string $target, string $format): void
- {
- if ($format === 'png') {
- if (!imageistruecolor($image)) {
- imagepalettetotruecolor($image);
- }
- imagealphablending($image, false);
- imagesavealpha($image, true);
- $written = @imagepng($image, $target, 6);
- } else {
- $written = @imagejpeg($image, $target, 85);
- }
-
- if ($written !== true || !is_file($target)) {
- throw new RuntimeException('Impossible d\'enregistrer cette image.');
- }
- }
-
// Dérive un texte alternatif lisible depuis le nom de fichier d'origine.
private static function altFromFilename(string $filename): string
{
diff --git a/app/Models/Post.php b/app/Models/Post.php
index 744003b..80d713d 100644
--- a/app/Models/Post.php
+++ b/app/Models/Post.php
@@ -7,14 +7,18 @@ class Post extends DB\SQL\Mapper
public const TITLE_MAX_LENGTH = 120;
public const EXCERPT_MAX_LENGTH = 240;
- public function __construct(DB\SQL $db)
+ public function __construct()
{
- parent::__construct($db, 'posts');
+ parent::__construct(Base::instance()->get('DB'), 'posts');
}
public static function bootstrap(DB\SQL $db): void
{
- $db->exec('CREATE TABLE IF NOT EXISTS posts (
+ if ($db->schema('posts', null, 0)) {
+ return;
+ }
+
+ $db->exec('CREATE TABLE posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
slug TEXT NOT NULL UNIQUE,
@@ -26,7 +30,7 @@ class Post extends DB\SQL\Mapper
updated_at TEXT NOT NULL,
FOREIGN KEY (cover_media_id) REFERENCES media(id) ON DELETE SET NULL
)');
- $db->exec('CREATE INDEX IF NOT EXISTS idx_posts_created_at ON posts(created_at DESC)');
+ $db->exec('CREATE INDEX idx_posts_created_at ON posts(created_at DESC)');
}
public static function emptyForm(): array
diff --git a/app/Models/User.php b/app/Models/User.php
index 9de0fa4..2afe0f8 100644
--- a/app/Models/User.php
+++ b/app/Models/User.php
@@ -4,14 +4,18 @@ declare(strict_types=1);
class User extends DB\SQL\Mapper
{
- public function __construct(DB\SQL $db)
+ public function __construct()
{
- parent::__construct($db, 'users');
+ parent::__construct(Base::instance()->get('DB'), 'users');
}
public static function bootstrap(DB\SQL $db): void
{
- $db->exec('CREATE TABLE IF NOT EXISTS users (
+ if ($db->schema('users', null, 0)) {
+ return;
+ }
+
+ $db->exec('CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
@@ -43,7 +47,10 @@ class User extends DB\SQL\Mapper
public function create(string $username, string $password): int
{
+ $f3 = Base::instance();
+ $f3->scrub($username);
$username = trim($username);
+
if ($username === '' || $password === '') {
throw new RuntimeException('Nom d’utilisateur et mot de passe obligatoires.');
}
diff --git a/app/Services/MarkdownService.php b/app/Services/MarkdownService.php
index 2cc40e4..5932a05 100644
--- a/app/Services/MarkdownService.php
+++ b/app/Services/MarkdownService.php
@@ -50,10 +50,10 @@ class MarkdownService extends Prefab
$alt = $a[1];
}
if ($alt === '') {
- $alt = htmlspecialchars($item['alt'], ENT_QUOTES, 'UTF-8');
+ $alt = Base::instance()->encode($item['alt']);
}
- $url = htmlspecialchars($item['url'], ENT_QUOTES, 'UTF-8');
+ $url = Base::instance()->encode($item['url']);
return '
';
}, $html) ?? $html;
diff --git a/app/Views/layout.html b/app/Views/layout.html
index 04edf7b..e890d2a 100644
--- a/app/Views/layout.html
+++ b/app/Views/layout.html
@@ -15,7 +15,9 @@
- {{ @flash.message }}
+
+ {{ @msg.message }}
+
diff --git a/scripts/create-admin.php b/scripts/create-admin.php
index fc52a21..052277c 100644
--- a/scripts/create-admin.php
+++ b/scripts/create-admin.php
@@ -3,7 +3,6 @@
declare(strict_types=1);
$f3 = require __DIR__ . '/bootstrap.php';
-$db = $f3->get('DB');
$username = trim((string) ($argv[1] ?? ''));
if ($username === '') {
@@ -26,10 +25,10 @@ if ($password === '') {
exit(1);
}
-User::bootstrap($db);
+User::bootstrap($f3->get('DB'));
try {
- $id = (new User($db))->create($username, $password);
+ $id = (new User())->create($username, $password);
fwrite(STDOUT, "Admin créé (ID {$id}).\n");
} catch (RuntimeException $e) {
fwrite(STDERR, $e->getMessage() . "\n");