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:
@@ -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, '&').replace(/\[/g, '[').replace(/\]/g, ']');
|
||||
const markdown = ``;
|
||||
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>
|
||||
Reference in New Issue
Block a user