Update updateArticle-controller.php
This commit is contained in:
@@ -13,11 +13,73 @@ if (!isset($_SESSION["user_email"])) {
|
||||
exit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut die Blockliste aus den POST-Daten (blocks[i][type], blocks[i][text],
|
||||
* blocks[i][existing_image]) und ggf. hochgeladenen Dateien (blocks[i][image])
|
||||
* zusammen. Läuft bei JEDEM Submit (Zwischen-Schritt "Block hinzufügen/löschen"
|
||||
* UND finales Speichern), damit neu ausgewählte Bilder in jedem Fall persistiert
|
||||
* werden, bevor PHP die temporäre Upload-Datei nach Request-Ende verwirft.
|
||||
*
|
||||
* @param array $postBlocks $_POST['blocks'] ?? []
|
||||
* @param array $fileBlocks $_FILES['blocks'] ?? []
|
||||
* @param string $uploadDir absoluter Pfad zum uploads-Verzeichnis (mit trailing slash)
|
||||
* @return array Liste von ['type' => 'text'|'image', 'value' => string]
|
||||
*/
|
||||
function rebuildBlocksFromPost(array $postBlocks, array $fileBlocks, string $uploadDir): array {
|
||||
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
|
||||
|
||||
$keys = array_keys($postBlocks);
|
||||
if (isset($fileBlocks['name']) && is_array($fileBlocks['name'])) {
|
||||
$keys = array_unique(array_merge($keys, array_keys($fileBlocks['name'])));
|
||||
}
|
||||
sort($keys, SORT_NUMERIC);
|
||||
|
||||
$blocks = [];
|
||||
|
||||
foreach ($keys as $key) {
|
||||
$type = $postBlocks[$key]['type'] ?? null;
|
||||
|
||||
if ($type === 'text') {
|
||||
$blocks[] = [
|
||||
'type' => 'text',
|
||||
'value' => $postBlocks[$key]['text'] ?? '',
|
||||
];
|
||||
} elseif ($type === 'image') {
|
||||
// Vorbelegung: bereits vorhandenes Server-Bild (falls Datei nicht ersetzt wird)
|
||||
$value = $postBlocks[$key]['existing_image'] ?? '';
|
||||
|
||||
$hasUpload = isset($fileBlocks['error'][$key]['image'])
|
||||
&& $fileBlocks['error'][$key]['image'] === UPLOAD_ERR_OK;
|
||||
|
||||
if ($hasUpload) {
|
||||
$tmpName = $fileBlocks['tmp_name'][$key]['image'];
|
||||
$originalName = $fileBlocks['name'][$key]['image'];
|
||||
$extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
|
||||
if (!in_array($extension, $allowedExtensions, true)) {
|
||||
$extension = 'jpg';
|
||||
}
|
||||
|
||||
$fileName = 'img_' . uniqid() . '.' . $extension;
|
||||
$destination = $uploadDir . $fileName;
|
||||
|
||||
if (move_uploaded_file($tmpName, $destination)) {
|
||||
$value = 'uploads/' . $fileName;
|
||||
}
|
||||
// Bei Fehler: alter Wert (falls vorhanden) bleibt erhalten, Block wird nicht verworfen
|
||||
}
|
||||
|
||||
$blocks[] = [
|
||||
'type' => 'image',
|
||||
'value' => $value,
|
||||
];
|
||||
}
|
||||
// unbekannter/fehlender type -> Block wird ignoriert
|
||||
}
|
||||
|
||||
return $blocks;
|
||||
}
|
||||
|
||||
if ($_SERVER["REQUEST_METHOD"] === "POST") {
|
||||
$_SESSION["old_title"] = $_POST["title"] ?? '';
|
||||
$_SESSION["old_content"] = $_POST["content"] ?? '';
|
||||
$_SESSION["old_category"] = $_POST["category"] ?? '';
|
||||
$_SESSION["old_tags"] = $_POST["tags"] ?? '';
|
||||
|
||||
if (isset($_GET["id"]) && !empty($_GET["id"])) {
|
||||
$id = $_GET["id"];
|
||||
@@ -41,13 +103,51 @@ if ($_SERVER["REQUEST_METHOD"] === "POST") {
|
||||
exit();
|
||||
}
|
||||
|
||||
if (!isset($_POST["title"]) ||!isset($_POST["content"]) || !isset($_POST["category"])){
|
||||
$uploadDir = __DIR__ . '/../../uploads/';
|
||||
if (!file_exists($uploadDir)) {
|
||||
mkdir($uploadDir, 0755, true);
|
||||
}
|
||||
|
||||
// Formularzustand (Titel/Tags/Kategorie/Blöcke) immer sichern, damit er nach einem
|
||||
// Redirect (PRG-Pattern oder Validierungsfehler) wieder angezeigt werden kann.
|
||||
$_SESSION["old_title"] = $_POST["title"] ?? '';
|
||||
$_SESSION["old_tags"] = $_POST["tags"] ?? '';
|
||||
$_SESSION["old_category"] = $_POST["category"] ?? '';
|
||||
|
||||
$blocks = rebuildBlocksFromPost($_POST['blocks'] ?? [], $_FILES['blocks'] ?? [], $uploadDir);
|
||||
$_SESSION["old_content"] = json_encode($blocks, JSON_UNESCAPED_UNICODE);
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Zwischenspeichern
|
||||
// ---------------------------------------------------------------------
|
||||
if (isset($_POST['editor_action']) && $_POST['editor_action'] !== '') {
|
||||
$action = $_POST['editor_action'];
|
||||
|
||||
if ($action === 'add_text') {
|
||||
$blocks[] = ['type' => 'text', 'value' => ''];
|
||||
} elseif ($action === 'add_image') {
|
||||
$blocks[] = ['type' => 'image', 'value' => ''];
|
||||
} elseif (str_starts_with($action, 'delete_block:')) {
|
||||
$deleteIndex = (int) substr($action, strlen('delete_block:'));
|
||||
unset($blocks[$deleteIndex]);
|
||||
$blocks = array_values($blocks);
|
||||
}
|
||||
|
||||
$_SESSION["old_content"] = json_encode($blocks, JSON_UNESCAPED_UNICODE);
|
||||
header("location: ../../content/updateArticle.php?id=$id");
|
||||
exit();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Echtes Speichern
|
||||
// ---------------------------------------------------------------------
|
||||
if (!isset($_POST["title"]) || !isset($_POST["category"])) {
|
||||
$_SESSION["message"] = "missing_parameters";
|
||||
header("location: ../../index.php?pfad=updateArticle&id=$id");
|
||||
exit();
|
||||
}else{
|
||||
} else {
|
||||
$title = $_POST["title"];
|
||||
$content = $_POST["content"];
|
||||
$content = json_encode($blocks, JSON_UNESCAPED_UNICODE);
|
||||
$author = $_SESSION["user_email"];
|
||||
$category = $_POST["category"];
|
||||
$tags = $_POST['tags'] ?? '';
|
||||
@@ -88,91 +188,51 @@ if ($_SERVER["REQUEST_METHOD"] === "POST") {
|
||||
$cleanedTags = implode(',', $cleanedTags);
|
||||
}
|
||||
|
||||
// --------------------------------------- Base64-Bilder speichern ---------------------------------------------
|
||||
$blocks = json_decode($content, true);
|
||||
$uploadDir = __DIR__ . '/../../uploads/';
|
||||
|
||||
if (!file_exists($uploadDir)) {
|
||||
mkdir($uploadDir, 0755, true);
|
||||
}
|
||||
|
||||
// ----------------- Gelöschte Bilder über die JS-Löschliste entfernen ----------------- TODO: Gelöschte Bilder über die JS-Löschliste entfernen
|
||||
/*if (isset($_POST['deleted_images'])) {
|
||||
$deletedImages = json_decode($_POST['deleted_images'], true);
|
||||
|
||||
// Wir ermitteln den physisch echten, absoluten Pfad zum uploads-Ordner auf der Festplatte
|
||||
$uploadDir = realpath(__DIR__ . '/../../uploads') . DIRECTORY_SEPARATOR;
|
||||
|
||||
if (is_array($deletedImages)) {
|
||||
foreach ($deletedImages as $imagePath) {
|
||||
// Nur den reinen Dateinamen heraustrennen (z.B. img_65a123.jpg)
|
||||
$filename = basename($imagePath);
|
||||
$fullDeletePath = $uploadDir . $filename;
|
||||
|
||||
// Debugging & Löschen:
|
||||
if (file_exists($fullDeletePath)) {
|
||||
// Versuchen zu löschen. Wenn es fehlschlägt, Fehlermeldung erzwingen
|
||||
if (!@unlink($fullDeletePath)) {
|
||||
$error = error_get_last();
|
||||
die("Datei existiert, aber PHP darf sie nicht löschen! Grund: " . $error['message']);
|
||||
}
|
||||
} else {
|
||||
// Wenn PHP die Datei an diesem Pfad nicht findet, brechen wir zum Debuggen ab
|
||||
// die("PHP findet die Datei nicht unter dem Pfad: " . $fullDeletePath);
|
||||
// ----------------- Verwaiste Bilder aufräumen -----------------
|
||||
// Bilder, die im alten (gespeicherten) Content vorkamen, im neuen aber nicht
|
||||
// mehr referenziert werden, wurden vom Nutzer entfernt oder ersetzt -> löschen.
|
||||
// TODO: Bilder, die innerhalb derselben Bearbeitungs-Sitzung neu hochgeladen und noch vor dem finalen Speichern wieder entfernt wurden, werden hierüber nicht erfasst (sie tauchten nie im alten Content auf) und bleiben als Datei liegen. Für eine vollständige Bereinigung würde sich ein
|
||||
$oldBlocks = json_decode($article->getContent(), true);
|
||||
$oldImagePaths = [];
|
||||
if (is_array($oldBlocks)) {
|
||||
foreach ($oldBlocks as $oldBlock) {
|
||||
if (($oldBlock['type'] ?? '') === 'image'
|
||||
&& !empty($oldBlock['value'])
|
||||
&& is_string($oldBlock['value'])
|
||||
&& str_starts_with($oldBlock['value'], 'uploads/')) {
|
||||
$oldImagePaths[] = $oldBlock['value'];
|
||||
}
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
// ----------------------- NEU hinzugefügte Base64-Bilder: --------------------------
|
||||
if (is_array($blocks)) {
|
||||
foreach ($blocks as &$block) {
|
||||
// Prüfen, ob der Block ein Bild ist und ein NEUES Bild (Base64-Format) enthält
|
||||
if (isset($block['type']) && isset($block['value']) && $block['type'] === 'image' && is_string($block['value'])) {
|
||||
|
||||
if (str_starts_with($block['value'], 'data:image/')) {
|
||||
$parts = explode(',', $block['value']);
|
||||
if (count($parts) >= 2) {
|
||||
$metadata = $parts[0];
|
||||
$base64Data = $parts[1];
|
||||
|
||||
preg_match('/data:image\/(?<extension>.*?);/', $metadata, $matches);
|
||||
$extension = $matches['extension'] ?? 'jpg';
|
||||
if ($extension === 'jpeg') { $extension = 'jpg'; }
|
||||
|
||||
$fileName = 'img_' . uniqid() . '.' . $extension;
|
||||
$filePath = $uploadDir . $fileName;
|
||||
|
||||
if (file_put_contents($filePath, base64_decode($base64Data)) !== false) {
|
||||
$block['value'] = 'uploads/' . $fileName;
|
||||
} else {
|
||||
$_SESSION["message"] = "image_upload_error";
|
||||
header("location: ../../index.php?pfad=updateArticle&id=$id");
|
||||
exit();
|
||||
$newImagePaths = [];
|
||||
foreach ($blocks as $block) {
|
||||
if (($block['type'] ?? '') === 'image' && !empty($block['value'])) {
|
||||
$newImagePaths[] = $block['value'];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
unset($block);
|
||||
}
|
||||
|
||||
// Aktualisiertes Array wieder in JSON konvertieren
|
||||
$finalContent = json_encode($blocks, JSON_UNESCAPED_UNICODE);
|
||||
$orphanedImages = array_diff($oldImagePaths, $newImagePaths);
|
||||
foreach ($orphanedImages as $orphanedImage) {
|
||||
$absolutePath = __DIR__ . '/../../' . $orphanedImage;
|
||||
if (is_file($absolutePath)) {
|
||||
@unlink($absolutePath);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------- Übertragung der validierten Daten in ArticleManager: ---------------------------
|
||||
try {
|
||||
$articleManager = ArticleManager::getInstance();
|
||||
$article = $articleManager->getArticle($id);
|
||||
$article->setTitle($title);
|
||||
$article->setContent($finalContent);
|
||||
$article->setContent($content);
|
||||
$article->setCategory($category);
|
||||
$article->setTags($cleanedTags);
|
||||
$articleManager->updateArticle($id ,$article, $author);
|
||||
$articleManager->updateArticle($id, $article, $author);
|
||||
|
||||
unset($_SESSION["old_title"], $_SESSION["old_content"], $_SESSION["old_category"], $_SESSION["old_tags"]);
|
||||
|
||||
} catch (\Throwable $e){
|
||||
} catch (\Throwable $e) {
|
||||
$_SESSION["message"] = $e->getMessage();
|
||||
header("location: ../../index.php?pfad=updateArticle&id=$id");
|
||||
exit();
|
||||
|
||||
Reference in New Issue
Block a user