blog-app/core/controllers/Comment.php
2021-11-13 14:19:55 +08:00

86 lines
2.4 KiB
PHP

<?php
namespace Controllers;
class Comment
{
public function create()
{
if (! $this->commentValid()) {
header('Location: /post/' . $_POST['post_id']);
return false;
}
$sql = 'INSERT INTO comments VALUES (NULL, ?, ?, DEFAULT, DEFAULT, ?)';
$query = db()->prepare($sql);
$query->execute([
trim($_POST['content']),
$_SESSION['username'],
$_POST['post_id']
]);
header("Location: /post/{$_POST['post_id']}");
return false;
}
public function update($id)
{
if (! $this->isCommentAuthor($id)) {
header('HTTP/1.0 403 Forbidden');
die();
return false;
}
if (! $this->commentValid()) {
header('Location: /post/' . $_POST['post_id']);
return false;
}
$sql = 'UPDATE comments SET content=? WHERE id=?';
$query = db()->prepare($sql);
$query->execute([trim($_POST['content']), $id]);
header("Location: /post/{$_POST['post_id']}");
return false;
}
public function delete($id)
{
if (! $this->isAuthor($id)) {
header('HTTP/1.0 403 Forbidden');
die();
return false;
}
$sql = 'DELETE FROM comments WHERE id=?';
$query = db()->prepare($sql);
$query->execute([$id]);
header("Location: /post/{$_POST['post_id']}");
return false;
}
private function isCommentAuthor($id)
{
$sql = 'SELECT author FROM comments WHERE id=?';
$query = db()->prepare($sql);
$query->execute([$id]);
$comment = $query->fetchAll(\PDO::FETCH_CLASS, 'Core\\Record');
return (count($comment) != 0 &&
$comment[0]->author == $_SESSION['username']);
}
private function isAuthor($id)
{
$sql = 'SELECT author FROM posts WHERE id IN ( ' .
'SELECT comment_to FROM comments WHERE id=? )';
$query = db()->prepare($sql);
$query->execute([$id]);
$post = $query->fetchAll(\PDO::FETCH_CLASS, 'Core\\Record');
return (count($post) != 0 &&
$post[0]->author == $_SESSION['username']);
}
private function commentValid()
{
if (empty(trim($_POST['content']))) {
$_SESSION['comment_errors'] = ['Comment cannot be empty.'];
return false;
}
return true;
}
}