Kommentare ohne js verfassen

This commit is contained in:
2026-07-18 15:26:13 +02:00
parent 0b4c5f988d
commit ada97ec538
4 changed files with 272 additions and 57 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="dataSourceStorageLocal" created-in="IU-261.25134.95">
<component name="dataSourceStorageLocal" created-in="IU-253.32098.101">
<data-source name="articles" uuid="315cb5c9-2b0f-435b-b602-59823b160908">
<database-info product="SQLite" version="3.51.1" jdbc-version="4.2" driver-name="SQLite JDBC" driver-version="3.51.1.0" dbms="SQLITE" exact-version="3.51.1" exact-driver-version="3.51">
<identifier-quote-string>&quot;</identifier-quote-string>
+92 -12
View File
@@ -5,6 +5,34 @@ $repliesByParent = [];
$articleObj = null;
include_once 'php/controller/showArticle-controller.php';
/*
* Ermittelt, ob ohne JavaScript auf einen Kommentar
* geantwortet werden soll.
*/
$replyTo = filter_input(
INPUT_GET,
"reply_to",
FILTER_VALIDATE_INT
);
$replyAuthor = null;
if ($replyTo !== false && $replyTo !== null) {
foreach ($mainComments as $mainComment) {
if ($mainComment->getId() === $replyTo) {
$replyAuthor = $mainComment->getAuthor();
break;
}
}
}
/*
* Eine Antwort darf nur auf einen existierenden
* Hauptkommentar geschrieben werden.
*/
if ($replyAuthor === null) {
$replyTo = null;
}
?>
<!--
Seite: Anzeige für Beiträge
@@ -17,8 +45,6 @@ include_once 'php/controller/showArticle-controller.php';
<!-- Metadaten & Titel -->
<div class="article-view-top-section">
<div class="article-view-top-section">
<div class="category-and-likes-row">
<?php if (isset($category) && !empty($category)): ?>
<span class="article-view-category"><?php echo htmlspecialchars($category); ?></span>
@@ -106,9 +132,24 @@ include_once 'php/controller/showArticle-controller.php';
</div>
<?php endif; ?>
<section class="article-comments-section">
<section class="article-comments-section" id="comments">
<h2>Kommentare</h2>
<?php if (isset($_SESSION["comment_message"])): ?>
<div class="alert-message <?php
echo ($_SESSION["comment_message_type"] ?? "") === "success"
? "is-success"
: "is-error";
?>">
<?php echo htmlspecialchars($_SESSION["comment_message"]); ?>
</div>
<?php
unset($_SESSION["comment_message"]);
unset($_SESSION["comment_message_type"]);
?>
<?php endif; ?>
<div id="comments-list">
<?php if (!empty($mainComments)): ?>
<?php foreach ($mainComments as $comment): ?>
@@ -121,12 +162,22 @@ include_once 'php/controller/showArticle-controller.php';
<p><?php echo nl2br(htmlspecialchars($comment->getContent())); ?></p>
<?php if (isset($_SESSION["user_email"])): ?>
<button type="button"
class="reply-button"
data-comment-id="<?php echo htmlspecialchars($comment->getId()); ?>"
data-author="<?php echo htmlspecialchars($comment->getAuthor()); ?>">
<a href="index.php?pfad=<?php
echo urlencode($_GET["pfad"] ?? "showArticle");
?>&id=<?php
echo urlencode((string) ($_GET["id"] ?? ""));
?>&reply_to=<?php
echo urlencode((string) $comment->getId());
?>#comment-form"
class="reply-button"
data-comment-id="<?php echo htmlspecialchars(
(string) $comment->getId()
); ?>"
data-author="<?php echo htmlspecialchars(
$comment->getAuthor()
); ?>">
Antworten
</button>
</a>
<?php endif; ?>
<div class="comment-replies">
@@ -153,17 +204,46 @@ include_once 'php/controller/showArticle-controller.php';
</div>
<?php if (isset($_SESSION["user_email"])): ?>
<form id="comment-form">
<form id="comment-form"
method="post"
action="php/ajax/add-comment.php">
<input type="hidden"
name="article_id"
value="<?php echo htmlspecialchars($_GET["id"] ?? ""); ?>">
value="<?php echo htmlspecialchars(
(string) ($_GET["id"] ?? "")
); ?>">
<input type="hidden"
name="parent_comment_id"
id="parent-comment-id"
value="">
value="<?php echo $replyTo !== null
? htmlspecialchars((string) $replyTo)
: "";
?>">
<p id="reply-info" class="reply-info" style="display: none;"></p>
<p id="reply-info"
class="reply-info"
<?php if ($replyAuthor === null): ?>
style="display: none;"
<?php endif; ?>>
<?php if ($replyAuthor !== null): ?>
Antwort auf <?php echo htmlspecialchars($replyAuthor); ?>
<a href="index.php?pfad=<?php
echo urlencode($_GET["pfad"] ?? "showArticle");
?>&id=<?php
echo urlencode((string) ($_GET["id"] ?? ""));
?>#comment-form">
Abbrechen
</a>
<?php endif; ?>
</p>
<label for="comment-content">
Kommentar
</label>
<textarea name="content"
id="comment-content"
+23 -14
View File
@@ -16,14 +16,20 @@ document.addEventListener("DOMContentLoaded", function () {
}
/**
* Aktiviert einen einzelnen Antworten-Button.
* Aktiviert einen einzelnen Antworten-Link.
*
* @param {HTMLButtonElement} button Antworten-Button
* @param {HTMLAnchorElement} replyLink Antworten-Link
*/
function registerReplyButton(button) {
button.addEventListener("click", function () {
parentCommentInput.value = button.dataset.commentId;
replyInfo.textContent = "Antwort auf " + button.dataset.author;
function registerReplyButton(replyLink) {
replyLink.addEventListener("click", function (event) {
/*
* Mit JavaScript wird die Seite nicht neu geladen.
* Ohne JavaScript funktioniert der normale Link.
*/
event.preventDefault();
parentCommentInput.value = replyLink.dataset.commentId;
replyInfo.textContent = "Antwort auf " + replyLink.dataset.author;
replyInfo.style.display = "block";
commentContent.focus();
});
@@ -45,9 +51,12 @@ document.addEventListener("DOMContentLoaded", function () {
const formData = new FormData(form);
const parentCommentId = parentCommentInput.value;
fetch("php/ajax/add-comment.php", {
fetch(form.action, {
method: "POST",
body: formData
body: formData,
headers: {
"X-Requested-With": "XMLHttpRequest"
}
})
.then(response => response.json())
.then(data => {
@@ -94,12 +103,12 @@ document.addEventListener("DOMContentLoaded", function () {
</p>
<p>${escapeHtml(data.content).replace(/\n/g, "<br>")}</p>
<button type="button"
class="reply-button"
data-comment-id="${escapeHtml(data.commentId)}"
data-author="${escapeHtml(data.author)}">
Antworten
</button>
<a href="#comment-form"
class="reply-button"
data-comment-id="${escapeHtml(data.commentId)}"
data-author="${escapeHtml(data.author)}">
Antworten
</a>
<div class="comment-replies"></div>
`;
+156 -30
View File
@@ -3,32 +3,153 @@ if (session_status() === PHP_SESSION_NONE) {
session_start();
}
header("Content-Type: application/json");
require_once "../model/CommentManager.php";
if (!isset($_SESSION["user_email"])) {
echo json_encode([
"success" => false,
"message" => "Du musst angemeldet sein, um zu kommentieren."
]);
/**
* Prüft, ob die Anfrage durch JavaScript per AJAX gesendet wurde.
*/
$isAjaxRequest = isset($_SERVER["HTTP_X_REQUESTED_WITH"])
&& strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest";
/**
* Gibt das Ergebnis entweder als JSON zurück oder leitet
* bei einem normalen Formularaufruf wieder zum Beitrag zurück.
*
* @param bool $success War das Speichern erfolgreich?
* @param string $message Rückmeldung für den Benutzer
* @param int|null $articleId ID des Beitrags
* @param array $additionalData Zusätzliche Daten für AJAX
*/
function sendCommentResponse(
$success,
$message,
$articleId,
$additionalData = []
) {
global $isAjaxRequest;
if ($isAjaxRequest) {
header("Content-Type: application/json; charset=utf-8");
echo json_encode(
array_merge(
[
"success" => $success,
"message" => $message
],
$additionalData
)
);
exit();
}
/*
* Bei deaktiviertem JavaScript wird die Rückmeldung
* in der Session gespeichert und die Beitragsseite neu geladen.
*/
$_SESSION["comment_message"] = $message;
$_SESSION["comment_message_type"] = $success ? "success" : "error";
if ($articleId !== null) {
header(
"Location: ../../index.php?pfad=showArticle&id="
. urlencode((string) $articleId)
. "#comments"
);
} else {
header("Location: ../../index.php");
}
exit();
}
$articleId = $_POST["article_id"] ?? null;
$content = trim($_POST["content"] ?? "");
$parentCommentId = $_POST["parent_comment_id"] ?? null;
/*
* Nur POST-Anfragen dürfen Kommentare erstellen.
*/
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
sendCommentResponse(
false,
"Ungültige Anfrage.",
null
);
}
if ($parentCommentId === "" || $parentCommentId === "0") {
/*
* Die Beitrags-ID wird zuerst eingelesen,
* damit bei Fehlern wieder zum Beitrag zurückgeleitet werden kann.
*/
$articleId = filter_input(
INPUT_POST,
"article_id",
FILTER_VALIDATE_INT
);
/*
* Ein Benutzer muss angemeldet sein.
*/
if (!isset($_SESSION["user_email"])) {
sendCommentResponse(
false,
"Du musst angemeldet sein, um zu kommentieren.",
$articleId !== false ? $articleId : null
);
}
/*
* Weitere Formulardaten einlesen.
*/
$content = trim($_POST["content"] ?? "");
$parentCommentId = filter_input(
INPUT_POST,
"parent_comment_id",
FILTER_VALIDATE_INT
);
/*
* Ein leerer Wert bedeutet, dass es sich um einen
* normalen Hauptkommentar handelt.
*/
if (
!isset($_POST["parent_comment_id"])
|| $_POST["parent_comment_id"] === ""
|| $_POST["parent_comment_id"] === "0"
) {
$parentCommentId = null;
}
if (empty($articleId) || empty($content)) {
echo json_encode([
"success" => false,
"message" => "Kommentar darf nicht leer sein."
]);
exit();
if ($articleId === false || $articleId === null) {
sendCommentResponse(
false,
"Der zugehörige Beitrag ist ungültig.",
null
);
}
if ($content === "") {
sendCommentResponse(
false,
"Der Kommentar darf nicht leer sein.",
$articleId
);
}
/*
* Eine ungültige Eltern-ID darf nicht gespeichert werden.
*/
if (
isset($_POST["parent_comment_id"])
&& $_POST["parent_comment_id"] !== ""
&& $_POST["parent_comment_id"] !== "0"
&& $parentCommentId === false
) {
sendCommentResponse(
false,
"Der ausgewählte Kommentar ist ungültig.",
$articleId
);
}
try {
@@ -41,18 +162,23 @@ try {
$parentCommentId
);
echo json_encode([
"success" => true,
"commentId" => $commentId,
"author" => $_SESSION["user_email"],
"content" => $content,
"created" => date("Y-m-d H:i:s"),
"parentCommentId" => $parentCommentId
]);
sendCommentResponse(
true,
"Der Kommentar wurde erfolgreich gespeichert.",
$articleId,
[
"commentId" => $commentId,
"author" => $_SESSION["user_email"],
"content" => $content,
"created" => date("Y-m-d H:i:s"),
"parentCommentId" => $parentCommentId
]
);
} catch (Exception $e) {
echo json_encode([
"success" => false,
"message" => "Kommentar konnte nicht gespeichert werden."
]);
} catch (Throwable $e) {
sendCommentResponse(
false,
"Der Kommentar konnte nicht gespeichert werden.",
$articleId
);
}