Add blog extension
This commit is contained in:
+3
-2
@@ -2,8 +2,9 @@ FROM php:8.4-apache-bookworm
|
|||||||
WORKDIR "/var/www/html"
|
WORKDIR "/var/www/html"
|
||||||
|
|
||||||
RUN apt-get update; \
|
RUN apt-get update; \
|
||||||
docker-php-ext-install pdo_mysql; \
|
|
||||||
apt-get -y --no-install-recommends install \
|
apt-get -y --no-install-recommends install \
|
||||||
git; \
|
git \
|
||||||
|
libonig-dev; \
|
||||||
|
docker-php-ext-install mbstring pdo_mysql; \
|
||||||
apt-get clean; \
|
apt-get clean; \
|
||||||
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*
|
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# Plugi Blog Extension
|
||||||
|
|
||||||
|
The blog extension provides Website Manager post and category management plus two page-builder blocks. Posts are single-language; post bodies are stored as plain text and safely escaped when rendered.
|
||||||
|
|
||||||
|
## Install and update the database
|
||||||
|
|
||||||
|
1. Place this directory at `extensions/plugi-ext-blog`. Plugi automatically discovers extension folders containing both `extension.php` and `config.php`.
|
||||||
|
2. Open Website Manager and apply the pending database definition update. Existing installations need this update to create the extension-owned post and category tables.
|
||||||
|
3. Add categories if useful, then create posts as drafts or publish them from the Blog section.
|
||||||
|
|
||||||
|
## Create the public pages
|
||||||
|
|
||||||
|
1. Create a regular Plugi page with the route `/blog` and add the **Published Posts** block. It lists published posts newest first; drafts are never shown.
|
||||||
|
2. Create another regular page with the route `/blog/{slug}` and add the **Blog Post** block. The core router supplies the named `slug` parameter to the block.
|
||||||
|
3. Apply the site’s normal page layout and theme to both pages. Their presentation remains controlled by the page builder and theme.
|
||||||
|
|
||||||
|
The detail block displays a not-found state for a missing, unknown, or unpublished slug. The blog blocks are not page-cached so publishing or editing content is reflected on the next request. Authors, tags, scheduling, RSS, and translated posts are not included in this release.
|
||||||
|
|
||||||
|
Keep `/blog` and `/blog/{slug}` unique among the site’s page routes.
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Plugi\Extensions\Blog;
|
||||||
|
|
||||||
|
use InvalidArgumentException;
|
||||||
|
use Plugi\Repositories\BaseRepository;
|
||||||
|
|
||||||
|
class CategoriesRepository extends BaseRepository
|
||||||
|
{
|
||||||
|
protected $table = 'ext__blog_categories';
|
||||||
|
|
||||||
|
public function create(array $data)
|
||||||
|
{
|
||||||
|
return parent::create($this->validatedData($data));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update($instance, array $data)
|
||||||
|
{
|
||||||
|
$id = is_array($instance) ? ($instance['id'] ?? null) : ($instance->id ?? null);
|
||||||
|
if (!is_numeric($id) || (int) $id < 1 || $this->findWithId($id) === null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return parent::update(['id' => (int) $id], $this->validatedData($data, (int) $id));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getAllForAdmin(): array
|
||||||
|
{
|
||||||
|
return $this->db->select("SELECT * FROM {$this->table} ORDER BY name ASC, id ASC", []);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function destroy($id)
|
||||||
|
{
|
||||||
|
if (!is_numeric($id) || (int) $id < 1) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->db->transaction(function () use ($id) {
|
||||||
|
return (new PostsRepository())->clearCategory((int) $id) && parent::destroy((int) $id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function validatedData(array $data, ?int $categoryId = null): array
|
||||||
|
{
|
||||||
|
$name = is_string($data['name'] ?? null) ? trim($data['name']) : '';
|
||||||
|
$slug = is_string($data['slug'] ?? null) ? trim($data['slug']) : '';
|
||||||
|
if ($name === '' || mb_strlen($name) > 255) {
|
||||||
|
throw new InvalidArgumentException('A category name of 1–255 characters is required.');
|
||||||
|
}
|
||||||
|
if (strlen($slug) > 191 || !preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug)) {
|
||||||
|
throw new InvalidArgumentException('Use a lowercase slug with letters, numbers, and single hyphens.');
|
||||||
|
}
|
||||||
|
foreach ($this->findWhere('slug', $slug) as $category) {
|
||||||
|
if ((int) $category['id'] !== $categoryId) {
|
||||||
|
throw new InvalidArgumentException('That category slug is already in use.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['name' => $name, 'slug' => $slug];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Plugi\Extensions\Blog;
|
||||||
|
|
||||||
|
use DateTimeImmutable;
|
||||||
|
use InvalidArgumentException;
|
||||||
|
use Plugi\Repositories\BaseRepository;
|
||||||
|
|
||||||
|
class PostsRepository extends BaseRepository
|
||||||
|
{
|
||||||
|
protected $table = 'ext__blog_posts';
|
||||||
|
|
||||||
|
public function create(array $data)
|
||||||
|
{
|
||||||
|
return parent::create($this->validatedData($data));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update($instance, array $data)
|
||||||
|
{
|
||||||
|
$id = is_array($instance) ? ($instance['id'] ?? null) : ($instance->id ?? null);
|
||||||
|
if (!is_numeric($id) || (int) $id < 1 || $this->findWithId($id) === null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return parent::update(['id' => (int) $id], $this->validatedData($data, (int) $id));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getAllForAdmin(): array
|
||||||
|
{
|
||||||
|
return $this->db->select("SELECT * FROM {$this->table} ORDER BY updated_at DESC, id DESC", []);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getPublishedForListing(): array
|
||||||
|
{
|
||||||
|
$categoriesTable = $_ENV['DATABASE_PREFIX'] . 'ext__blog_categories';
|
||||||
|
return $this->db->select(
|
||||||
|
"SELECT posts.*, categories.name AS category_name FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id WHERE posts.status = ? ORDER BY posts.published_at DESC, posts.id DESC",
|
||||||
|
['published']
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function findPublishedBySlug(string $slug): ?array
|
||||||
|
{
|
||||||
|
$categoriesTable = $_ENV['DATABASE_PREFIX'] . 'ext__blog_categories';
|
||||||
|
$posts = $this->db->select(
|
||||||
|
"SELECT posts.*, categories.name AS category_name FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id WHERE posts.slug = ? AND posts.status = ? LIMIT 1",
|
||||||
|
[$slug, 'published']
|
||||||
|
);
|
||||||
|
|
||||||
|
return $posts[0] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function clearCategory(int $categoryId): bool
|
||||||
|
{
|
||||||
|
return $this->db->query("UPDATE {$this->table} SET category_id = NULL WHERE category_id = ?", [$categoryId]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function validatedData(array $data, ?int $postId = null): array
|
||||||
|
{
|
||||||
|
$title = is_string($data['title'] ?? null) ? trim($data['title']) : '';
|
||||||
|
$slug = is_string($data['slug'] ?? null) ? trim($data['slug']) : '';
|
||||||
|
$excerpt = is_string($data['excerpt'] ?? null) ? trim($data['excerpt']) : '';
|
||||||
|
$body = is_string($data['body'] ?? null) ? $data['body'] : '';
|
||||||
|
$status = is_string($data['status'] ?? null) ? $data['status'] : '';
|
||||||
|
|
||||||
|
if ($title === '' || mb_strlen($title) > 255) {
|
||||||
|
throw new InvalidArgumentException('A title of 1–255 characters is required.');
|
||||||
|
}
|
||||||
|
if (strlen($slug) > 191 || !preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug)) {
|
||||||
|
throw new InvalidArgumentException('Use a lowercase slug with letters, numbers, and single hyphens.');
|
||||||
|
}
|
||||||
|
foreach ($this->findWhere('slug', $slug) as $post) {
|
||||||
|
if ((int) $post['id'] !== $postId) {
|
||||||
|
throw new InvalidArgumentException('That post slug is already in use.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!in_array($status, ['draft', 'published'], true)) {
|
||||||
|
throw new InvalidArgumentException('Choose draft or published status.');
|
||||||
|
}
|
||||||
|
if ($status === 'published' && trim($body) === '') {
|
||||||
|
throw new InvalidArgumentException('Add the post body before publishing.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$categoryId = $data['category_id'] ?? '';
|
||||||
|
if ($categoryId === '' || $categoryId === null) {
|
||||||
|
$categoryId = null;
|
||||||
|
} elseif (!is_scalar($categoryId) || !ctype_digit((string) $categoryId) || (int) $categoryId < 1 || (new CategoriesRepository())->findWithId((int) $categoryId) === null) {
|
||||||
|
throw new InvalidArgumentException('Choose an existing category.');
|
||||||
|
} else {
|
||||||
|
$categoryId = (int) $categoryId;
|
||||||
|
}
|
||||||
|
|
||||||
|
$publishedAt = $this->validatedPublicationDate($data['published_at'] ?? '', $status);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'title' => $title,
|
||||||
|
'slug' => $slug,
|
||||||
|
'excerpt' => $excerpt,
|
||||||
|
'body' => $body,
|
||||||
|
'category_id' => $categoryId,
|
||||||
|
'status' => $status,
|
||||||
|
'published_at' => $publishedAt,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function validatedPublicationDate(mixed $value, string $status): ?string
|
||||||
|
{
|
||||||
|
if ($value === null || $value === '') {
|
||||||
|
return $status === 'published' ? date('Y-m-d H:i:s') : null;
|
||||||
|
}
|
||||||
|
if (!is_string($value)) {
|
||||||
|
throw new InvalidArgumentException('Enter a valid publication date.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$value = trim($value);
|
||||||
|
$format = str_contains($value, 'T') ? 'Y-m-d\\TH:i' : 'Y-m-d H:i:s';
|
||||||
|
$date = DateTimeImmutable::createFromFormat('!' . $format, $value);
|
||||||
|
$errors = DateTimeImmutable::getLastErrors();
|
||||||
|
if ($date === false || ($errors !== false && ($errors['warning_count'] > 0 || $errors['error_count'] > 0)) || $date->format($format) !== $value) {
|
||||||
|
throw new InvalidArgumentException('Enter a valid publication date.');
|
||||||
|
}
|
||||||
|
if ($date > new DateTimeImmutable()) {
|
||||||
|
throw new InvalidArgumentException('Publication dates cannot be in the future.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $date->format('Y-m-d H:i:s');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Plugi\Extensions\Blog\CategoriesRepository;
|
||||||
|
use Plugi\Extensions\Blog\PostsRepository;
|
||||||
|
|
||||||
|
$postsRepository = new PostsRepository();
|
||||||
|
$post = [
|
||||||
|
'title' => '',
|
||||||
|
'slug' => '',
|
||||||
|
'excerpt' => '',
|
||||||
|
'body' => '',
|
||||||
|
'category_id' => null,
|
||||||
|
'status' => 'draft',
|
||||||
|
'published_at' => null,
|
||||||
|
];
|
||||||
|
if (isset($_GET['id']) && ctype_digit((string) $_GET['id'])) {
|
||||||
|
$post = $postsRepository->findWithId($_GET['id']) ?? $post;
|
||||||
|
}
|
||||||
|
$isEditing = isset($post['id']);
|
||||||
|
$publishedAt = $post['published_at'] ? date('Y-m-d\TH:i', strtotime($post['published_at'])) : '';
|
||||||
|
$categories = (new CategoriesRepository())->getAllForAdmin();
|
||||||
|
?>
|
||||||
|
<header class="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'posts']) ?>" class="btn btn-ghost btn-square btn-sm" aria-label="Back to posts" title="Back to posts">
|
||||||
|
<i class="ph-duotone ph-arrow-left text-xl" aria-hidden="true"></i>
|
||||||
|
</a>
|
||||||
|
<div class="space-y-1">
|
||||||
|
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-primary">Blog editor</p>
|
||||||
|
<h2 class="text-xl font-bold tracking-tight"><?= $isEditing ? 'Edit post' : 'New post' ?></h2>
|
||||||
|
<p class="text-sm text-base-content/60">Save as a draft or publish the article.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<form action="/ext--blog/save-post" method="post" class="space-y-6">
|
||||||
|
<?php phpb_csrf_field(); ?>
|
||||||
|
<?php if ($isEditing): ?>
|
||||||
|
<input type="hidden" name="id" value="<?= phpb_e((string) $post['id']) ?>">
|
||||||
|
<?php endif; ?>
|
||||||
|
|
||||||
|
<section class="card border border-base-300 bg-base-100 shadow-sm">
|
||||||
|
<div class="card-body gap-5 p-4 sm:p-6 lg:p-8">
|
||||||
|
<div>
|
||||||
|
<label for="post-title" class="label"><span class="label-text font-medium">Title</span></label>
|
||||||
|
<input id="post-title" type="text" name="title" maxlength="255" required value="<?= phpb_e($post['title']) ?>" class="input w-full">
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="post-slug" class="label"><span class="label-text font-medium">Slug</span></label>
|
||||||
|
<input id="post-slug" type="text" name="slug" maxlength="191" pattern="[a-z0-9]+(-[a-z0-9]+)*" required value="<?= phpb_e($post['slug']) ?>" class="input w-full" aria-describedby="post-slug-help">
|
||||||
|
<p id="post-slug-help" class="mt-1 text-sm text-base-content/60">Use lowercase letters, numbers, and hyphens.</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="post-excerpt" class="label"><span class="label-text font-medium">Excerpt</span></label>
|
||||||
|
<textarea id="post-excerpt" name="excerpt" rows="3" class="textarea w-full"><?= phpb_e($post['excerpt']) ?></textarea>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="post-body" class="label"><span class="label-text font-medium">Body</span></label>
|
||||||
|
<textarea id="post-body" name="body" rows="12" class="textarea w-full" aria-describedby="post-body-help"><?= phpb_e($post['body']) ?></textarea>
|
||||||
|
<p id="post-body-help" class="mt-1 text-sm text-base-content/60">Body content is rendered as escaped plain text on the public page.</p>
|
||||||
|
</div>
|
||||||
|
<div class="grid gap-5 sm:grid-cols-2">
|
||||||
|
<div>
|
||||||
|
<label for="post-category" class="label"><span class="label-text font-medium">Category</span></label>
|
||||||
|
<select id="post-category" name="category_id" class="select w-full">
|
||||||
|
<option value="">No category</option>
|
||||||
|
<?php foreach ($categories as $category): ?>
|
||||||
|
<option value="<?= phpb_e((string) $category['id']) ?>" <?= (string) $category['id'] === (string) $post['category_id'] ? 'selected' : '' ?>><?= phpb_e($category['name']) ?></option>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="post-status" class="label"><span class="label-text font-medium">Status</span></label>
|
||||||
|
<select id="post-status" name="status" class="select w-full">
|
||||||
|
<option value="draft" <?= $post['status'] === 'draft' ? 'selected' : '' ?>>Draft</option>
|
||||||
|
<option value="published" <?= $post['status'] === 'published' ? 'selected' : '' ?>>Published</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="post-published-at" class="label"><span class="label-text font-medium">Publication date</span></label>
|
||||||
|
<input id="post-published-at" type="datetime-local" name="published_at" value="<?= phpb_e($publishedAt) ?>" class="input w-full" aria-describedby="post-published-at-help">
|
||||||
|
<p id="post-published-at-help" class="mt-1 text-sm text-base-content/60">Leave blank to use the current time when publishing. Future dates are not supported.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="flex flex-wrap justify-end gap-3">
|
||||||
|
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'posts']) ?>" class="btn btn-ghost">Cancel</a>
|
||||||
|
<button type="submit" class="btn btn-primary">Save post</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Plugi\Extensions\Blog\CategoriesRepository;
|
||||||
|
|
||||||
|
$categoriesRepository = new CategoriesRepository();
|
||||||
|
$categories = $categoriesRepository->getAllForAdmin();
|
||||||
|
$category = ['name' => '', 'slug' => ''];
|
||||||
|
if (isset($_GET['id']) && ctype_digit((string) $_GET['id'])) {
|
||||||
|
$category = $categoriesRepository->findWithId($_GET['id']) ?? $category;
|
||||||
|
}
|
||||||
|
$isEditing = isset($category['id']);
|
||||||
|
?>
|
||||||
|
<section class="space-y-5">
|
||||||
|
<header class="space-y-1">
|
||||||
|
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-primary">Blog extension</p>
|
||||||
|
<h2 class="text-xl font-bold tracking-tight text-base-content">Categories</h2>
|
||||||
|
<p class="text-sm text-base-content/60">Organize posts with one optional category each.</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<form action="/ext--blog/save-category" method="post" class="card border border-base-300 bg-base-100 shadow-sm">
|
||||||
|
<?php phpb_csrf_field(); ?>
|
||||||
|
<?php if ($isEditing): ?>
|
||||||
|
<input type="hidden" name="id" value="<?= phpb_e((string) $category['id']) ?>">
|
||||||
|
<?php endif; ?>
|
||||||
|
<div class="card-body gap-4 p-4 sm:p-6">
|
||||||
|
<h3 class="card-title text-lg"><?= $isEditing ? 'Edit category' : 'New category' ?></h3>
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2">
|
||||||
|
<div>
|
||||||
|
<label for="category-name" class="label"><span class="label-text font-medium">Name</span></label>
|
||||||
|
<input id="category-name" type="text" name="name" maxlength="255" required value="<?= phpb_e($category['name']) ?>" class="input w-full">
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="category-slug" class="label"><span class="label-text font-medium">Slug</span></label>
|
||||||
|
<input id="category-slug" type="text" name="slug" maxlength="191" pattern="[a-z0-9]+(-[a-z0-9]+)*" required value="<?= phpb_e($category['slug']) ?>" class="input w-full">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-wrap justify-end gap-3">
|
||||||
|
<?php if ($isEditing): ?>
|
||||||
|
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'categories']) ?>" class="btn btn-ghost">Cancel</a>
|
||||||
|
<?php endif; ?>
|
||||||
|
<button type="submit" class="btn btn-primary"><?= $isEditing ? 'Save category' : 'Add category' ?></button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<?php if (empty($categories)): ?>
|
||||||
|
<div class="card border border-dashed border-base-300 bg-base-100 shadow-sm" role="status">
|
||||||
|
<div class="card-body items-center px-5 py-10 text-center">
|
||||||
|
<h3 class="card-title text-lg">No categories yet</h3>
|
||||||
|
<p class="text-sm text-base-content/60">Create a category above to make it available to posts.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<?php else: ?>
|
||||||
|
<div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
|
||||||
|
<table class="table table-zebra w-full min-w-[32rem]">
|
||||||
|
<thead><tr><th>Name</th><th>Slug</th><th class="w-40 text-right">Actions</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
<?php foreach ($categories as $item): ?>
|
||||||
|
<tr>
|
||||||
|
<td><?= phpb_e($item['name']) ?></td>
|
||||||
|
<td><span class="font-mono text-sm"><?= phpb_e($item['slug']) ?></span></td>
|
||||||
|
<td>
|
||||||
|
<div class="flex items-center justify-end gap-1">
|
||||||
|
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'categories', 'id' => $item['id']]) ?>" class="btn btn-ghost btn-square btn-sm" title="Edit category" aria-label="Edit <?= phpb_e($item['name']) ?>">
|
||||||
|
<i class="ph-duotone ph-pencil-line text-lg" aria-hidden="true"></i>
|
||||||
|
</a>
|
||||||
|
<form action="/ext--blog/delete-category" method="post" onsubmit="return confirm('Delete this category? Posts will remain uncategorized.')">
|
||||||
|
<?php phpb_csrf_field(); ?>
|
||||||
|
<input type="hidden" name="id" value="<?= phpb_e((string) $item['id']) ?>">
|
||||||
|
<button type="submit" class="btn btn-ghost btn-square btn-sm text-error" title="Delete category" aria-label="Delete <?= phpb_e($item['name']) ?>">
|
||||||
|
<i class="ph-duotone ph-trash text-lg" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<?php endif; ?>
|
||||||
|
</section>
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Plugi\Extensions\Blog\CategoriesRepository;
|
||||||
|
use Plugi\Extensions\Blog\PostsRepository;
|
||||||
|
|
||||||
|
$posts = (new PostsRepository())->getAllForAdmin();
|
||||||
|
$categories = (new CategoriesRepository())->getAllForAdmin();
|
||||||
|
$categoryNames = [];
|
||||||
|
foreach ($categories as $category) {
|
||||||
|
$categoryNames[$category['id']] = $category['name'];
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
<section class="space-y-5">
|
||||||
|
<header class="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
|
||||||
|
<div class="space-y-1">
|
||||||
|
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-primary">Blog extension</p>
|
||||||
|
<h2 class="text-xl font-bold tracking-tight text-base-content">Posts</h2>
|
||||||
|
<p class="text-sm text-base-content/60"><?= count($posts) ?> post<?= count($posts) !== 1 ? 's' : '' ?></p>
|
||||||
|
</div>
|
||||||
|
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'editPost']) ?>" class="btn btn-primary">
|
||||||
|
<i class="ph-duotone ph-plus" aria-hidden="true"></i>
|
||||||
|
New post
|
||||||
|
</a>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<?php if (empty($posts)): ?>
|
||||||
|
<div class="card border border-dashed border-base-300 bg-base-100 shadow-sm" role="status">
|
||||||
|
<div class="card-body items-center gap-3 px-5 py-12 text-center sm:py-16">
|
||||||
|
<span class="grid size-14 place-items-center rounded-2xl bg-primary/10 text-primary">
|
||||||
|
<i class="text-3xl ph-duotone ph-article" aria-hidden="true"></i>
|
||||||
|
</span>
|
||||||
|
<h3 class="card-title mt-1 text-lg">No posts yet</h3>
|
||||||
|
<p class="max-w-md text-sm leading-relaxed text-base-content/60">Create a draft or publish your first article.</p>
|
||||||
|
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'editPost']) ?>" class="btn btn-primary mt-2">
|
||||||
|
<i class="ph-duotone ph-plus" aria-hidden="true"></i>
|
||||||
|
Create your first post
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<?php else: ?>
|
||||||
|
<div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
|
||||||
|
<table class="table table-zebra w-full min-w-[48rem]">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Title</th>
|
||||||
|
<th>Category</th>
|
||||||
|
<th>Status</th>
|
||||||
|
<th>Published</th>
|
||||||
|
<th class="w-40 text-right">Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<?php foreach ($posts as $post): ?>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<div class="font-medium"><?= phpb_e($post['title']) ?></div>
|
||||||
|
<div class="text-xs text-base-content/60">/<?= phpb_e($post['slug']) ?></div>
|
||||||
|
</td>
|
||||||
|
<td><?= phpb_e($categoryNames[$post['category_id']] ?? '—') ?></td>
|
||||||
|
<td><span class="badge <?= $post['status'] === 'published' ? 'badge-success' : 'badge-warning' ?>"><?= phpb_e(ucfirst($post['status'])) ?></span></td>
|
||||||
|
<td><?= phpb_e($post['published_at'] ?? '—') ?></td>
|
||||||
|
<td>
|
||||||
|
<div class="flex items-center justify-end gap-1">
|
||||||
|
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'editPost', 'id' => $post['id']]) ?>" class="btn btn-ghost btn-square btn-sm" title="Edit post" aria-label="Edit <?= phpb_e($post['title']) ?>">
|
||||||
|
<i class="ph-duotone ph-pencil-line text-lg" aria-hidden="true"></i>
|
||||||
|
</a>
|
||||||
|
<form action="/ext--blog/delete-post" method="post" onsubmit="return confirm('Delete this post?')">
|
||||||
|
<?php phpb_csrf_field(); ?>
|
||||||
|
<input type="hidden" name="id" value="<?= phpb_e((string) $post['id']) ?>">
|
||||||
|
<button type="submit" class="btn btn-ghost btn-square btn-sm text-error" title="Delete post" aria-label="Delete <?= phpb_e($post['title']) ?>">
|
||||||
|
<i class="ph-duotone ph-trash text-lg" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<?php endif; ?>
|
||||||
|
</section>
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
$modules = [
|
||||||
|
'posts' => [
|
||||||
|
'include' => __DIR__ . '/Views/ListPosts.php',
|
||||||
|
'label' => 'Posts',
|
||||||
|
'icon' => 'ph-article',
|
||||||
|
'inMenu' => true,
|
||||||
|
],
|
||||||
|
'categories' => [
|
||||||
|
'include' => __DIR__ . '/Views/ListCategories.php',
|
||||||
|
'label' => 'Categories',
|
||||||
|
'icon' => 'ph-tag',
|
||||||
|
'inMenu' => true,
|
||||||
|
],
|
||||||
|
'editPost' => [
|
||||||
|
'include' => __DIR__ . '/Views/EditPost.php',
|
||||||
|
'inMenu' => false,
|
||||||
|
],
|
||||||
|
];
|
||||||
|
|
||||||
|
$activeModule = isset($_GET['action']) && array_key_exists($_GET['action'], $modules) ? $_GET['action'] : 'posts';
|
||||||
|
|
||||||
|
?>
|
||||||
|
<nav class="mb-6 overflow-x-auto" aria-label="Blog extension navigation">
|
||||||
|
<div class="tabs tabs-box w-max min-w-full bg-base-200/50">
|
||||||
|
<?php foreach ($modules as $name => $module): ?>
|
||||||
|
<?php if (!$module['inMenu']) continue; ?>
|
||||||
|
<a class="tab gap-2 <?= $name === $activeModule ? 'tab-active' : '' ?>" <?= $name === $activeModule ? 'aria-current="page"' : '' ?> href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => $name]) ?>">
|
||||||
|
<i class="ph-duotone <?= phpb_e($module['icon']) ?>" aria-hidden="true"></i>
|
||||||
|
<?= phpb_e($module['label']) ?>
|
||||||
|
</a>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
<div class="w-full">
|
||||||
|
<?php include $modules[$activeModule]['include']; ?>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
'title' => 'Blog Post',
|
||||||
|
'category' => 'Blog',
|
||||||
|
'icon' => 'ph ph-article',
|
||||||
|
'cache' => false,
|
||||||
|
];
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
$slug = phpb_route_parameter('slug');
|
||||||
|
$post = is_string($slug) && $slug !== ''
|
||||||
|
? (new \Plugi\Extensions\Blog\PostsRepository())->findPublishedBySlug($slug)
|
||||||
|
: null;
|
||||||
|
?>
|
||||||
|
<?php if ($post === null): ?>
|
||||||
|
<section class="card border border-base-300 bg-base-100 shadow-sm" aria-labelledby="blog-post-not-found">
|
||||||
|
<div class="card-body">
|
||||||
|
<h1 id="blog-post-not-found" class="card-title">Article not found</h1>
|
||||||
|
<p class="text-base-content/70">This article is unavailable or may no longer be published.</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<?php else: ?>
|
||||||
|
<article class="mx-auto w-full max-w-3xl space-y-8">
|
||||||
|
<header class="space-y-4">
|
||||||
|
<div class="flex flex-wrap items-center gap-3 text-sm text-base-content/60">
|
||||||
|
<?php if (!empty($post['category_name'])): ?>
|
||||||
|
<span class="badge badge-outline"><?= phpb_e($post['category_name']) ?></span>
|
||||||
|
<?php endif; ?>
|
||||||
|
<?php if (!empty($post['published_at'])): ?>
|
||||||
|
<?php $publishedTimestamp = strtotime($post['published_at']); ?>
|
||||||
|
<?php if ($publishedTimestamp !== false): ?>
|
||||||
|
<time datetime="<?= phpb_e(date('c', $publishedTimestamp)) ?>"><?= phpb_e(date('F j, Y', $publishedTimestamp)) ?></time>
|
||||||
|
<?php endif; ?>
|
||||||
|
<?php endif; ?>
|
||||||
|
</div>
|
||||||
|
<h1 class="text-3xl font-bold tracking-tight text-base-content sm:text-4xl"><?= phpb_e($post['title']) ?></h1>
|
||||||
|
<?php if ($post['excerpt'] !== ''): ?>
|
||||||
|
<p class="text-lg leading-relaxed text-base-content/70"><?= phpb_e($post['excerpt']) ?></p>
|
||||||
|
<?php endif; ?>
|
||||||
|
</header>
|
||||||
|
<div class="whitespace-pre-line text-base leading-7 text-base-content"><?= nl2br(phpb_e($post['body'])) ?></div>
|
||||||
|
</article>
|
||||||
|
<?php endif; ?>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
'title' => 'Published Posts',
|
||||||
|
'category' => 'Blog',
|
||||||
|
'icon' => 'ph ph-article',
|
||||||
|
'cache' => false,
|
||||||
|
];
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
$posts = (new \Plugi\Extensions\Blog\PostsRepository())->getPublishedForListing();
|
||||||
|
?>
|
||||||
|
<section class="space-y-6" aria-label="Blog posts">
|
||||||
|
<?php if (empty($posts)): ?>
|
||||||
|
<div class="alert alert-info" role="status">No published posts yet.</div>
|
||||||
|
<?php else: ?>
|
||||||
|
<div class="grid gap-6 md:grid-cols-2">
|
||||||
|
<?php foreach ($posts as $post): ?>
|
||||||
|
<article class="card h-full border border-base-300 bg-base-100 shadow-sm">
|
||||||
|
<div class="card-body gap-4">
|
||||||
|
<div class="flex flex-wrap items-center gap-3 text-sm text-base-content/60">
|
||||||
|
<?php if (!empty($post['category_name'])): ?>
|
||||||
|
<span class="badge badge-outline"><?= phpb_e($post['category_name']) ?></span>
|
||||||
|
<?php endif; ?>
|
||||||
|
<?php if (!empty($post['published_at'])): ?>
|
||||||
|
<?php $publishedTimestamp = strtotime($post['published_at']); ?>
|
||||||
|
<?php if ($publishedTimestamp !== false): ?>
|
||||||
|
<time datetime="<?= phpb_e(date('c', $publishedTimestamp)) ?>"><?= phpb_e(date('F j, Y', $publishedTimestamp)) ?></time>
|
||||||
|
<?php endif; ?>
|
||||||
|
<?php endif; ?>
|
||||||
|
</div>
|
||||||
|
<h2 class="card-title text-xl">
|
||||||
|
<a class="link link-hover" href="<?= phpb_e(phpb_full_url('/blog/' . rawurlencode($post['slug']))) ?>"><?= phpb_e($post['title']) ?></a>
|
||||||
|
</h2>
|
||||||
|
<?php if ($post['excerpt'] !== ''): ?>
|
||||||
|
<p class="whitespace-pre-line text-base-content/80"><?= phpb_e($post['excerpt']) ?></p>
|
||||||
|
<?php endif; ?>
|
||||||
|
<div class="card-actions mt-auto justify-end">
|
||||||
|
<a class="btn btn-ghost btn-sm" href="<?= phpb_e(phpb_full_url('/blog/' . rawurlencode($post['slug']))) ?>">
|
||||||
|
Read article<span class="sr-only">: <?= phpb_e($post['title']) ?></span>
|
||||||
|
<i class="ph ph-arrow-right" aria-hidden="true"></i>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</div>
|
||||||
|
<?php endif; ?>
|
||||||
|
</section>
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
'title' => 'Blog',
|
||||||
|
'author' => 'Paul Spenke',
|
||||||
|
'identifier' => 'blog',
|
||||||
|
'licence' => 'MIT',
|
||||||
|
'version' => '1.0.0',
|
||||||
|
'tables' => [
|
||||||
|
'posts' => [
|
||||||
|
'columns' => [
|
||||||
|
'title' => 'varchar(255) NOT NULL',
|
||||||
|
'slug' => 'varchar(191) NOT NULL',
|
||||||
|
'excerpt' => 'text NOT NULL',
|
||||||
|
'body' => 'longtext NOT NULL',
|
||||||
|
'category_id' => 'int NULL',
|
||||||
|
'status' => "varchar(20) NOT NULL DEFAULT 'draft'",
|
||||||
|
'published_at' => 'datetime NULL',
|
||||||
|
'created_at' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP',
|
||||||
|
'updated_at' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
|
||||||
|
],
|
||||||
|
'uniqueKeys' => [
|
||||||
|
'slug' => ['slug'],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
'categories' => [
|
||||||
|
'columns' => [
|
||||||
|
'name' => 'varchar(255) NOT NULL',
|
||||||
|
'slug' => 'varchar(191) NOT NULL',
|
||||||
|
'created_at' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP',
|
||||||
|
'updated_at' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
|
||||||
|
],
|
||||||
|
'uniqueKeys' => [
|
||||||
|
'slug' => ['slug'],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
];
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Plugi\Extensions;
|
||||||
|
|
||||||
|
Extensions::addRoutes([
|
||||||
|
'/ext--blog/save-post' => __DIR__ . '/routes/savePost.php',
|
||||||
|
'/ext--blog/delete-post' => __DIR__ . '/routes/deletePost.php',
|
||||||
|
'/ext--blog/save-category' => __DIR__ . '/routes/saveCategory.php',
|
||||||
|
'/ext--blog/delete-category' => __DIR__ . '/routes/deleteCategory.php',
|
||||||
|
]);
|
||||||
|
|
||||||
|
Extensions::addBlocks([
|
||||||
|
'post-list' => __DIR__ . '/blocks/post-list',
|
||||||
|
'post-detail' => __DIR__ . '/blocks/post-detail',
|
||||||
|
]);
|
||||||
|
|
||||||
|
Extensions::registerBackend('blog', [
|
||||||
|
'title' => 'Blog',
|
||||||
|
'include' => __DIR__ . '/admin/blog.php',
|
||||||
|
'icon' => '<i class="ph ph-article"></i>',
|
||||||
|
]);
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
phpb_requires_authenticated();
|
||||||
|
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
|
||||||
|
http_response_code(405);
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
if (!phpb_validate_csrf()) {
|
||||||
|
http_response_code(403);
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
|
||||||
|
$deleted = false;
|
||||||
|
try {
|
||||||
|
if (isset($_POST['id']) && is_string($_POST['id']) && ctype_digit($_POST['id']) && (int) $_POST['id'] > 0) {
|
||||||
|
$deleted = (new \Plugi\Extensions\Blog\CategoriesRepository())->destroy((int) $_POST['id']);
|
||||||
|
}
|
||||||
|
} catch (\Throwable) {
|
||||||
|
$deleted = false;
|
||||||
|
}
|
||||||
|
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'categories']), [
|
||||||
|
'message-type' => $deleted ? 'success' : 'error',
|
||||||
|
'message' => $deleted ? 'Category deleted; associated posts are uncategorized.' : 'The category could not be deleted.',
|
||||||
|
]);
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
phpb_requires_authenticated();
|
||||||
|
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
|
||||||
|
http_response_code(405);
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
if (!phpb_validate_csrf()) {
|
||||||
|
http_response_code(403);
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
|
||||||
|
$deleted = false;
|
||||||
|
try {
|
||||||
|
if (isset($_POST['id']) && is_string($_POST['id']) && ctype_digit($_POST['id']) && (int) $_POST['id'] > 0) {
|
||||||
|
$deleted = (new \Plugi\Extensions\Blog\PostsRepository())->destroy((int) $_POST['id']);
|
||||||
|
}
|
||||||
|
} catch (\Throwable) {
|
||||||
|
$deleted = false;
|
||||||
|
}
|
||||||
|
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'posts']), [
|
||||||
|
'message-type' => $deleted ? 'success' : 'error',
|
||||||
|
'message' => $deleted ? 'Post deleted.' : 'The post could not be deleted.',
|
||||||
|
]);
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
phpb_requires_authenticated();
|
||||||
|
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
|
||||||
|
http_response_code(405);
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
if (!phpb_validate_csrf()) {
|
||||||
|
http_response_code(403);
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
|
||||||
|
$categoriesRepository = new \Plugi\Extensions\Blog\CategoriesRepository();
|
||||||
|
$redirectUrl = phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'categories']);
|
||||||
|
$data = array_intersect_key($_POST, array_flip(['name', 'slug']));
|
||||||
|
try {
|
||||||
|
if (isset($_POST['id']) && is_string($_POST['id']) && ctype_digit($_POST['id']) && (int) $_POST['id'] > 0) {
|
||||||
|
$saved = $categoriesRepository->update(['id' => (int) $_POST['id']], $data);
|
||||||
|
} elseif (!isset($_POST['id'])) {
|
||||||
|
$saved = $categoriesRepository->create($data);
|
||||||
|
} else {
|
||||||
|
$saved = false;
|
||||||
|
}
|
||||||
|
$message = $saved ? ['message-type' => 'success', 'message' => 'Category saved.'] : ['message-type' => 'error', 'message' => 'The category could not be saved.'];
|
||||||
|
} catch (\InvalidArgumentException $exception) {
|
||||||
|
$message = ['message-type' => 'error', 'message' => $exception->getMessage()];
|
||||||
|
} catch (\Throwable) {
|
||||||
|
$message = ['message-type' => 'error', 'message' => 'The category could not be saved. Check that the slug is unique.'];
|
||||||
|
}
|
||||||
|
phpb_redirect($redirectUrl, $message);
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
phpb_requires_authenticated();
|
||||||
|
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
|
||||||
|
http_response_code(405);
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
if (!phpb_validate_csrf()) {
|
||||||
|
http_response_code(403);
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
|
||||||
|
$postsRepository = new \Plugi\Extensions\Blog\PostsRepository();
|
||||||
|
$redirectUrl = phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'posts']);
|
||||||
|
$fields = ['title', 'slug', 'excerpt', 'body', 'category_id', 'status', 'published_at'];
|
||||||
|
$data = array_intersect_key($_POST, array_flip($fields));
|
||||||
|
try {
|
||||||
|
if (isset($_POST['id']) && is_string($_POST['id']) && ctype_digit($_POST['id']) && (int) $_POST['id'] > 0) {
|
||||||
|
$saved = $postsRepository->update(['id' => (int) $_POST['id']], $data);
|
||||||
|
} elseif (!isset($_POST['id'])) {
|
||||||
|
$saved = $postsRepository->create($data);
|
||||||
|
} else {
|
||||||
|
$saved = false;
|
||||||
|
}
|
||||||
|
$message = $saved ? ['message-type' => 'success', 'message' => 'Post saved.'] : ['message-type' => 'error', 'message' => 'The post could not be saved.'];
|
||||||
|
} catch (\InvalidArgumentException $exception) {
|
||||||
|
$message = ['message-type' => 'error', 'message' => $exception->getMessage()];
|
||||||
|
} catch (\Throwable) {
|
||||||
|
$message = ['message-type' => 'error', 'message' => 'The post could not be saved. Check that the slug is unique.'];
|
||||||
|
}
|
||||||
|
phpb_redirect($redirectUrl, $message);
|
||||||
@@ -0,0 +1,239 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Plugi\Core\DB;
|
||||||
|
use Plugi\Extensions\Blog\CategoriesRepository;
|
||||||
|
use Plugi\Extensions\Blog\PostsRepository;
|
||||||
|
|
||||||
|
require_once dirname(__DIR__, 3) . '/plugi-core/src/Extensions.php';
|
||||||
|
require_once dirname(__DIR__, 3) . '/plugi-core/src/Core/DB.php';
|
||||||
|
require_once dirname(__DIR__, 3) . '/plugi-core/src/Core/helpers.php';
|
||||||
|
require_once dirname(__DIR__, 3) . '/plugi-core/src/Repositories/BaseRepository.php';
|
||||||
|
require_once dirname(__DIR__, 3) . '/plugi-core/src/Contracts/PageContract.php';
|
||||||
|
require_once dirname(__DIR__, 3) . '/plugi-core/src/Contracts/ThemeContract.php';
|
||||||
|
require_once dirname(__DIR__, 3) . '/plugi-core/src/Page.php';
|
||||||
|
require_once dirname(__DIR__, 3) . '/plugi-core/src/Modules/GrapesJS/PageRenderer.php';
|
||||||
|
require_once dirname(__DIR__, 3) . '/plugi-core/src/Modules/GrapesJS/Block/BaseModel.php';
|
||||||
|
require_once dirname(__DIR__, 3) . '/plugi-core/src/Modules/GrapesJS/Block/BaseController.php';
|
||||||
|
require_once dirname(__DIR__, 3) . '/plugi-core/src/ThemeBlock.php';
|
||||||
|
require_once dirname(__DIR__, 3) . '/plugi-core/src/Modules/GrapesJS/Block/BlockRenderer.php';
|
||||||
|
require_once dirname(__DIR__) . '/admin/Classes/PostsRepository.php';
|
||||||
|
require_once dirname(__DIR__) . '/admin/Classes/CategoriesRepository.php';
|
||||||
|
|
||||||
|
$blogConfig = require dirname(__DIR__) . '/config.php';
|
||||||
|
\Plugi\Extensions::registerConfig('blog', $blogConfig);
|
||||||
|
require_once dirname(__DIR__) . '/extension.php';
|
||||||
|
|
||||||
|
class BlogTestDatabase extends DB
|
||||||
|
{
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
$this->pdo = new PDO('sqlite::memory:');
|
||||||
|
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||||
|
$this->databaseName = 'blog_test';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function createSchema(): void
|
||||||
|
{
|
||||||
|
$this->query('CREATE TABLE test_ext__blog_posts (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
title VARCHAR(255) NOT NULL,
|
||||||
|
slug VARCHAR(191) NOT NULL UNIQUE,
|
||||||
|
excerpt TEXT NOT NULL,
|
||||||
|
body TEXT NOT NULL,
|
||||||
|
category_id INTEGER NULL,
|
||||||
|
status VARCHAR(20) NOT NULL,
|
||||||
|
published_at DATETIME NULL,
|
||||||
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)');
|
||||||
|
$this->query('CREATE TABLE test_ext__blog_categories (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
slug VARCHAR(191) NOT NULL UNIQUE,
|
||||||
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class BlogTestTheme implements \Plugi\Contracts\ThemeContract
|
||||||
|
{
|
||||||
|
public function getThemeBlocks()
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getThemeLayouts()
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getFolder()
|
||||||
|
{
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertBlog(bool $condition, string $message): void
|
||||||
|
{
|
||||||
|
if (!$condition) {
|
||||||
|
throw new RuntimeException($message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function expectBlogValidation(callable $callback, string $message): void
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$callback();
|
||||||
|
} catch (InvalidArgumentException) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new RuntimeException($message);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderBlogBlock(string $slug): string
|
||||||
|
{
|
||||||
|
$theme = new BlogTestTheme();
|
||||||
|
$page = new \Plugi\Page();
|
||||||
|
$themeBlock = new \Plugi\ThemeBlock($theme, \Plugi\Extensions::getBlock($slug), true, $slug);
|
||||||
|
return (new \Plugi\Modules\GrapesJS\Block\BlockRenderer($theme, $page))->render($themeBlock);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderBlogListing(): string
|
||||||
|
{
|
||||||
|
return renderBlogBlock('post-list');
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderBlogDetail(?string $slug): string
|
||||||
|
{
|
||||||
|
$GLOBALS['phpb_route_parameters'] = $slug === null ? [] : ['slug' => $slug];
|
||||||
|
return renderBlogBlock('post-detail');
|
||||||
|
}
|
||||||
|
|
||||||
|
$_ENV['DATABASE_PREFIX'] = 'test_';
|
||||||
|
$phpb_db = new BlogTestDatabase();
|
||||||
|
$phpb_db->createSchema();
|
||||||
|
assertBlog(isset($phpb_db->getDBDefinition()['ext__blog_posts'], $phpb_db->getDBDefinition()['ext__blog_categories']), 'The blog tables should be included in the core database definition.');
|
||||||
|
assertBlog(isset(\Plugi\Extensions::getBackends()['ext--blog']), 'The blog admin backend should be registered.');
|
||||||
|
assertBlog(count(array_intersect(['/ext--blog/save-post', '/ext--blog/delete-post', '/ext--blog/save-category', '/ext--blog/delete-category'], array_keys(\Plugi\Extensions::getRoutes()))) === 4, 'Blog CRUD routes should be registered.');
|
||||||
|
assertBlog(\Plugi\Extensions::getBlock('post-list') === dirname(__DIR__) . '/blocks/post-list', 'The published-post block should be registered.');
|
||||||
|
assertBlog((require dirname(__DIR__) . '/blocks/post-list/config.php')['cache'] === false, 'The listing block should avoid stale cached post data.');
|
||||||
|
assertBlog(\Plugi\Extensions::getBlock('post-detail') === dirname(__DIR__) . '/blocks/post-detail', 'The post-detail block should be registered.');
|
||||||
|
assertBlog((require dirname(__DIR__) . '/blocks/post-detail/config.php')['cache'] === false, 'The detail block should avoid stale route-specific output.');
|
||||||
|
$posts = new PostsRepository();
|
||||||
|
$categories = new CategoriesRepository();
|
||||||
|
$category = $categories->create(['name' => 'News', 'slug' => 'news']);
|
||||||
|
assertBlog(is_array($category) && (int) $category['id'] > 0, 'Category creation should return the new category.');
|
||||||
|
|
||||||
|
$post = $posts->create([
|
||||||
|
'title' => 'First post',
|
||||||
|
'slug' => 'first-post',
|
||||||
|
'excerpt' => 'A short summary',
|
||||||
|
'body' => 'Post body',
|
||||||
|
'category_id' => $category['id'],
|
||||||
|
'status' => 'published',
|
||||||
|
'published_at' => '',
|
||||||
|
]);
|
||||||
|
assertBlog(is_array($post) && $post['status'] === 'published', 'A valid published post should be created.');
|
||||||
|
assertBlog($post['published_at'] !== null, 'Publishing without a date should set the current publication timestamp.');
|
||||||
|
|
||||||
|
$olderPost = $posts->create([
|
||||||
|
'title' => 'Older published post',
|
||||||
|
'slug' => 'older-published-post',
|
||||||
|
'excerpt' => 'Older excerpt',
|
||||||
|
'body' => '<script>alert("x")</script>&safe',
|
||||||
|
'category_id' => '',
|
||||||
|
'status' => 'published',
|
||||||
|
'published_at' => '2020-01-01T00:00',
|
||||||
|
]);
|
||||||
|
$pastPublication = date('Y-m-d\\TH:i', time() - 3600);
|
||||||
|
$datedPost = $posts->create([
|
||||||
|
'title' => 'Dated draft',
|
||||||
|
'slug' => 'dated-draft',
|
||||||
|
'excerpt' => '',
|
||||||
|
'body' => " Draft body\n",
|
||||||
|
'category_id' => '',
|
||||||
|
'status' => 'draft',
|
||||||
|
'published_at' => $pastPublication,
|
||||||
|
]);
|
||||||
|
$secondPost = $posts->create([
|
||||||
|
'title' => 'Second post',
|
||||||
|
'slug' => 'second-post',
|
||||||
|
'excerpt' => '',
|
||||||
|
'body' => '',
|
||||||
|
'category_id' => $category['id'],
|
||||||
|
'status' => 'draft',
|
||||||
|
'published_at' => '',
|
||||||
|
]);
|
||||||
|
$publishedPosts = $posts->getPublishedForListing();
|
||||||
|
assertBlog(count($publishedPosts) === 2, 'The public listing should exclude drafts.');
|
||||||
|
assertBlog($publishedPosts[0]['slug'] === $post['slug'] && $publishedPosts[0]['category_name'] === 'News', 'Published posts should be newest first and include their category name.');
|
||||||
|
assertBlog($publishedPosts[1]['slug'] === $olderPost['slug'], 'Older published posts should follow newer posts.');
|
||||||
|
|
||||||
|
$_ENV['BASE_URL'] = 'https://blog.example';
|
||||||
|
$listingHtml = renderBlogListing();
|
||||||
|
assertBlog(str_contains($listingHtml, 'href="https://blog.example/blog/first-post"'), 'The listing should link to the configured post detail URL.');
|
||||||
|
assertBlog(strpos($listingHtml, 'first-post') < strpos($listingHtml, 'older-published-post'), 'The rendered listing should preserve newest-first order.');
|
||||||
|
assertBlog(!str_contains($listingHtml, 'dated-draft') && !str_contains($listingHtml, 'second-post'), 'Draft posts should not appear in the rendered listing.');
|
||||||
|
$detailHtml = renderBlogDetail('older-published-post');
|
||||||
|
assertBlog(str_contains($detailHtml, '<h1 class="text-3xl font-bold tracking-tight text-base-content sm:text-4xl">Older published post</h1>'), 'The detail block should resolve a published post from the named slug route parameter.');
|
||||||
|
assertBlog(str_contains($detailHtml, '<script>alert("x")</script>&safe') && !str_contains($detailHtml, '<script>alert'), 'The detail block should safely escape post bodies.');
|
||||||
|
assertBlog(str_contains(renderBlogDetail(null), 'Article not found'), 'A missing route slug should render a not-found state.');
|
||||||
|
assertBlog(str_contains(renderBlogDetail('unknown-post'), 'Article not found'), 'An unknown route slug should render a not-found state.');
|
||||||
|
assertBlog(str_contains(renderBlogDetail('dated-draft'), 'Article not found'), 'An unpublished post should render a not-found state.');
|
||||||
|
assertBlog(str_contains(renderBlogDetail('second-post'), 'Article not found'), 'A draft post should render a not-found state.');
|
||||||
|
|
||||||
|
assertBlog($datedPost['published_at'] === str_replace('T', ' ', $pastPublication) . ':00', 'A valid local publication date should be normalized for storage.');
|
||||||
|
assertBlog($datedPost['body'] === " Draft body\n", 'Post body whitespace should be preserved.');
|
||||||
|
expectBlogValidation(fn() => $posts->create([
|
||||||
|
'title' => 'Invalid date', 'slug' => 'invalid-date', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => 'not-a-date',
|
||||||
|
]), 'Invalid publication dates should be rejected.');
|
||||||
|
expectBlogValidation(fn() => $posts->create([
|
||||||
|
'title' => 'Future date', 'slug' => 'future-date', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => date('Y-m-d\\TH:i', time() + 86400),
|
||||||
|
]), 'Future publication dates should be rejected.');
|
||||||
|
|
||||||
|
$updated = $posts->update(['id' => $post['id']], [
|
||||||
|
'title' => 'Updated post',
|
||||||
|
'slug' => 'updated-post',
|
||||||
|
'excerpt' => '',
|
||||||
|
'body' => 'Updated body',
|
||||||
|
'category_id' => '',
|
||||||
|
'status' => 'draft',
|
||||||
|
'published_at' => '',
|
||||||
|
]);
|
||||||
|
assertBlog($updated === true, 'An existing post should update.');
|
||||||
|
$updatedPost = $posts->findWithId($post['id']);
|
||||||
|
assertBlog($updatedPost['title'] === 'Updated post' && $updatedPost['category_id'] === null && $updatedPost['published_at'] === null, 'Post updates should persist edited fields and clear optional values.');
|
||||||
|
|
||||||
|
assertBlog(is_array($secondPost), 'A draft with an empty body should be saved.');
|
||||||
|
|
||||||
|
expectBlogValidation(fn() => $posts->create([
|
||||||
|
'title' => 'Duplicate post', 'slug' => 'second-post', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => '',
|
||||||
|
]), 'Duplicate post slugs should be rejected.');
|
||||||
|
expectBlogValidation(fn() => $posts->create([
|
||||||
|
'title' => 'Bad slug', 'slug' => 'Invalid Slug', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => '',
|
||||||
|
]), 'Invalid post slugs should be rejected.');
|
||||||
|
expectBlogValidation(fn() => $posts->create([
|
||||||
|
'title' => 'Bad status', 'slug' => 'bad-status', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'scheduled', 'published_at' => '',
|
||||||
|
]), 'Unsupported post statuses should be rejected.');
|
||||||
|
expectBlogValidation(fn() => $posts->create([
|
||||||
|
'title' => 'Missing category', 'slug' => 'missing-category', 'excerpt' => '', 'body' => '', 'category_id' => '999', 'status' => 'draft', 'published_at' => '',
|
||||||
|
]), 'Unknown categories should be rejected.');
|
||||||
|
expectBlogValidation(fn() => $posts->create([
|
||||||
|
'title' => 'No body', 'slug' => 'no-body', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'published', 'published_at' => '',
|
||||||
|
]), 'Published posts should require body content.');
|
||||||
|
|
||||||
|
expectBlogValidation(fn() => $categories->create(['name' => 'Duplicate', 'slug' => 'news']), 'Duplicate category slugs should be rejected.');
|
||||||
|
expectBlogValidation(fn() => $categories->create(['name' => 'Bad slug', 'slug' => 'not a slug']), 'Invalid category slugs should be rejected.');
|
||||||
|
$updatedCategory = $categories->update(['id' => $category['id']], ['name' => 'Announcements', 'slug' => 'announcements']);
|
||||||
|
assertBlog($updatedCategory === true, 'An existing category should update.');
|
||||||
|
|
||||||
|
assertBlog($categories->destroy($category['id']) === true, 'A category should be deleted.');
|
||||||
|
assertBlog($posts->findWithId($secondPost['id'])['category_id'] === null, 'Deleting a category should detach its posts.');
|
||||||
|
assertBlog($posts->destroy($secondPost['id']) === true, 'A post should be deleted.');
|
||||||
|
assertBlog($posts->destroy($datedPost['id']) === true, 'A dated post should be deleted.');
|
||||||
|
assertBlog($posts->destroy($olderPost['id']) === true, 'An older published post should be deleted.');
|
||||||
|
assertBlog($categories->findWithId($category['id']) === null && $posts->findWithId($secondPost['id']) === null, 'Deleted records should no longer be found.');
|
||||||
|
assertBlog(str_contains(renderBlogListing(), 'No published posts yet.'), 'The listing should show an empty state when no posts are published.');
|
||||||
|
|
||||||
|
fwrite(STDOUT, "Blog repository tests passed.\n");
|
||||||
Reference in New Issue
Block a user