Less home code more F3
This commit is contained in:
@@ -21,8 +21,12 @@ class AuthController extends BaseController
|
|||||||
$username = trim((string) ($this->f3->get('POST.username') ?? ''));
|
$username = trim((string) ($this->f3->get('POST.username') ?? ''));
|
||||||
$password = (string) ($this->f3->get('POST.password') ?? '');
|
$password = (string) ($this->f3->get('POST.password') ?? '');
|
||||||
|
|
||||||
$user = (new User($this->db))->findByUsername($username);
|
// User étend DB\SQL\Mapper — inutile de recréer un Mapper générique.
|
||||||
if ($user === null || !password_verify($password, $user['password_hash'])) {
|
// 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
|
usleep(1_500_000); // 1,5 s — ralentit le brute-force
|
||||||
$this->flash('error', 'Identifiants invalides.');
|
$this->flash('error', 'Identifiants invalides.');
|
||||||
$this->f3->reroute('@login');
|
$this->f3->reroute('@login');
|
||||||
@@ -30,7 +34,7 @@ class AuthController extends BaseController
|
|||||||
}
|
}
|
||||||
|
|
||||||
session_regenerate_id(true); // Prévient la fixation de session.
|
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->flash('success', 'Connexion réussie.');
|
||||||
$this->f3->reroute('@dashboard');
|
$this->f3->reroute('@dashboard');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,53 +5,51 @@ declare(strict_types=1);
|
|||||||
abstract class BaseController
|
abstract class BaseController
|
||||||
{
|
{
|
||||||
protected Base $f3;
|
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()
|
public function __construct()
|
||||||
{
|
{
|
||||||
$this->f3 = Base::instance();
|
$this->f3 = Base::instance();
|
||||||
$this->db = $this->f3->get('DB');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function render(string $view, array $data = [], int $cacheTtl = 0): void
|
protected function render(string $view, array $data = [], int $cacheTtl = 0): void
|
||||||
{
|
{
|
||||||
$user = $this->currentUser();
|
|
||||||
|
|
||||||
// Les pages publiques restent cacheables avec le TTL demandé.
|
// Les pages publiques restent cacheables avec le TTL demandé.
|
||||||
// Si un utilisateur est connecté, le layout dépend de la session
|
// Si un utilisateur est connecté, le layout dépend de la session
|
||||||
// (navigation admin, déconnexion + CSRF) : on force expire(0)
|
// (navigation admin, déconnexion + CSRF) : on force expire(0)
|
||||||
// pour ne pas servir ce rendu à d'autres visiteurs.
|
// 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'])
|
$flash = array_key_exists('flash', $data) && is_array($data['flash'])
|
||||||
? $data['flash']
|
? $data['flash']
|
||||||
: $this->pullFlash();
|
: $this->pullFlash();
|
||||||
|
|
||||||
|
// currentUser est déjà dans le hive (posé par currentUser()).
|
||||||
|
// Le template y accède directement via {{ @currentUser }}.
|
||||||
$this->f3->mset($data + [
|
$this->f3->mset($data + [
|
||||||
'view' => $view,
|
'view' => $view,
|
||||||
'currentUser' => $user,
|
|
||||||
'flash' => $flash,
|
'flash' => $flash,
|
||||||
'metaDescription' => null,
|
'metaDescription' => null,
|
||||||
'adminMode' => false,
|
'adminMode' => false,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Recopier @CSRF en session pour que verifyCsrf() puisse
|
// F3 régénère @CSRF à chaque requête (variable hive uniquement).
|
||||||
// vérifier le jeton soumis au POST suivant.
|
// On le persiste en session pour que verifyCsrf() puisse comparer
|
||||||
$this->f3->copy('CSRF', 'SESSION.csrf');
|
// le jeton soumis au POST suivant.
|
||||||
|
$this->f3->copy('CSRF', 'SESSION.csrf_token');
|
||||||
echo Template::instance()->render('layout.html');
|
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
|
protected function currentUser(): ?array
|
||||||
{
|
{
|
||||||
if ($this->resolvedUser === false) {
|
if (!$this->f3->exists('currentUser', $user)) {
|
||||||
$userId = (int) ($this->f3->get('SESSION.user_id') ?? 0);
|
$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
|
protected function requireAuth(): void
|
||||||
@@ -64,12 +62,13 @@ abstract class BaseController
|
|||||||
$this->f3->reroute('@login');
|
$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
|
protected function verifyCsrf(): void
|
||||||
{
|
{
|
||||||
$submitted = (string) ($this->f3->get('POST.csrf_token') ?? '');
|
$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)) {
|
if ($submitted !== '' && $expected !== '' && hash_equals($expected, $submitted)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -77,15 +76,14 @@ abstract class BaseController
|
|||||||
$this->f3->error(400, 'Jeton CSRF invalide.');
|
$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
|
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');
|
return $this->f3->pull('SESSION.flash') ?: [];
|
||||||
$this->f3->clear('SESSION.flash');
|
|
||||||
return is_array($flash) ? $flash : null;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ class DashboardController extends BaseController
|
|||||||
public function index(): void
|
public function index(): void
|
||||||
{
|
{
|
||||||
$page = max(1, (int) ($this->f3->get('GET.page') ?? 1));
|
$page = max(1, (int) ($this->f3->get('GET.page') ?? 1));
|
||||||
$media = new Media($this->db);
|
$media = new Media();
|
||||||
$result = (new Post($this->db))->paginateList($page, 24, $media);
|
$result = (new Post())->paginateList($page, 24, $media);
|
||||||
|
|
||||||
$this->render('admin/dashboard.html', [
|
$this->render('admin/dashboard.html', [
|
||||||
'pageTitle' => 'Tableau de bord',
|
'pageTitle' => 'Tableau de bord',
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ class MediaController extends BaseController
|
|||||||
public function index(): void
|
public function index(): void
|
||||||
{
|
{
|
||||||
$page = max(1, (int) ($this->f3->get('GET.page') ?? 1));
|
$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', [
|
$this->render('admin/media.html', [
|
||||||
'pageTitle' => 'Médiathèque',
|
'pageTitle' => 'Médiathèque',
|
||||||
@@ -50,7 +50,7 @@ class MediaController extends BaseController
|
|||||||
}
|
}
|
||||||
|
|
||||||
foreach ($accepted as $destPath) {
|
foreach ($accepted as $destPath) {
|
||||||
(new Media($this->db))->upload($destPath, $originalName);
|
(new Media())->upload($destPath, $originalName);
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->flash('success', 'Image ajoutée.');
|
$this->flash('success', 'Image ajoutée.');
|
||||||
@@ -66,8 +66,9 @@ class MediaController extends BaseController
|
|||||||
$this->verifyCsrf();
|
$this->verifyCsrf();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$alt = trim((string) ($this->f3->get('POST.alt') ?? ''));
|
$alt = (string) ($this->f3->get('POST.alt') ?? '');
|
||||||
(new Media($this->db))->updateAlt((int) $this->f3->get('PARAMS.id'), $alt);
|
$this->f3->scrub($alt);
|
||||||
|
(new Media())->updateAlt((int) $this->f3->get('PARAMS.id'), trim($alt));
|
||||||
$this->flash('success', 'Texte alternatif mis à jour.');
|
$this->flash('success', 'Texte alternatif mis à jour.');
|
||||||
} catch (RuntimeException $e) {
|
} catch (RuntimeException $e) {
|
||||||
$this->flash('error', $e->getMessage());
|
$this->flash('error', $e->getMessage());
|
||||||
@@ -82,14 +83,14 @@ class MediaController extends BaseController
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
$id = (int) $this->f3->get('PARAMS.id');
|
$id = (int) $this->f3->get('PARAMS.id');
|
||||||
$media = new Media($this->db);
|
$media = new Media();
|
||||||
$item = $media->findById($id);
|
$item = $media->findById($id);
|
||||||
|
|
||||||
if ($item === null) {
|
if ($item === null) {
|
||||||
throw new RuntimeException('Image introuvable.');
|
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.');
|
throw new RuntimeException('Cette image est encore utilisée par un article.');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,11 +20,11 @@ class PostController extends BaseController
|
|||||||
{
|
{
|
||||||
$this->verifyCsrf();
|
$this->verifyCsrf();
|
||||||
|
|
||||||
$media = new Media($this->db);
|
$media = new Media();
|
||||||
$input = $this->postInput();
|
$input = $this->postInput();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
(new Post($this->db))->create($input, $media);
|
(new Post())->create($input, $media);
|
||||||
$this->flash('success', 'Article créé.');
|
$this->flash('success', 'Article créé.');
|
||||||
$this->f3->reroute('@dashboard');
|
$this->f3->reroute('@dashboard');
|
||||||
} catch (RuntimeException $e) {
|
} catch (RuntimeException $e) {
|
||||||
@@ -34,7 +34,7 @@ class PostController extends BaseController
|
|||||||
|
|
||||||
public function edit(): void
|
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) {
|
if ($post === null) {
|
||||||
$this->f3->error(404, 'Article introuvable.');
|
$this->f3->error(404, 'Article introuvable.');
|
||||||
return;
|
return;
|
||||||
@@ -47,12 +47,12 @@ class PostController extends BaseController
|
|||||||
{
|
{
|
||||||
$this->verifyCsrf();
|
$this->verifyCsrf();
|
||||||
|
|
||||||
$media = new Media($this->db);
|
$media = new Media();
|
||||||
$id = (int) $this->f3->get('PARAMS.id');
|
$id = (int) $this->f3->get('PARAMS.id');
|
||||||
$input = $this->postInput() + ['id' => $id];
|
$input = $this->postInput() + ['id' => $id];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$updated = (new Post($this->db))->updatePost($id, $input, $media);
|
$updated = (new Post())->updatePost($id, $input, $media);
|
||||||
if (!$updated) {
|
if (!$updated) {
|
||||||
$this->f3->error(404, 'Article introuvable.');
|
$this->f3->error(404, 'Article introuvable.');
|
||||||
return;
|
return;
|
||||||
@@ -70,7 +70,7 @@ class PostController extends BaseController
|
|||||||
$this->verifyCsrf();
|
$this->verifyCsrf();
|
||||||
|
|
||||||
try {
|
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é.');
|
$this->flash('success', 'Article supprimé.');
|
||||||
} catch (RuntimeException $e) {
|
} catch (RuntimeException $e) {
|
||||||
$this->flash('error', $e->getMessage());
|
$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
|
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;
|
$coverPreview = null;
|
||||||
if (!empty($post['cover_media_id'])) {
|
if (!empty($post['cover_media_id'])) {
|
||||||
@@ -90,7 +90,7 @@ class PostController extends BaseController
|
|||||||
|
|
||||||
$mediaItems = $media->latest(self::MEDIA_PICKER_LIMIT);
|
$mediaItems = $media->latest(self::MEDIA_PICKER_LIMIT);
|
||||||
$mediaCount = $media->count();
|
$mediaCount = $media->count();
|
||||||
$flash = $error !== null ? ['type' => 'error', 'message' => $error] : null;
|
$flash = $error !== null ? [['type' => 'error', 'message' => $error]] : [];
|
||||||
|
|
||||||
$this->render('admin/post_form.html', [
|
$this->render('admin/post_form.html', [
|
||||||
'pageTitle' => $pageTitle,
|
'pageTitle' => $pageTitle,
|
||||||
@@ -109,9 +109,17 @@ class PostController extends BaseController
|
|||||||
|
|
||||||
private function postInput(): array
|
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 [
|
return [
|
||||||
'title' => trim((string) ($this->f3->get('POST.title') ?? '')),
|
'title' => trim($title),
|
||||||
'excerpt' => trim((string) ($this->f3->get('POST.excerpt') ?? '')),
|
'excerpt' => trim($excerpt),
|
||||||
'cover_media_id' => (string) ($this->f3->get('POST.cover_media_id') ?? ''),
|
'cover_media_id' => (string) ($this->f3->get('POST.cover_media_id') ?? ''),
|
||||||
'body_markdown' => trim((string) ($this->f3->get('POST.body_markdown') ?? '')),
|
'body_markdown' => trim((string) ($this->f3->get('POST.body_markdown') ?? '')),
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -7,8 +7,8 @@ class SiteController extends BaseController
|
|||||||
public function home(): void
|
public function home(): void
|
||||||
{
|
{
|
||||||
$page = max(1, (int) ($this->f3->get('GET.page') ?? 1));
|
$page = max(1, (int) ($this->f3->get('GET.page') ?? 1));
|
||||||
$media = new Media($this->db);
|
$media = new Media();
|
||||||
$result = (new Post($this->db))->paginateList($page, 12, $media);
|
$result = (new Post())->paginateList($page, 12, $media);
|
||||||
|
|
||||||
$this->render('site/home.html', [
|
$this->render('site/home.html', [
|
||||||
'pageTitle' => 'Accueil',
|
'pageTitle' => 'Accueil',
|
||||||
@@ -20,8 +20,8 @@ class SiteController extends BaseController
|
|||||||
|
|
||||||
public function show(): void
|
public function show(): void
|
||||||
{
|
{
|
||||||
$media = new Media($this->db);
|
$media = new Media();
|
||||||
$post = (new Post($this->db))->findBySlug((string) $this->f3->get('PARAMS.slug'), $media);
|
$post = (new Post())->findBySlug((string) $this->f3->get('PARAMS.slug'), $media);
|
||||||
if ($post === null) {
|
if ($post === null) {
|
||||||
$this->f3->error(404, 'Article introuvable.');
|
$this->f3->error(404, 'Article introuvable.');
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -8,14 +8,18 @@ class Media extends DB\SQL\Mapper
|
|||||||
private const MAX_HEIGHT = 8000;
|
private const MAX_HEIGHT = 8000;
|
||||||
private const MAX_PIXELS = 40_000_000;
|
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
|
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,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
file_name TEXT NOT NULL UNIQUE,
|
file_name TEXT NOT NULL UNIQUE,
|
||||||
alt TEXT NOT NULL DEFAULT \'\',
|
alt TEXT NOT NULL DEFAULT \'\',
|
||||||
@@ -23,7 +27,7 @@ class Media extends DB\SQL\Mapper
|
|||||||
height INTEGER NOT NULL,
|
height INTEGER NOT NULL,
|
||||||
created_at TEXT 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
|
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
|
public function upload(string $srcPath, string $originalName = ''): int
|
||||||
{
|
{
|
||||||
$target = null;
|
$target = null;
|
||||||
$image = null;
|
|
||||||
$committed = false; // Contrôle le nettoyage de $target dans finally.
|
$committed = false; // Contrôle le nettoyage de $target dans finally.
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$meta = self::inspectUpload($srcPath);
|
$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.
|
// Nom aléatoire : empêche le path traversal et la devinabilité des URLs.
|
||||||
$fileName = bin2hex(random_bytes(16)) . '.' . $extension;
|
$fileName = bin2hex(random_bytes(16)) . '.' . $extension;
|
||||||
$target = app_public_media_dir() . '/' . $fileName;
|
$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();
|
$this->db->begin();
|
||||||
try {
|
try {
|
||||||
@@ -123,9 +138,7 @@ class Media extends DB\SQL\Mapper
|
|||||||
} catch (Throwable $e) {
|
} catch (Throwable $e) {
|
||||||
throw $e instanceof RuntimeException ? $e : new RuntimeException('Impossible d\'enregistrer cette image.');
|
throw $e instanceof RuntimeException ? $e : new RuntimeException('Impossible d\'enregistrer cette image.');
|
||||||
} finally {
|
} finally {
|
||||||
if ($image instanceof GdImage) {
|
// Le destructeur de F3 Image libère la ressource GD.
|
||||||
imagedestroy($image);
|
|
||||||
}
|
|
||||||
if (is_file($srcPath)) {
|
if (is_file($srcPath)) {
|
||||||
@unlink($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.
|
// Dérive un texte alternatif lisible depuis le nom de fichier d'origine.
|
||||||
private static function altFromFilename(string $filename): string
|
private static function altFromFilename(string $filename): string
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -7,14 +7,18 @@ class Post extends DB\SQL\Mapper
|
|||||||
public const TITLE_MAX_LENGTH = 120;
|
public const TITLE_MAX_LENGTH = 120;
|
||||||
public const EXCERPT_MAX_LENGTH = 240;
|
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
|
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,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
title TEXT NOT NULL,
|
title TEXT NOT NULL,
|
||||||
slug TEXT NOT NULL UNIQUE,
|
slug TEXT NOT NULL UNIQUE,
|
||||||
@@ -26,7 +30,7 @@ class Post extends DB\SQL\Mapper
|
|||||||
updated_at TEXT NOT NULL,
|
updated_at TEXT NOT NULL,
|
||||||
FOREIGN KEY (cover_media_id) REFERENCES media(id) ON DELETE SET 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
|
public static function emptyForm(): array
|
||||||
|
|||||||
@@ -4,14 +4,18 @@ declare(strict_types=1);
|
|||||||
|
|
||||||
class User extends DB\SQL\Mapper
|
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
|
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,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
username TEXT NOT NULL UNIQUE,
|
username TEXT NOT NULL UNIQUE,
|
||||||
password_hash TEXT NOT NULL,
|
password_hash TEXT NOT NULL,
|
||||||
@@ -43,7 +47,10 @@ class User extends DB\SQL\Mapper
|
|||||||
|
|
||||||
public function create(string $username, string $password): int
|
public function create(string $username, string $password): int
|
||||||
{
|
{
|
||||||
|
$f3 = Base::instance();
|
||||||
|
$f3->scrub($username);
|
||||||
$username = trim($username);
|
$username = trim($username);
|
||||||
|
|
||||||
if ($username === '' || $password === '') {
|
if ($username === '' || $password === '') {
|
||||||
throw new RuntimeException('Nom d’utilisateur et mot de passe obligatoires.');
|
throw new RuntimeException('Nom d’utilisateur et mot de passe obligatoires.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,10 +50,10 @@ class MarkdownService extends Prefab
|
|||||||
$alt = $a[1];
|
$alt = $a[1];
|
||||||
}
|
}
|
||||||
if ($alt === '') {
|
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 '<img src="' . $url . '" alt="' . $alt . '" loading="lazy" decoding="async">';
|
return '<img src="' . $url . '" alt="' . $alt . '" loading="lazy" decoding="async">';
|
||||||
}, $html) ?? $html;
|
}, $html) ?? $html;
|
||||||
|
|||||||
@@ -15,7 +15,9 @@
|
|||||||
<main class="page" id="main-content">
|
<main class="page" id="main-content">
|
||||||
<div class="container">
|
<div class="container">
|
||||||
<check if="{{ @flash }}">
|
<check if="{{ @flash }}">
|
||||||
<div class="flash flash--{{ @flash.type }}" role="status">{{ @flash.message }}</div>
|
<repeat group="{{ @flash }}" value="{{ @msg }}">
|
||||||
|
<div class="flash flash--{{ @msg.type }}" role="status">{{ @msg.message }}</div>
|
||||||
|
</repeat>
|
||||||
</check>
|
</check>
|
||||||
<include href="{{ @view }}" />
|
<include href="{{ @view }}" />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
$f3 = require __DIR__ . '/bootstrap.php';
|
$f3 = require __DIR__ . '/bootstrap.php';
|
||||||
$db = $f3->get('DB');
|
|
||||||
|
|
||||||
$username = trim((string) ($argv[1] ?? ''));
|
$username = trim((string) ($argv[1] ?? ''));
|
||||||
if ($username === '') {
|
if ($username === '') {
|
||||||
@@ -26,10 +25,10 @@ if ($password === '') {
|
|||||||
exit(1);
|
exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
User::bootstrap($db);
|
User::bootstrap($f3->get('DB'));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$id = (new User($db))->create($username, $password);
|
$id = (new User())->create($username, $password);
|
||||||
fwrite(STDOUT, "Admin créé (ID {$id}).\n");
|
fwrite(STDOUT, "Admin créé (ID {$id}).\n");
|
||||||
} catch (RuntimeException $e) {
|
} catch (RuntimeException $e) {
|
||||||
fwrite(STDERR, $e->getMessage() . "\n");
|
fwrite(STDERR, $e->getMessage() . "\n");
|
||||||
|
|||||||
Reference in New Issue
Block a user