feat(ext-blog): Add Markdown support and featured images to Plugi Blog Extension

Updated README.md to document Markdown rendering and image authoring capabilities. Added PostContentRenderer class for safe Markdown parsing with XSS protection. Updated PostsRepository to fetch and resolve featured image data from the uploads table. Added UI controls in EditPost.php for selecting images and inserting inline Markdown. Updated views to display featured images on post cards and detail pages.
This commit is contained in:
2026-12-02 10:20:36 +00:00
parent 32582e9279
commit e97d96c1f5
9 changed files with 336 additions and 17 deletions
+9 -3
View File
@@ -1,11 +1,11 @@
# 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.
The blog extension provides Website Manager post and category management plus two page-builder blocks. Posts are single-language; post bodies are stored as Markdown and rendered safely on request.
## 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.
2. Open Website Manager and apply the pending database definition update. Existing installations need this update to create or update the extension-owned post and category tables, including the optional featured-image field.
3. Add categories if useful, then create posts as drafts or publish them from the Blog section.
## Create the public pages
@@ -16,4 +16,10 @@ The blog extension provides Website Manager post and category management plus tw
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.
Keep `/blog` and `/blog/{slug}` unique among the site’s page routes.
## Authoring content and images
Write post bodies in Markdown. The detail page supports headings, paragraphs and line breaks, bold and italic text, inline code, links, and ordered or unordered lists. Raw HTML is displayed as text; links only render with relative URLs or `http`, `https`, and `mailto` schemes.
Choose a featured image from the existing Website Manager media library to show it on post cards and detail pages. Use the editor’s inline-image selector to insert Markdown image syntax at the body cursor; image alt text comes from the selected media item. Inline images render only with relative, `http`, or `https` sources. Unsafe link and image protocols are not rendered.
@@ -0,0 +1,131 @@
<?php
namespace Plugi\Extensions\Blog;
class PostContentRenderer
{
// shortcut: supports basic Markdown blocks and inline syntax; use a maintained parser if authors need advanced Markdown.
public function render(string $markdown): string
{
$blocks = [];
$paragraph = [];
$listType = null;
$listItems = [];
$flush = function () use (&$blocks, &$paragraph, &$listType, &$listItems): void {
if ($paragraph !== []) {
$blocks[] = '<p>' . nl2br($this->renderInline(implode("\n", $paragraph))) . '</p>';
$paragraph = [];
}
if ($listType !== null) {
$class = $listType === 'ul' ? 'list-disc' : 'list-decimal';
$items = array_map(fn(string $item): string => '<li>' . $this->renderInline($item) . '</li>', $listItems);
$blocks[] = '<' . $listType . ' class="' . $class . ' space-y-1 pl-6">' . implode('', $items) . '</' . $listType . '>';
$listType = null;
$listItems = [];
}
};
foreach (preg_split('/\R/', $markdown) ?: [] as $line) {
if (trim($line) === '') {
$flush();
continue;
}
if (preg_match('/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*#*[ \t]*$/', $line, $matches)) {
$flush();
$level = strlen($matches[1]);
$class = [
1 => 'text-3xl font-bold tracking-tight',
2 => 'text-2xl font-bold tracking-tight',
3 => 'text-xl font-semibold',
4 => 'text-lg font-semibold',
5 => 'text-base font-semibold',
6 => 'text-sm font-semibold',
][$level];
$blocks[] = '<h' . $level . ' class="' . $class . '">' . $this->renderInline($matches[2]) . '</h' . $level . '>';
continue;
}
if (preg_match('/^ {0,3}[-*+]\s+(.+)$/', $line, $matches)) {
$type = 'ul';
} elseif (preg_match('/^ {0,3}\d+[.)]\s+(.+)$/', $line, $matches)) {
$type = 'ol';
} else {
if ($listType !== null) {
$flush();
}
$paragraph[] = $line;
continue;
}
if ($paragraph !== []) {
$flush();
} elseif ($listType !== null && $listType !== $type) {
$flush();
}
$listType = $type;
$listItems[] = $matches[1];
}
$flush();
return implode("\n", $blocks);
}
private function renderInline(string $text): string
{
$parts = preg_split('/(`[^`\r\n]+`|!\[[^\]\r\n]*\]\([^\s)\r\n]+\)|\[[^\]\r\n]+\]\([^\s)\r\n]+\)|\*\*[^*\r\n]+\*\*|__[^_\r\n]+__|\*[^*\r\n]+\*|_[^_\r\n]+_)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE) ?: [$text];
$html = '';
foreach ($parts as $part) {
if ($part === '') {
continue;
}
if ($part[0] === '`') {
$html .= '<code>' . $this->escape(substr($part, 1, -1)) . '</code>';
} elseif (preg_match('/^!\[([^\]]*)\]\(([^)]+)\)$/', $part, $matches)) {
$altText = html_entity_decode($matches[1], ENT_QUOTES | ENT_HTML5, 'UTF-8');
$html .= $this->isSafeImageUrl($matches[2])
? '<img src="' . $this->escape($matches[2]) . '" alt="' . $this->escape($altText) . '" class="max-w-full rounded-box">'
: $this->escape($altText);
} elseif (preg_match('/^\[([^\]]+)\]\(([^)]+)\)$/', $part, $matches)) {
$html .= $this->isSafeLink($matches[2])
? '<a class="link link-hover" href="' . $this->escape($matches[2]) . '">' . $this->renderInline($matches[1]) . '</a>'
: $this->renderInline($matches[1]);
} elseif (str_starts_with($part, '**') || str_starts_with($part, '__')) {
$html .= '<strong>' . $this->renderInline(substr($part, 2, -2)) . '</strong>';
} elseif ($part[0] === '*' || $part[0] === '_') {
$html .= '<em>' . $this->renderInline(substr($part, 1, -1)) . '</em>';
} else {
$html .= $this->escape($part);
}
}
return $html;
}
private function isSafeLink(string $url): bool
{
return $this->isSafeUrl($url, ['http', 'https', 'mailto']);
}
private function isSafeImageUrl(string $url): bool
{
return $this->isSafeUrl($url, ['http', 'https']);
}
private function isSafeUrl(string $url, array $allowedSchemes): bool
{
$decodedUrl = html_entity_decode($url, ENT_QUOTES | ENT_HTML5, 'UTF-8');
if ($decodedUrl === '' || preg_match('/[\x00-\x20\x7f]/', $decodedUrl)) {
return false;
}
if (preg_match('/^([a-z][a-z0-9+.-]*):/i', $decodedUrl, $matches)) {
return in_array(strtolower($matches[1]), $allowedSchemes, true);
}
return true;
}
private function escape(string $text): string
{
return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
}
@@ -35,10 +35,12 @@ class PostsRepository extends BaseRepository
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",
$uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads';
$posts = $this->db->select(
"SELECT posts.*, categories.name AS category_name, featured_image.public_id AS featured_image_public_id, featured_image.original_file AS featured_image_original_file, featured_image.alt_text AS featured_image_alt_text FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id LEFT JOIN {$uploadsTable} featured_image ON featured_image.public_id = posts.featured_image_id AND LOWER(featured_image.mime_type) LIKE 'image/%' WHERE posts.status = ? ORDER BY posts.published_at DESC, posts.id DESC",
['published']
);
return array_map(fn(array $post): array => $this->resolveFeaturedImage($post), $posts);
}
public function getPageForAdmin(string $search, int $page): array
@@ -54,8 +56,9 @@ class PostsRepository extends BaseRepository
private function getPostPage(string $search, int $page, bool $publishedOnly): array
{
$categoriesTable = $_ENV['DATABASE_PREFIX'] . 'ext__blog_categories';
$uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads';
$from = $publishedOnly
? "FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id"
? "FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id LEFT JOIN {$uploadsTable} featured_image ON featured_image.public_id = posts.featured_image_id AND LOWER(featured_image.mime_type) LIKE 'image/%'"
: "FROM {$this->table} posts";
$filters = [];
$parameters = [];
@@ -75,13 +78,16 @@ class PostsRepository extends BaseRepository
$page = min(max(1, $page), max(1, (int) ceil((int) $total / self::POSTS_PER_PAGE)));
$offset = ($page - 1) * self::POSTS_PER_PAGE;
$select = $publishedOnly
? 'SELECT posts.*, categories.name AS category_name'
? 'SELECT posts.*, categories.name AS category_name, featured_image.public_id AS featured_image_public_id, featured_image.original_file AS featured_image_original_file, featured_image.alt_text AS featured_image_alt_text'
: 'SELECT posts.*';
$order = $publishedOnly ? 'posts.published_at DESC, posts.id DESC' : 'posts.updated_at DESC, posts.id DESC';
$posts = $this->db->select(
"{$select} {$from}{$where} ORDER BY {$order} LIMIT " . self::POSTS_PER_PAGE . " OFFSET {$offset}",
$parameters
);
if ($publishedOnly) {
$posts = array_map(fn(array $post): array => $this->resolveFeaturedImage($post), $posts);
}
return ['posts' => $posts, 'total' => (int) $total];
}
@@ -89,12 +95,13 @@ class PostsRepository extends BaseRepository
public function findPublishedBySlug(string $slug): ?array
{
$categoriesTable = $_ENV['DATABASE_PREFIX'] . 'ext__blog_categories';
$uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads';
$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",
"SELECT posts.*, categories.name AS category_name, featured_image.public_id AS featured_image_public_id, featured_image.original_file AS featured_image_original_file, featured_image.alt_text AS featured_image_alt_text FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id LEFT JOIN {$uploadsTable} featured_image ON featured_image.public_id = posts.featured_image_id AND LOWER(featured_image.mime_type) LIKE 'image/%' WHERE posts.slug = ? AND posts.status = ? LIMIT 1",
[$slug, 'published']
);
return $posts[0] ?? null;
return isset($posts[0]) ? $this->resolveFeaturedImage($posts[0]) : null;
}
public function clearCategory(int $categoryId): bool
@@ -137,6 +144,23 @@ class PostsRepository extends BaseRepository
$categoryId = (int) $categoryId;
}
$featuredImageId = $data['featured_image_id'] ?? '';
if ($featuredImageId === '' || $featuredImageId === null) {
$featuredImageId = null;
} elseif (!is_string($featuredImageId) || strlen($featuredImageId) > 50) {
throw new InvalidArgumentException('Choose an existing image upload.');
} else {
$uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads';
$images = $this->db->select(
"SELECT public_id FROM {$uploadsTable} WHERE public_id = ? AND LOWER(mime_type) LIKE 'image/%' LIMIT 1",
[$featuredImageId]
);
if ($images === []) {
throw new InvalidArgumentException('Choose an existing image upload.');
}
$featuredImageId = $images[0]['public_id'];
}
$publishedAt = $this->validatedPublicationDate($data['published_at'] ?? '', $status);
return [
@@ -144,12 +168,30 @@ class PostsRepository extends BaseRepository
'slug' => $slug,
'excerpt' => $excerpt,
'body' => $body,
'featured_image_id' => $featuredImageId,
'category_id' => $categoryId,
'status' => $status,
'published_at' => $publishedAt,
];
}
private function resolveFeaturedImage(array $post): array
{
$publicId = $post['featured_image_public_id'] ?? null;
$originalFile = $post['featured_image_original_file'] ?? null;
if (is_string($publicId) && $publicId !== '' && is_string($originalFile) && $originalFile !== '') {
$image = new \Plugi\UploadedFile();
$image->public_id = $publicId;
$image->original_file = $originalFile;
$post['featured_image_url'] = $image->getUrl();
} else {
$post['featured_image_url'] = null;
$post['featured_image_alt_text'] = null;
}
unset($post['featured_image_public_id'], $post['featured_image_original_file']);
return $post;
}
private function validatedPublicationDate(mixed $value, string $status): ?string
{
if ($value === null || $value === '') {
@@ -2,6 +2,7 @@
use Plugi\Extensions\Blog\CategoriesRepository;
use Plugi\Extensions\Blog\PostsRepository;
use Plugi\Repositories\UploadRepository;
$postsRepository = new PostsRepository();
$post = [
@@ -9,6 +10,7 @@ $post = [
'slug' => '',
'excerpt' => '',
'body' => '',
'featured_image_id' => null,
'category_id' => null,
'status' => 'draft',
'published_at' => null,
@@ -19,6 +21,7 @@ if (isset($_GET['id']) && ctype_digit((string) $_GET['id'])) {
$isEditing = isset($post['id']);
$publishedAt = $post['published_at'] ? date('Y-m-d\TH:i', strtotime($post['published_at'])) : '';
$categories = (new CategoriesRepository())->getAllForAdmin();
$imageUploads = array_values(array_filter((new UploadRepository())->getAll(), static fn($file): bool => is_string($file->mime_type ?? null) && str_starts_with(strtolower($file->mime_type), 'image/')));
?>
<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">
@@ -57,7 +60,36 @@ $categories = (new CategoriesRepository())->getAllForAdmin();
<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>
<p id="post-body-help" class="mt-1 text-sm text-base-content/60">Use Markdown for headings, links, lists, and emphasis.</p>
<div class="mt-3 flex flex-col gap-3 sm:flex-row sm:items-end">
<div class="w-full sm:flex-1">
<label for="post-inline-image" class="label"><span class="label-text font-medium">Insert inline image</span></label>
<select id="post-inline-image" class="select w-full" aria-describedby="post-inline-image-help">
<option value="">Choose an image</option>
<?php foreach ($imageUploads as $file): ?>
<?php
$inlineImageUrl = $file->getUrl();
if ($file->original_file !== '') {
$inlineImageUrl = substr($inlineImageUrl, 0, -strlen($file->original_file)) . rawurlencode($file->original_file);
}
?>
<option value="<?= phpb_e($file->public_id) ?>" data-url="<?= phpb_e($inlineImageUrl) ?>" data-alt="<?= phpb_e($file->alt_text ?? '') ?>"><?= phpb_e($file->original_file) ?></option>
<?php endforeach; ?>
</select>
</div>
<button type="button" id="insert-post-inline-image" class="btn btn-outline" aria-label="Insert selected image at the cursor">Insert image</button>
</div>
<p id="post-inline-image-help" class="mt-1 text-sm text-base-content/60">Alt text comes from the media library; the image Markdown is inserted at the cursor.</p>
</div>
<div>
<label for="post-featured-image" class="label"><span class="label-text font-medium">Featured image</span></label>
<select id="post-featured-image" name="featured_image_id" class="select w-full" aria-describedby="post-featured-image-help">
<option value="">No featured image</option>
<?php foreach ($imageUploads as $file): ?>
<option value="<?= phpb_e($file->public_id) ?>" <?= (string) $file->public_id === (string) ($post['featured_image_id'] ?? '') ? 'selected' : '' ?>><?= phpb_e($file->original_file) ?></option>
<?php endforeach; ?>
</select>
<p id="post-featured-image-help" class="mt-1 text-sm text-base-content/60">Choose an image from the existing media library.</p>
</div>
<div class="grid gap-5 sm:grid-cols-2">
<div>
@@ -89,4 +121,32 @@ $categories = (new CategoriesRepository())->getAllForAdmin();
<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>
</form>
<script>
(function () {
const body = document.getElementById('post-body');
const imageSelect = document.getElementById('post-inline-image');
const insertButton = document.getElementById('insert-post-inline-image');
if (!body || !imageSelect || !insertButton) {
return;
}
insertButton.addEventListener('click', function () {
const option = imageSelect.selectedOptions[0];
if (!option || !option.value) {
return;
}
const altText = option.dataset.alt || option.textContent.trim();
const markdownAlt = altText.replace(/[\r\n]+/g, ' ').replace(/&/g, '&amp;').replace(/\[/g, '&#91;').replace(/\]/g, '&#93;');
const markdown = `![${markdownAlt}](${option.dataset.url})`;
const start = body.selectionStart;
const end = body.selectionEnd;
const prefix = start > 0 && !/\s/.test(body.value[start - 1]) ? ' ' : '';
const suffix = end < body.value.length && !/\s/.test(body.value[end]) ? ' ' : '';
body.setRangeText(prefix + markdown + suffix, start, end, 'end');
body.focus();
});
})();
</script>
@@ -31,6 +31,12 @@ $post = is_string($slug) && $slug !== ''
<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>
<?php if (!empty($post['featured_image_url'])): ?>
<?php $featuredImageAlt = trim((string) ($post['featured_image_alt_text'] ?? '')) ?: $post['title']; ?>
<figure class="overflow-hidden rounded-box">
<img src="<?= phpb_e($post['featured_image_url']) ?>" alt="<?= phpb_e($featuredImageAlt) ?>" class="max-h-[32rem] w-full object-cover">
</figure>
<?php endif; ?>
<div class="space-y-4 text-base leading-7 text-base-content"><?= (new \Plugi\Extensions\Blog\PostContentRenderer())->render($post['body']) ?></div>
</article>
<?php endif; ?>
@@ -31,6 +31,12 @@ $searchParameters = $search === '' ? [] : ['q' => $search];
<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">
<?php if (!empty($post['featured_image_url'])): ?>
<?php $featuredImageAlt = trim((string) ($post['featured_image_alt_text'] ?? '')) ?: $post['title']; ?>
<figure class="px-6 pt-6">
<img src="<?= phpb_e($post['featured_image_url']) ?>" alt="<?= phpb_e($featuredImageAlt) ?>" class="aspect-video w-full rounded-box object-cover">
</figure>
<?php endif; ?>
<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'])): ?>
+1
View File
@@ -13,6 +13,7 @@ return [
'slug' => 'varchar(191) NOT NULL',
'excerpt' => 'text NOT NULL',
'body' => 'longtext NOT NULL',
'featured_image_id' => 'varchar(50) NULL',
'category_id' => 'int NULL',
'status' => "varchar(20) NOT NULL DEFAULT 'draft'",
'published_at' => 'datetime NULL',
@@ -12,7 +12,7 @@ if (!phpb_validate_csrf()) {
$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'];
$fields = ['title', 'slug', 'excerpt', 'body', 'featured_image_id', '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) {
@@ -3,11 +3,14 @@
use Plugi\Core\DB;
use Plugi\Extensions\Blog\CategoriesRepository;
use Plugi\Extensions\Blog\PostsRepository;
use Plugi\Repositories\UploadRepository;
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/Repositories/UploadRepository.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/UploadedFile.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';
@@ -18,10 +21,12 @@ 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';
require_once dirname(__DIR__) . '/admin/Classes/PostContentRenderer.php';
$blogConfig = require dirname(__DIR__) . '/config.php';
\Plugi\Extensions::registerConfig('blog', $blogConfig);
require_once dirname(__DIR__) . '/extension.php';
assertBlog(($blogConfig['tables']['posts']['columns']['featured_image_id'] ?? null) === 'varchar(50) NULL', 'Featured image metadata should be declared as nullable extension schema.');
class BlogTestDatabase extends DB
{
@@ -40,12 +45,22 @@ class BlogTestDatabase extends DB
slug VARCHAR(191) NOT NULL UNIQUE,
excerpt TEXT NOT NULL,
body TEXT NOT NULL,
featured_image_id VARCHAR(50) 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_uploads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
public_id VARCHAR(50) NOT NULL UNIQUE,
original_file VARCHAR(512) NOT NULL,
mime_type VARCHAR(50) NOT NULL,
server_file VARCHAR(512) NOT NULL,
alt_text VARCHAR(1000) NOT NULL DEFAULT "",
folder VARCHAR(255) NOT NULL DEFAULT ""
)');
$this->query('CREATE TABLE test_ext__blog_categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(255) NOT NULL,
@@ -117,6 +132,14 @@ function renderBlogAdminList(): string
return (string) ob_get_clean();
}
function renderBlogEditor(int $postId): string
{
$_GET = ['id' => (string) $postId];
ob_start();
include dirname(__DIR__) . '/admin/Views/EditPost.php';
return (string) ob_get_clean();
}
$_ENV['DATABASE_PREFIX'] = 'test_';
$phpb_db = new BlogTestDatabase();
$phpb_db->createSchema();
@@ -131,24 +154,38 @@ $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.');
$phpb_db->query('INSERT INTO test_uploads (public_id, original_file, mime_type, server_file, alt_text) VALUES (?, ?, ?, ?, ?)', [
'blog-cover-1', 'cover.jpg', 'image/jpeg', 'cover.jpg', 'A "featured" & <cover>',
]);
$phpb_db->query('INSERT INTO test_uploads (public_id, original_file, mime_type, server_file, alt_text) VALUES (?, ?, ?, ?, ?)', [
'blog-document-1', 'notes.pdf', 'application/pdf', 'notes.pdf', 'A document',
]);
$post = $posts->create([
'title' => 'First post',
'slug' => 'first-post',
'excerpt' => 'A short summary',
'body' => 'Post body',
'featured_image_id' => 'blog-cover-1',
'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.');
assertBlog($post['featured_image_id'] === 'blog-cover-1', 'A valid image upload reference should be persisted on the post.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Missing featured image', 'slug' => 'missing-featured-image', 'excerpt' => '', 'body' => 'Body', 'featured_image_id' => 'missing-upload', 'category_id' => '', 'status' => 'draft', 'published_at' => '',
]), 'Missing upload references should be rejected.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Non-image featured image', 'slug' => 'non-image-featured-image', 'excerpt' => '', 'body' => 'Body', 'featured_image_id' => 'blog-document-1', 'category_id' => '', 'status' => 'draft', 'published_at' => '',
]), 'Non-image upload references should be rejected.');
$olderPost = $posts->create([
'title' => 'Older published post',
'slug' => 'older-published-post',
'excerpt' => 'Older excerpt',
'body' => '<script>alert("x")</script>&safe',
'body' => "## Markdown heading\n\nA **bold** and *emphasized* phrase with `inline code`, a [safe link](https://example.com), an [unsafe link](javascript:alert), and an [encoded unsafe link](java&#x73;cript:alert).\n\n- first item\n- second item\n\n1. first numbered item\n2. second numbered item\n\n![Inline &amp; &#93;](https://images.example/photo.jpg)\n![Unsafe JavaScript](javascript:alert)\n![Encoded JavaScript](java&#x73;cript:alert)\n![Unsafe data](data:text/html;base64,abc)\n\n<script>alert(\"x\")</script>&safe",
'category_id' => '',
'status' => 'published',
'published_at' => '2020-01-01T00:00',
@@ -172,19 +209,48 @@ $secondPost = $posts->create([
'status' => 'draft',
'published_at' => '',
]);
$_ENV['BASE_URL'] = 'https://blog.example';
$phpb_config = ['website_manager' => ['url' => '/website-manager'], 'general' => ['uploads_url' => '/uploads']];
$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';
$editorHtml = renderBlogEditor((int) $post['id']);
assertBlog(str_contains($editorHtml, 'name="featured_image_id"') && str_contains($editorHtml, 'value="blog-cover-1" selected'), 'The editor should select a post featured image.');
assertBlog(!str_contains($editorHtml, 'notes.pdf'), 'The featured-image selector should omit non-image uploads.');
assertBlog(str_contains($editorHtml, 'id="post-inline-image"') && str_contains($editorHtml, 'id="insert-post-inline-image"'), 'The editor should offer a control for inserting inline images.');
assertBlog(str_contains($editorHtml, 'data-url="https://blog.example/uploads/blog-cover-1/cover.jpg"') && str_contains($editorHtml, 'data-alt="A &quot;featured&quot; &amp; &lt;cover&gt;"'), 'The inline picker should expose escaped media URL and alt metadata.');
assertBlog(str_contains($editorHtml, 'selectionStart') && str_contains($editorHtml, 'setRangeText'), 'The inline picker should insert Markdown at the textarea cursor.');
$listingHtml = renderBlogListing();
assertBlog(str_contains($listingHtml, 'href="https://blog.example/blog/first-post"'), 'The listing should link to the configured post detail URL.');
assertBlog(str_contains($listingHtml, 'src="https://blog.example/uploads/blog-cover-1/cover.jpg" alt="A &quot;featured&quot; &amp; &lt;cover&gt;"'), 'The public listing should display a featured image with escaped alt text.');
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, '&lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;&amp;safe') && !str_contains($detailHtml, '<script>alert'), 'The detail block should safely escape post bodies.');
assertBlog(str_contains($detailHtml, '<h2 class="text-2xl font-bold tracking-tight">Markdown heading</h2>') && str_contains($detailHtml, '<strong>bold</strong>') && str_contains($detailHtml, '<em>emphasized</em>'), 'The detail block should render Markdown headings and emphasis.');
assertBlog(str_contains($detailHtml, '<a class="link link-hover" href="https://example.com">safe link</a>') && !str_contains($detailHtml, 'href="javascript:') && !str_contains($detailHtml, 'href="java'), 'The detail block should render safe links and reject unsafe protocols.');
assertBlog(str_contains($detailHtml, '<ul class="list-disc') && str_contains($detailHtml, '<li>first item</li>') && str_contains($detailHtml, '<li>second item</li>'), 'The detail block should render Markdown lists.');
assertBlog(str_contains($detailHtml, '<ol class="list-decimal') && str_contains($detailHtml, '<li>first numbered item</li>'), 'The detail block should render ordered Markdown lists.');
assertBlog(str_contains($detailHtml, '<code>inline code</code>'), 'The detail block should render inline code.');
assertBlog(str_contains($detailHtml, '<img src="https://images.example/photo.jpg" alt="Inline &amp; ]" class="max-w-full rounded-box">'), 'The detail block should render inline Markdown images with escaped alt text.');
assertBlog(!str_contains($detailHtml, 'src="javascript:') && !str_contains($detailHtml, 'src="java') && !str_contains($detailHtml, 'src="data:'), 'The detail block should reject unsafe image URL protocols.');
assertBlog(str_contains($detailHtml, '&lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;&amp;safe') && !str_contains($detailHtml, '<script>alert'), 'The detail block should escape raw HTML in post bodies.');
assertBlog(!str_contains($detailHtml, 'src="https://blog.example/uploads/blog-cover-1/cover.jpg"'), 'Posts without featured images should omit the featured-image URL.');
$plainTextHtml = renderBlogDetail('first-post');
assertBlog(str_contains($plainTextHtml, '<p>Post body</p>'), 'Existing plain-text post bodies should remain readable.');
assertBlog(str_contains($plainTextHtml, 'src="https://blog.example/uploads/blog-cover-1/cover.jpg" alt="A &quot;featured&quot; &amp; &lt;cover&gt;"'), 'The public detail block should display a featured image with escaped alt text.');
$phpb_db->query('INSERT INTO test_uploads (public_id, original_file, mime_type, server_file, alt_text) VALUES (?, ?, ?, ?, ?)', [
'blog-cover-deleted', 'deleted.jpg', 'image/jpeg', 'deleted.jpg', 'Deleted cover',
]);
$deletedCoverPost = $posts->create([
'title' => 'Deleted featured image', 'slug' => 'deleted-featured-image', 'excerpt' => '', 'body' => 'Body', 'featured_image_id' => 'blog-cover-deleted', 'category_id' => '', 'status' => 'published', 'published_at' => '2019-01-01T00:00',
]);
$phpb_db->query('DELETE FROM test_uploads WHERE public_id = ?', ['blog-cover-deleted']);
assertBlog(!str_contains(renderBlogDetail('deleted-featured-image'), '<img'), 'Deleted featured-image uploads should be omitted from public detail pages.');
assertBlog(!str_contains(renderBlogListing(), 'deleted.jpg'), 'Deleted featured-image uploads should be omitted from public post cards.');
$posts->destroy($deletedCoverPost['id']);
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.');
@@ -205,13 +271,14 @@ $updated = $posts->update(['id' => $post['id']], [
'slug' => 'updated-post',
'excerpt' => '',
'body' => 'Updated body',
'featured_image_id' => '',
'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($updatedPost['title'] === 'Updated post' && $updatedPost['category_id'] === null && $updatedPost['published_at'] === null && $updatedPost['featured_image_id'] === null, 'Post updates should persist edited fields and clear optional values.');
assertBlog(is_array($secondPost), 'A draft with an empty body should be saved.');