Compare commits

...

9 Commits

15 changed files with 1117 additions and 191 deletions

@ -3,7 +3,8 @@ require_once '../../includes/config.php';
require_once '../../includes/auth.php';
require_once '../../includes/stories.php';
// Vérification de l'authentification
header('Content-Type: application/json');
if (!Auth::check()) {
http_response_code(401);
exit(json_encode(['error' => 'Non autorisé']));
@ -35,9 +36,39 @@ try {
throw new Exception('Chapitre non trouvé');
}
header('Content-Type: application/json');
// Vérification et correction de la structure du chapitre
if (!isset($chapter['title'])) {
$chapter['title'] = '';
}
// Conversion du contenu HTML en format Delta de Quill si nécessaire
if (!isset($chapter['content'])) {
$chapter['content'] = '{"ops":[{"insert":"\n"}]}';
} else {
// Si le contenu est une chaîne HTML
if (is_string($chapter['content']) && !isJson($chapter['content'])) {
// On envoie le HTML brut, Quill le convertira côté client
$chapter['html'] = $chapter['content'];
$chapter['content'] = null;
}
}
echo json_encode($chapter);
} catch (Exception $e) {
error_log('Erreur dans get-chapter.php: ' . $e->getMessage());
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
echo json_encode([
'error' => $e->getMessage(),
'details' => [
'storyId' => $storyId,
'chapterId' => $chapterId,
'file' => __FILE__,
'line' => __LINE__
]
]);
}
function isJson($string) {
json_decode($string);
return json_last_error() === JSON_ERROR_NONE;
}

207
admin/api/upload-image.php Normal file

@ -0,0 +1,207 @@
<?php
require_once '../../includes/config.php';
require_once '../../includes/auth.php';
class ImageUploadHandler {
private $uploadDir;
private $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
private $maxFileSize = 5242880; // 5MB
private $maxWidth = 1200;
private $maxHeight = 1200;
public function __construct($storyId) {
// Création du dossier d'upload spécifique au roman
$this->uploadDir = __DIR__ . '/../../assets/images/chapters/' . $storyId . '/';
$this->ensureUploadDirectory();
}
public function handleUpload($file) {
try {
// Vérifications de base
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new Exception($this->getUploadErrorMessage($file['error']));
}
// Vérification du type MIME
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($file['tmp_name']);
if (!in_array($mimeType, $this->allowedTypes)) {
throw new Exception('Type de fichier non autorisé. Types acceptés : JPG, PNG, GIF, WEBP');
}
// Vérification de la taille
if ($file['size'] > $this->maxFileSize) {
throw new Exception('Fichier trop volumineux. Taille maximum : 5MB');
}
// Vérification et redimensionnement de l'image
[$width, $height, $type] = getimagesize($file['tmp_name']);
$needsResize = $width > $this->maxWidth || $height > $this->maxHeight;
// Génération d'un nom de fichier unique
$extension = $this->getExtensionFromMimeType($mimeType);
$filename = uniqid() . '.' . $extension;
$targetPath = $this->uploadDir . $filename;
if ($needsResize) {
// Calcul des nouvelles dimensions en conservant le ratio
$ratio = min($this->maxWidth / $width, $this->maxHeight / $height);
$newWidth = round($width * $ratio);
$newHeight = round($height * $ratio);
// Création de la nouvelle image
$sourceImage = $this->createImageFromFile($file['tmp_name'], $mimeType);
$newImage = imagecreatetruecolor($newWidth, $newHeight);
// Préservation de la transparence pour PNG
if ($mimeType === 'image/png') {
imagealphablending($newImage, false);
imagesavealpha($newImage, true);
}
// Redimensionnement
imagecopyresampled(
$newImage, $sourceImage,
0, 0, 0, 0,
$newWidth, $newHeight,
$width, $height
);
// Sauvegarde de l'image redimensionnée
$this->saveImage($newImage, $targetPath, $mimeType);
// Libération de la mémoire
imagedestroy($sourceImage);
imagedestroy($newImage);
} else {
// Déplacement du fichier original si pas besoin de redimensionnement
if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
throw new Exception('Erreur lors du déplacement du fichier uploadé');
}
}
// Retourner le chemin relatif pour l'éditeur
return [
'success' => true,
'url' => $this->getRelativePath($targetPath),
'width' => $needsResize ? $newWidth : $width,
'height' => $needsResize ? $newHeight : $height
];
} catch (Exception $e) {
return [
'success' => false,
'error' => $e->getMessage()
];
}
}
private function ensureUploadDirectory() {
if (!file_exists($this->uploadDir)) {
if (!mkdir($this->uploadDir, 0755, true)) {
throw new Exception('Impossible de créer le dossier d\'upload');
}
}
if (!is_writable($this->uploadDir)) {
throw new Exception('Le dossier d\'upload n\'est pas accessible en écriture');
}
}
private function createImageFromFile($file, $mimeType) {
switch ($mimeType) {
case 'image/jpeg':
return imagecreatefromjpeg($file);
case 'image/png':
return imagecreatefrompng($file);
case 'image/gif':
return imagecreatefromgif($file);
case 'image/webp':
return imagecreatefromwebp($file);
default:
throw new Exception('Type d\'image non supporté');
}
}
private function saveImage($image, $path, $mimeType) {
switch ($mimeType) {
case 'image/jpeg':
return imagejpeg($image, $path, 85); // Qualité 85%
case 'image/png':
return imagepng($image, $path, 8); // Compression 8
case 'image/gif':
return imagegif($image, $path);
case 'image/webp':
return imagewebp($image, $path, 85); // Qualité 85%
default:
throw new Exception('Type d\'image non supporté pour la sauvegarde');
}
}
private function getExtensionFromMimeType($mimeType) {
$map = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/webp' => 'webp'
];
return $map[$mimeType] ?? 'jpg';
}
private function getRelativePath($absolutePath) {
$relativePath = str_replace(__DIR__ . '/../../', '', $absolutePath);
// Ajout de '../' car on est dans admin/api/
return '../' . str_replace('\\', '/', $relativePath); // Pour la compatibilité Windows
}
private function getUploadErrorMessage($error) {
$errors = [
UPLOAD_ERR_INI_SIZE => 'Le fichier dépasse la taille maximale autorisée par PHP',
UPLOAD_ERR_FORM_SIZE => 'Le fichier dépasse la taille maximale autorisée par le formulaire',
UPLOAD_ERR_PARTIAL => 'Le fichier n\'a été que partiellement uploadé',
UPLOAD_ERR_NO_FILE => 'Aucun fichier n\'a été uploadé',
UPLOAD_ERR_NO_TMP_DIR => 'Dossier temporaire manquant',
UPLOAD_ERR_CANT_WRITE => 'Échec de l\'écriture du fichier sur le disque',
UPLOAD_ERR_EXTENSION => 'Une extension PHP a arrêté l\'upload'
];
return $errors[$error] ?? 'Erreur inconnue lors de l\'upload';
}
}
// Point d'entrée du script
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
exit(json_encode(['error' => 'Méthode non autorisée']));
}
// Vérification de l'authentification
if (!Auth::check()) {
http_response_code(401);
exit(json_encode(['error' => 'Non autorisé']));
}
// Récupération de l'ID du roman
$storyId = $_POST['storyId'] ?? null;
if (!$storyId) {
http_response_code(400);
exit(json_encode(['error' => 'ID du roman manquant']));
}
// Traitement de l'upload
try {
$handler = new ImageUploadHandler($storyId);
$result = $handler->handleUpload($_FILES['image']);
if (!$result['success']) {
http_response_code(400);
}
header('Content-Type: application/json');
echo json_encode($result);
} catch (Exception $e) {
http_response_code(500);
echo json_encode([
'success' => false,
'error' => 'Erreur serveur : ' . $e->getMessage()
]);
}

@ -21,10 +21,19 @@ $stories = Stories::getAll();
</head>
<body>
<nav class="admin-nav">
<div class="nav-brand">Administration</div>
<div class="nav-brand">
<?php
$config = Config::load();
if (!empty($config['site']['logo'])): ?>
<img src="<?= htmlspecialchars('../' . $config['site']['logo']) ?>"
alt="<?= htmlspecialchars($config['site']['name']) ?>">
<?php endif; ?>
<span>Administration</span>
</div>
<div class="nav-menu">
<a href="profile.php" class="button">Profil</a>
<a href="story-edit.php" class="button">Nouveau roman</a>
<a href="options.php" class="button">Options</a>
<form method="POST" action="logout.php" class="logout-form">
<button type="submit">Déconnexion</button>
</form>

156
admin/options.php Normal file

@ -0,0 +1,156 @@
<?php
require_once '../includes/config.php';
require_once '../includes/auth.php';
require_once '../includes/site-upload.php';
// Vérification de l'authentification
if (!Auth::check()) {
header('Location: login.php');
exit;
}
$success = '';
$error = '';
// Traitement du formulaire
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
try {
$config = Config::load();
// Mise à jour des valeurs textuelles
$config['site']['name'] = trim($_POST['site_name'] ?? '');
$config['site']['description'] = trim($_POST['site_description'] ?? '');
// Validation
if (empty($config['site']['name'])) {
throw new Exception('Le nom du site est requis');
}
// Gestion de l'upload du logo
if (isset($_FILES['site_logo']) && $_FILES['site_logo']['error'] !== UPLOAD_ERR_NO_FILE) {
$uploadHandler = new SiteUploadHandler();
$config['site']['logo'] = $uploadHandler->handleLogoUpload($_FILES['site_logo']);
}
// Sauvegarde
Config::save($config);
$success = 'Configuration mise à jour avec succès';
} catch (Exception $e) {
$error = $e->getMessage();
}
}
// Chargement de la configuration actuelle
$config = Config::load();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Options du site - Administration</title>
<link rel="stylesheet" href="../assets/css/main.css">
</head>
<body>
<nav class="admin-nav">
<div class="nav-brand">
<?php
$config = Config::load();
if (!empty($config['site']['logo'])): ?>
<img src="<?= htmlspecialchars('../' . $config['site']['logo']) ?>"
alt="<?= htmlspecialchars($config['site']['name']) ?>">
<?php endif; ?>
<span>Administration</span>
</div>
<div class="nav-menu">
<a href="index.php" class="button">Retour</a>
</div>
</nav>
<main class="admin-main">
<h1>Options du site</h1>
<?php if ($success): ?>
<div class="success-message"><?= htmlspecialchars($success) ?></div>
<?php endif; ?>
<?php if ($error): ?>
<div class="error-message"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<form method="POST" class="options-form" enctype="multipart/form-data">
<div class="form-group">
<label for="site_name">Nom du site</label>
<input type="text"
id="site_name"
name="site_name"
value="<?= htmlspecialchars($config['site']['name']) ?>"
required>
</div>
<div class="form-group">
<label for="site_description">Description du site</label>
<textarea id="site_description"
name="site_description"
rows="4"><?= htmlspecialchars($config['site']['description']) ?></textarea>
</div>
<div class="form-group">
<label for="site_logo">Logo du site</label>
<?php if (!empty($config['site']['logo'])): ?>
<div class="current-logo">
<img src="<?= htmlspecialchars('../' . $config['site']['logo']) ?>"
alt="Logo actuel"
style="max-height: 100px; margin: 10px 0;">
</div>
<?php endif; ?>
<input type="file"
id="site_logo"
name="site_logo"
accept="image/jpeg,image/png,image/gif,image/svg+xml">
<small>Formats acceptés : JPG, PNG, GIF, SVG. Taille maximum : 2MB</small>
</div>
<button type="submit" class="button">Enregistrer les modifications</button>
</form>
</main>
<script>
// Prévisualisation du logo
document.getElementById('site_logo').addEventListener('change', function(e) {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
let currentLogo = document.querySelector('.current-logo');
if (!currentLogo) {
currentLogo = document.createElement('div');
currentLogo.className = 'current-logo';
e.target.parentElement.insertBefore(currentLogo, e.target.nextSibling);
}
currentLogo.innerHTML = `
<img src="${e.target.result}"
alt="Aperçu du logo"
style="max-height: 100px; margin: 10px 0;">
`;
};
reader.readAsDataURL(file);
}
});
// Détection des changements non sauvegardés
document.addEventListener('DOMContentLoaded', function() {
const form = document.querySelector('form');
const initialState = new FormData(form).toString();
window.addEventListener('beforeunload', (e) => {
if (new FormData(form).toString() !== initialState) {
e.preventDefault();
e.returnValue = '';
}
});
});
</script>
</body>
</html>

@ -83,7 +83,15 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
</head>
<body>
<nav class="admin-nav">
<div class="nav-brand">Administration</div>
<div class="nav-brand">
<?php
$config = Config::load();
if (!empty($config['site']['logo'])): ?>
<img src="<?= htmlspecialchars('../' . $config['site']['logo']) ?>"
alt="<?= htmlspecialchars($config['site']['name']) ?>">
<?php endif; ?>
<span>Administration</span>
</div>
<div class="nav-menu">
<a href="index.php" class="button">Retour</a>
</div>

@ -67,7 +67,15 @@ function generateSlug($title) {
</head>
<body>
<nav class="admin-nav">
<div class="nav-brand">Administration</div>
<div class="nav-brand">
<?php
$config = Config::load();
if (!empty($config['site']['logo'])): ?>
<img src="<?= htmlspecialchars('../' . $config['site']['logo']) ?>"
alt="<?= htmlspecialchars($config['site']['name']) ?>">
<?php endif; ?>
<span>Administration</span>
</div>
<div class="nav-menu">
<a href="index.php" class="button">Retour</a>
</div>

@ -72,7 +72,7 @@
align-items: center;
gap: var(--spacing-lg);
transition: transform var(--transition-fast), box-shadow var(--transition-fast);
cursor: grab;
cursor: default;
}
.chapter-item:hover {
@ -95,6 +95,11 @@
justify-content: center;
border-radius: var(--radius-sm);
font-weight: bold;
cursor: grab;
}
.chapter-number:active {
cursor: grabbing;
}
.chapter-title {

@ -1,55 +1,329 @@
/* Personnalisation de l'éditeur Quill */
.ql-toolbar {
background: var(--bg-secondary) !important;
border-color: var(--border-color) !important;
/* Base de l'éditeur */
.ql-toolbar.ql-snow {
background: var(--bg-secondary);
border-color: var(--border-color);
border-radius: var(--radius-sm) var(--radius-sm) 0 0;
padding: var(--spacing-sm);
display: flex;
flex-wrap: wrap;
gap: 5px;
}
.ql-container {
background: var(--input-bg) !important;
border-color: var(--border-color) !important;
color: var(--text-primary) !important;
.ql-container.ql-snow {
background: var(--input-bg);
border-color: var(--border-color);
border-radius: 0 0 var(--radius-sm) var(--radius-sm);
color: var(--text-primary);
min-height: 300px;
font-family: inherit;
}
/* Contenu de l'éditeur */
.ql-editor {
color: var(--text-primary) !important;
color: var(--text-primary);
padding: var(--spacing-md);
font-size: 1rem;
line-height: 1.6;
}
/* Boutons de la barre d'outils */
.ql-editor.ql-blank::before {
color: var(--text-secondary);
font-style: italic;
left: var(--spacing-md);
}
/* Styles des éléments dans l'éditeur */
.ql-editor h1,
.ql-editor h2,
.ql-editor h3 {
color: var(--text-primary);
margin: 1em 0 0.5em;
}
.ql-editor blockquote {
border-left: 4px solid var(--accent-primary);
margin: 1.5em 0;
padding-left: 1em;
color: var(--text-secondary);
}
.ql-editor pre.ql-syntax {
background: var(--bg-secondary);
color: var(--text-primary);
border-radius: var(--radius-sm);
padding: var(--spacing-md);
}
/* Gestion des images dans l'éditeur */
.ql-editor img {
max-width: 100% !important;
height: auto;
display: block;
margin: var(--spacing-md) 0;
}
.ql-editor img.ql-selected {
border: 2px solid var(--accent-primary);
}
.ql-editor .image-container {
margin: var(--spacing-md) 0;
max-width: 100%;
}
.ql-editor .ql-size-small img {
max-width: 50%;
margin: 0 auto;
}
.ql-editor .ql-size-large img {
max-width: 100%;
}
.ql-editor .ql-align-center img {
margin-left: auto;
margin-right: auto;
}
.ql-editor .ql-align-right img {
margin-left: auto;
margin-right: 0;
}
/* Icônes de la barre d'outils */
.ql-snow .ql-stroke {
stroke: var(--text-secondary) !important;
stroke: var(--text-primary) !important;
stroke-width: 1.2 !important;
}
.ql-snow .ql-fill {
fill: var(--text-secondary) !important;
.ql-snow .ql-fill,
.ql-snow .ql-stroke.ql-fill {
fill: var(--text-primary) !important;
}
.ql-snow .ql-picker {
color: var(--text-secondary) !important;
color: var(--text-primary) !important;
}
/* Menu déroulant */
.ql-snow.ql-toolbar button {
padding: 4px 6px;
height: 28px;
width: 28px;
opacity: 0.9;
}
.ql-snow.ql-toolbar button svg {
width: 20px;
height: 20px;
}
/* États au survol et actif */
.ql-snow .ql-toolbar button:hover,
.ql-snow .ql-toolbar button:focus,
.ql-snow .ql-toolbar button.ql-active,
.ql-snow .ql-toolbar .ql-picker-label:hover,
.ql-snow .ql-toolbar .ql-picker-label.ql-active {
color: var(--accent-primary) !important;
opacity: 1;
}
.ql-snow .ql-toolbar button:hover .ql-stroke,
.ql-snow .ql-toolbar button:focus .ql-stroke,
.ql-snow .ql-toolbar button.ql-active .ql-stroke,
.ql-snow .ql-toolbar .ql-picker-label:hover .ql-stroke,
.ql-snow .ql-toolbar .ql-picker-label.ql-active .ql-stroke {
stroke: var(--accent-primary) !important;
}
.ql-snow .ql-toolbar button:hover .ql-fill,
.ql-snow .ql-toolbar button:focus .ql-fill,
.ql-snow .ql-toolbar button.ql-active .ql-fill,
.ql-snow .ql-toolbar .ql-picker-label:hover .ql-fill,
.ql-snow .ql-toolbar .ql-picker-label.ql-active .ql-fill {
fill: var(--accent-primary) !important;
}
/* Menus déroulants */
.ql-snow .ql-picker-options {
background-color: var(--bg-secondary) !important;
border-color: var(--border-color) !important;
border-radius: var(--radius-sm);
padding: var(--spacing-sm);
}
/* États au survol */
.ql-snow .ql-toolbar button:hover,
.ql-snow .ql-toolbar button.ql-active {
.ql-stroke {
stroke: var(--accent-primary) !important;
}
.ql-fill {
fill: var(--accent-primary) !important;
}
.ql-snow .ql-picker-options .ql-picker-item {
color: var(--text-primary) !important;
padding: 4px 8px;
border-radius: var(--radius-sm);
}
.ql-snow .ql-picker-options .ql-picker-item:hover,
.ql-snow .ql-picker-options .ql-picker-item.ql-selected {
color: var(--accent-primary) !important;
background-color: var(--bg-tertiary) !important;
}
/* Tooltip pour les liens */
.ql-snow .ql-tooltip {
background-color: var(--bg-secondary);
border: 1px solid var(--border-color);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
color: var(--text-primary);
border-radius: var(--radius-sm);
padding: var(--spacing-sm);
z-index: 1000;
}
.ql-snow .ql-tooltip input[type=text] {
background-color: var(--input-bg);
border: 1px solid var(--border-color);
color: var(--text-primary);
padding: 4px 8px;
border-radius: var(--radius-sm);
width: 170px;
margin: 0;
}
.ql-snow .ql-tooltip input[type=text]:focus {
border-color: var(--accent-primary);
outline: none;
}
.ql-snow .ql-tooltip a.ql-action,
.ql-snow .ql-tooltip a.ql-remove {
color: var(--accent-primary);
padding: 4px 8px;
margin: 0 4px;
cursor: pointer;
border-radius: var(--radius-sm);
display: inline-block;
text-decoration: none;
}
.ql-snow .ql-tooltip a.ql-action:hover,
.ql-snow .ql-tooltip a.ql-remove:hover {
color: var(--accent-secondary);
background-color: var(--bg-tertiary);
}
/* Tooltip pour le redimensionnement des images */
.ql-snow .ql-tooltip[data-mode="image"] {
padding: var(--spacing-sm);
display: flex;
gap: var(--spacing-sm);
align-items: center;
}
.ql-snow .ql-tooltip[data-mode="image"] input[type="text"] {
min-width: 200px;
}
/* Style des icônes dans la barre d'outils */
.ql-toolbar.ql-snow {
background: var(--bg-secondary);
border-color: var(--border-color);
border-radius: var(--radius-sm) var(--radius-sm) 0 0;
padding: var(--spacing-sm);
display: flex;
flex-wrap: wrap;
gap: 5px;
}
/* États au survol des boutons */
.ql-toolbar.ql-snow button:hover {
color: var(--accent-primary) !important;
}
.ql-toolbar.ql-snow button:hover svg {
stroke: var(--accent-primary) !important;
}
.ql-toolbar.ql-snow button:hover .ql-stroke {
stroke: var(--accent-primary) !important;
}
.ql-toolbar.ql-snow button:hover .ql-fill {
fill: var(--accent-primary) !important;
}
/* Style des pickers (menus déroulants) */
.ql-toolbar.ql-snow .ql-picker-label:hover {
color: var(--accent-primary) !important;
}
.ql-toolbar.ql-snow .ql-picker-label:hover .ql-stroke {
stroke: var(--accent-primary) !important;
}
/* Style du séparateur dans l'éditeur */
.chapter-divider {
border: none;
border-top: 2px solid var(--accent-primary);
margin: 2em 0;
opacity: 0.5;
transition: opacity var(--transition-fast);
}
.chapter-divider:hover {
opacity: 0.8;
}
/* Style de base des icônes */
.ql-snow .ql-stroke {
stroke: var(--text-primary);
}
.ql-snow .ql-fill {
fill: var(--text-primary);
}
.ql-snow .ql-picker {
color: var(--text-primary);
}
/* États actifs des boutons */
.ql-toolbar.ql-snow .ql-active,
.ql-toolbar.ql-snow .ql-active .ql-stroke,
.ql-toolbar.ql-snow .ql-active .ql-fill {
color: var(--accent-primary) !important;
stroke: var(--accent-primary) !important;
fill: var(--accent-primary) !important;
}
/* Responsive */
@media (max-width: 768px) {
.ql-container {
.ql-snow.ql-toolbar {
padding: var(--spacing-xs);
}
.ql-container.ql-snow {
min-height: 200px;
}
.ql-editor .ql-size-small img {
max-width: 75%;
}
.ql-editor img {
max-width: 100% !important;
}
.ql-snow .ql-tooltip {
left: 0 !important;
top: 100% !important;
width: 100%;
position: fixed;
transform: none !important;
}
.ql-snow .ql-tooltip input[type=text] {
width: 100%;
margin: 4px 0;
}
.tooltip:before {
width: 200px;
white-space: normal;
text-align: center;
}
}

@ -12,6 +12,14 @@
.nav-brand {
font-size: 1.25rem;
font-weight: bold;
display: flex;
align-items: center;
gap: var(--spacing-md);
}
.nav-brand img {
height: 40px;
width: auto;
}
.nav-menu {

@ -1,23 +1,24 @@
/* Thème et variables globales */
:root {
/* Couleurs principales */
--bg-primary: #1a1512;
--bg-secondary: #2c1810;
--bg-tertiary: #382218;
/* Couleurs de fond */
--bg-primary: #2c2424;
--bg-secondary: #3e3232;
--bg-tertiary: #4a3f3f;
/* Textes */
--text-primary: #e0d6cc;
--text-secondary: #b3a69b;
--text-primary: #e6d8cc;
--text-secondary: #cfbfa3;
--text-tertiary: #2c2420;
/* Accents */
--accent-primary: #8b4513;
--accent-secondary: #d4691e;
--accent-primary: #d2a679;
--accent-secondary: #e6b88a;
/* Utilitaires */
--border-color: #483225;
--success-color: #2d5a27;
--error-color: #802020;
--input-bg: #241610;
--border-color: #5a4b4b;
--success-color: #5a8c54;
--error-color: #8c4646;
--input-bg: #332a2a;
/* Espacements */
--spacing-xs: 0.5rem;
@ -43,6 +44,7 @@ body {
font-family: Arial, sans-serif;
background-color: var(--bg-primary);
color: var(--text-primary);
line-height: 1.6;
}
button, input, textarea {
@ -53,16 +55,28 @@ button, input, textarea {
.button {
padding: var(--spacing-sm) var(--spacing-md);
background-color: var(--accent-primary);
color: var(--text-primary);
color: var(--text-tertiary);
border: none;
border-radius: var(--radius-sm);
cursor: pointer;
transition: background-color var(--transition-fast);
transition: all var(--transition-fast);
text-decoration: none;
}
.button:hover {
background-color: var(--accent-secondary);
color: var(--text-tertiary);
}
/* Variante de bouton sombre */
.button.dark {
background-color: var(--bg-secondary);
color: var(--text-primary);
}
.button.dark:hover {
background-color: var(--bg-tertiary);
color: var(--text-primary);
}
/* États de focus globaux */
@ -71,5 +85,24 @@ button, input, textarea {
}
:focus-visible {
box-shadow: 0 0 0 2px rgba(139, 69, 19, 0.2);
box-shadow: 0 0 0 2px rgba(210, 166, 121, 0.4);
}
/* Scrollbar personnalisée */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--bg-primary);
}
::-webkit-scrollbar-thumb {
background: var(--accent-primary);
border-radius: var(--radius-sm);
}
::-webkit-scrollbar-thumb:hover {
background: var(--accent-secondary);
}

Binary file not shown.

Before

Width: 48px  |  Height: 48px  |  Size: 15 KiB

@ -1,33 +1,120 @@
document.addEventListener('DOMContentLoaded', function() {
// Initialisation de l'éditeur Quill
const quill = new Quill('#editor', {
theme: 'snow',
modules: {
toolbar: [
['bold', 'italic', 'underline'],
[{ 'list': 'ordered'}, { 'list': 'bullet' }],
['clean']
]
}
});
// Variables globales
const chaptersList = document.getElementById('chaptersList');
const modal = document.getElementById('chapterEditor');
const addChapterBtn = document.getElementById('addChapter');
let currentChapterId = null;
const storyId = document.querySelector('input[name="id"]')?.value;
// Initialisation du tri par glisser-déposer
// Création de l'icône SVG pour le séparateur
const icons = {
divider: `
<svg viewBox="0 0 18 18">
<line class="ql-stroke" x1="3" x2="15" y1="9" y2="9"></line>
</svg>
`
};
// Ajout de l'icône à Quill
const Block = Quill.import('blots/block');
const icons_list = Quill.import('ui/icons');
icons_list['divider'] = icons.divider;
// Définition du format pour le séparateur
class DividerBlot extends Block {
static create() {
const node = super.create();
node.className = 'chapter-divider';
return node;
}
}
DividerBlot.blotName = 'divider';
DividerBlot.tagName = 'hr';
Quill.register(DividerBlot);
// Configuration et initialisation de Quill
const quill = new Quill('#editor', {
theme: 'snow',
modules: {
toolbar: {
container: [
[{ 'header': [1, 2, 3, false] }],
['bold', 'italic', 'underline', 'strike'],
[{ 'color': [] }, { 'background': [] }],
[{ 'font': [] }],
[{ 'align': [] }],
['blockquote', 'code-block'],
[{ 'list': 'ordered'}, { 'list': 'bullet' }],
[{ 'script': 'sub'}, { 'script': 'super' }],
[{ 'indent': '-1'}, { 'indent': '+1' }],
[{ 'direction': 'rtl' }],
['link', 'image', 'video'],
['divider'],
['clean']
],
handlers: {
image: function() {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.click();
input.onchange = async () => {
const file = input.files[0];
if (file) {
const formData = new FormData();
formData.append('image', file);
formData.append('storyId', storyId);
try {
const response = await fetch('api/upload-image.php', {
method: 'POST',
body: formData
});
if (!response.ok) throw new Error('Upload failed');
const result = await response.json();
if (result.success) {
const range = quill.getSelection(true);
quill.insertEmbed(range.index, 'image', result.url);
quill.setSelection(range.index + 1);
} else {
showNotification(result.error || 'Erreur lors de l\'upload', 'error');
}
} catch (error) {
console.error('Error:', error);
showNotification('Erreur lors de l\'upload de l\'image', 'error');
}
}
};
}
}
},
keyboard: {
bindings: {
tab: false,
'indent backwards': false
}
}
},
placeholder: 'Commencez à écrire votre chapitre ici...'
});
// Gestion des chapitres
const modal = document.getElementById('chapterEditor');
const addChapterBtn = document.getElementById('addChapter');
const saveChapterBtn = document.getElementById('saveChapter');
const cancelEditBtn = document.getElementById('cancelEdit');
const chapterTitleInput = document.getElementById('chapterTitle');
const chaptersList = document.getElementById('chaptersList');
// Configuration de Sortable pour la réorganisation des chapitres
if (chaptersList) {
new Sortable(chaptersList, {
animation: 150,
handle: '.chapter-number',
ghostClass: 'sortable-ghost',
onEnd: async function() {
// Récupérer le nouvel ordre des chapitres
onEnd: async function(evt) {
const chapters = Array.from(chaptersList.children).map((item, index) => ({
id: item.dataset.id,
order: index
position: index
}));
try {
@ -46,160 +133,148 @@ document.addEventListener('DOMContentLoaded', function() {
throw new Error('Erreur lors de la réorganisation');
}
// Mettre à jour les numéros affichés
chapters.forEach((chapter, index) => {
const element = document.querySelector(`[data-id="${chapter.id}"] .chapter-number`);
if (element) {
element.textContent = index + 1;
}
});
} catch (error) {
console.error('Erreur:', error);
alert('Erreur lors de la réorganisation des chapitres');
showNotification('Erreur lors de la réorganisation des chapitres', 'error');
}
}
});
}
// Gestion de l'ajout d'un nouveau chapitre
// Gestionnaires d'événements pour l'édition des chapitres
if (addChapterBtn) {
addChapterBtn.addEventListener('click', () => {
currentChapterId = null;
document.getElementById('chapterTitle').value = '';
quill.setContents([{ insert: '\n' }]);
chapterTitleInput.value = '';
quill.setContents([]);
modal.style.display = 'block';
});
}
// Gestion de l'édition d'un chapitre
chaptersList?.addEventListener('click', async (e) => {
if (e.target.matches('.edit-chapter')) {
const chapterItem = e.target.closest('.chapter-item');
currentChapterId = chapterItem.dataset.id;
try {
const response = await fetch(`api/get-chapter.php?storyId=${storyId}&chapterId=${currentChapterId}`);
if (!response.ok) throw new Error('Erreur lors de la récupération du chapitre');
const chapter = await response.json();
document.getElementById('chapterTitle').value = chapter.title;
try {
if (typeof chapter.content === 'string') {
quill.root.innerHTML = chapter.content;
} else {
quill.setContents(chapter.content);
}
} catch (error) {
console.error('Erreur lors du chargement du contenu:', error);
quill.root.innerHTML = chapter.content;
if (cancelEditBtn) {
cancelEditBtn.addEventListener('click', () => {
if (hasUnsavedChanges()) {
if (!confirm('Des modifications non sauvegardées seront perdues. Voulez-vous vraiment fermer ?')) {
return;
}
modal.style.display = 'block';
} catch (error) {
console.error('Erreur:', error);
alert('Erreur lors de la récupération du chapitre');
}
}
});
modal.style.display = 'none';
});
}
// Gestion de la suppression d'un chapitre
chaptersList?.addEventListener('click', async (e) => {
if (e.target.matches('.delete-chapter')) {
if (!confirm('Voulez-vous vraiment supprimer ce chapitre ?')) return;
const chapterItem = e.target.closest('.chapter-item');
const chapterId = chapterItem.dataset.id;
// Gestion des clics sur la liste des chapitres
if (chaptersList) {
chaptersList.addEventListener('click', async (e) => {
const target = e.target;
if (target.matches('.edit-chapter')) {
const chapterItem = target.closest('.chapter-item');
currentChapterId = chapterItem.dataset.id;
try {
const response = await fetch(`api/get-chapter.php?storyId=${storyId}&chapterId=${currentChapterId}`);
if (!response.ok) {
throw new Error('Erreur réseau');
}
const chapter = await response.json();
// Mise à jour du titre
chapterTitleInput.value = chapter.title || '';
// Gestion du contenu
if (chapter.html) {
quill.root.innerHTML = chapter.html;
} else if (chapter.content) {
try {
const content = typeof chapter.content === 'string'
? JSON.parse(chapter.content)
: chapter.content;
quill.setContents(content);
} catch (contentError) {
console.error('Erreur de parsing du contenu:', contentError);
quill.setText(chapter.content || '');
}
} else {
quill.setContents([]);
}
modal.style.display = 'block';
} catch (error) {
console.error('Erreur détaillée:', error);
showNotification('Erreur lors du chargement du chapitre', 'error');
}
}
});
}
// Sauvegarde d'un chapitre
if (saveChapterBtn) {
saveChapterBtn.addEventListener('click', async () => {
const title = chapterTitleInput.value.trim();
if (!title) {
showNotification('Le titre est requis', 'error');
return;
}
try {
const response = await fetch('api/delete-chapter.php', {
const response = await fetch('api/save-chapter.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
storyId: storyId,
chapterId: chapterId
chapterId: currentChapterId,
title: title,
content: JSON.stringify(quill.getContents())
})
});
if (!response.ok) throw new Error('Erreur lors de la suppression');
chapterItem.remove();
// Mettre à jour les numéros des chapitres
document.querySelectorAll('.chapter-number').forEach((num, index) => {
num.textContent = index + 1;
});
if (response.ok) {
showNotification('Chapitre sauvegardé avec succès');
setTimeout(() => location.reload(), 500);
} else {
throw new Error('Erreur lors de la sauvegarde');
}
} catch (error) {
console.error('Erreur:', error);
alert('Erreur lors de la suppression du chapitre');
showNotification('Erreur lors de la sauvegarde du chapitre', 'error');
}
});
}
function hasUnsavedChanges() {
if (!currentChapterId) {
return chapterTitleInput.value !== '' || quill.getLength() > 1;
}
});
return true;
}
// Gestion de la sauvegarde d'un chapitre
document.getElementById('saveChapter')?.addEventListener('click', async () => {
const title = document.getElementById('chapterTitle').value;
if (!title.trim()) {
alert('Le titre du chapitre est requis');
return;
}
try {
const response = await fetch('api/save-chapter.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
storyId: storyId,
chapterId: currentChapterId,
title: title,
content: quill.root.innerHTML
})
});
if (!response.ok) throw new Error('Erreur lors de la sauvegarde');
const result = await response.json();
if (!currentChapterId) {
// Nouveau chapitre - ajouter à la liste
const newChapter = document.createElement('div');
newChapter.className = 'chapter-item';
newChapter.dataset.id = result.chapterId;
newChapter.innerHTML = `
<span class="chapter-number">${document.querySelectorAll('.chapter-item').length + 1}</span>
<h3 class="chapter-title">${title}</h3>
<div class="chapter-actions">
<button type="button" class="button edit-chapter">Éditer</button>
<button type="button" class="button delete-chapter">Supprimer</button>
</div>
`;
chaptersList.appendChild(newChapter);
} else {
// Mise à jour du titre dans la liste
const chapterItem = document.querySelector(`[data-id="${currentChapterId}"] .chapter-title`);
if (chapterItem) {
chapterItem.textContent = title;
}
}
modal.style.display = 'none';
} catch (error) {
console.error('Erreur:', error);
alert('Erreur lors de la sauvegarde du chapitre');
}
});
// Fermeture de la modale
document.getElementById('cancelEdit')?.addEventListener('click', () => {
modal.style.display = 'none';
});
// Fermeture de la modale en cliquant en dehors
modal?.addEventListener('click', (e) => {
if (e.target === modal) {
modal.style.display = 'none';
}
});
function showNotification(message, type = 'success') {
const notification = document.createElement('div');
notification.className = `notification ${type}`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.opacity = '1';
notification.style.transform = 'translateY(0)';
}, 10);
setTimeout(() => {
notification.style.opacity = '0';
notification.style.transform = 'translateY(-100%)';
setTimeout(() => notification.remove(), 300);
}, 3000);
}
});

@ -1,4 +1,15 @@
<?php
ini_set('session.gc_maxlifetime', 30 * 24 * 60 * 60); // 30 jours en secondes
ini_set('session.cookie_lifetime', 30 * 24 * 60 * 60);
session_set_cookie_params([
'lifetime' => 30 * 24 * 60 * 60,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict'
]);
session_start();
class Config {
@ -20,16 +31,27 @@ class Config {
return $config[$key] ?? $default;
}
public static function save($config) {
public static function save($newConfig) {
$configFile = __DIR__ . '/../config.json';
$jsonContent = json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
if (file_put_contents($configFile, $jsonContent) === false) {
throw new Exception('Impossible de sauvegarder la configuration');
// S'assurer que le fichier est accessible en écriture
if (!is_writable($configFile)) {
throw new Exception('Le fichier de configuration n\'est pas accessible en écriture');
}
self::$config = $config;
// Sauvegarder avec un formatage JSON lisible
$success = file_put_contents(
$configFile,
json_encode($newConfig, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
);
if ($success === false) {
throw new Exception('Erreur lors de la sauvegarde de la configuration');
}
// Mettre à jour la configuration en mémoire
self::$config = $newConfig;
return true;
}
}

86
includes/site-upload.php Normal file

@ -0,0 +1,86 @@
<?php
class SiteUploadHandler {
private $uploadDir;
private $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml'];
private $maxFileSize = 2097152; // 2MB
public function __construct() {
$this->uploadDir = __DIR__ . '/../assets/images/site/';
$this->ensureUploadDirectory();
}
public function handleLogoUpload($file) {
try {
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new Exception($this->getUploadErrorMessage($file['error']));
}
// Vérifier le type MIME
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($file['tmp_name']);
if (!in_array($mimeType, $this->allowedTypes)) {
throw new Exception('Type de fichier non autorisé. Types acceptés : JPG, PNG, GIF, SVG');
}
// Vérifier la taille
if ($file['size'] > $this->maxFileSize) {
throw new Exception('Fichier trop volumineux. Taille maximum : 2MB');
}
// Générer le nom de fichier
$extension = $this->getExtensionFromMimeType($mimeType);
$filename = 'logo.' . $extension;
$targetPath = $this->uploadDir . $filename;
// Supprimer l'ancien logo s'il existe
$this->removeOldLogo();
// Déplacer le fichier
if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
throw new Exception('Erreur lors du déplacement du fichier uploadé');
}
return 'assets/images/site/' . $filename;
} catch (Exception $e) {
throw $e;
}
}
private function ensureUploadDirectory() {
if (!file_exists($this->uploadDir)) {
if (!mkdir($this->uploadDir, 0755, true)) {
throw new Exception('Impossible de créer le dossier d\'upload');
}
}
}
private function removeOldLogo() {
foreach (glob($this->uploadDir . 'logo.*') as $file) {
unlink($file);
}
}
private function getExtensionFromMimeType($mimeType) {
$map = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/svg+xml' => 'svg'
];
return $map[$mimeType] ?? 'png';
}
private function getUploadErrorMessage($error) {
$errors = [
UPLOAD_ERR_INI_SIZE => 'Le fichier dépasse la taille maximale autorisée par PHP',
UPLOAD_ERR_FORM_SIZE => 'Le fichier dépasse la taille maximale autorisée par le formulaire',
UPLOAD_ERR_PARTIAL => 'Le fichier n\'a été que partiellement uploadé',
UPLOAD_ERR_NO_FILE => 'Aucun fichier n\'a été uploadé',
UPLOAD_ERR_NO_TMP_DIR => 'Dossier temporaire manquant',
UPLOAD_ERR_CANT_WRITE => 'Échec de l\'écriture du fichier sur le disque',
UPLOAD_ERR_EXTENSION => 'Une extension PHP a arrêté l\'upload'
];
return $errors[$error] ?? 'Erreur inconnue lors de l\'upload';
}
}

@ -15,6 +15,10 @@ $stories = Stories::getAll();
</head>
<body>
<header>
<?php if (!empty($config['site']['logo'])): ?>
<img src="<?= htmlspecialchars($config['site']['logo']) ?>"
alt="<?= htmlspecialchars($config['site']['name']) ?>">
<?php endif; ?>
<h1><?= htmlspecialchars($config['site']['name']) ?></h1>
<p><?= htmlspecialchars($config['site']['description']) ?></p>
</header>