From d035a18ee620d6d876b13387396366cb04a12e60 Mon Sep 17 00:00:00 2001 From: Paul Spenke Date: Tue, 1 Dec 2026 22:06:27 +0100 Subject: [PATCH] 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. --- extensions/plugi-ext-blog/README.md | 12 +- .../admin/Classes/PostContentRenderer.php | 131 ++++++++++++++++++ .../admin/Classes/PostsRepository.php | 54 +++++++- .../plugi-ext-blog/admin/Views/EditPost.php | 64 ++++++++- .../blocks/post-detail/view.php | 8 +- .../plugi-ext-blog/blocks/post-list/view.php | 6 + extensions/plugi-ext-blog/config.php | 1 + extensions/plugi-ext-blog/routes/savePost.php | 2 +- .../tests/BlogRepositoriesTest.php | 75 +++++++++- 9 files changed, 336 insertions(+), 17 deletions(-) create mode 100644 extensions/plugi-ext-blog/admin/Classes/PostContentRenderer.php diff --git a/extensions/plugi-ext-blog/README.md b/extensions/plugi-ext-blog/README.md index ea05c22..298a1d6 100644 --- a/extensions/plugi-ext-blog/README.md +++ b/extensions/plugi-ext-blog/README.md @@ -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. \ No newline at end of file +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. \ No newline at end of file diff --git a/extensions/plugi-ext-blog/admin/Classes/PostContentRenderer.php b/extensions/plugi-ext-blog/admin/Classes/PostContentRenderer.php new file mode 100644 index 0000000..dfdaae2 --- /dev/null +++ b/extensions/plugi-ext-blog/admin/Classes/PostContentRenderer.php @@ -0,0 +1,131 @@ +' . nl2br($this->renderInline(implode("\n", $paragraph))) . '

'; + $paragraph = []; + } + if ($listType !== null) { + $class = $listType === 'ul' ? 'list-disc' : 'list-decimal'; + $items = array_map(fn(string $item): string => '
  • ' . $this->renderInline($item) . '
  • ', $listItems); + $blocks[] = '<' . $listType . ' class="' . $class . ' space-y-1 pl-6">' . implode('', $items) . ''; + $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[] = '' . $this->renderInline($matches[2]) . ''; + 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 .= '' . $this->escape(substr($part, 1, -1)) . ''; + } elseif (preg_match('/^!\[([^\]]*)\]\(([^)]+)\)$/', $part, $matches)) { + $altText = html_entity_decode($matches[1], ENT_QUOTES | ENT_HTML5, 'UTF-8'); + $html .= $this->isSafeImageUrl($matches[2]) + ? '' . $this->escape($altText) . '' + : $this->escape($altText); + } elseif (preg_match('/^\[([^\]]+)\]\(([^)]+)\)$/', $part, $matches)) { + $html .= $this->isSafeLink($matches[2]) + ? '' . $this->renderInline($matches[1]) . '' + : $this->renderInline($matches[1]); + } elseif (str_starts_with($part, '**') || str_starts_with($part, '__')) { + $html .= '' . $this->renderInline(substr($part, 2, -2)) . ''; + } elseif ($part[0] === '*' || $part[0] === '_') { + $html .= '' . $this->renderInline(substr($part, 1, -1)) . ''; + } 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'); + } +} \ No newline at end of file diff --git a/extensions/plugi-ext-blog/admin/Classes/PostsRepository.php b/extensions/plugi-ext-blog/admin/Classes/PostsRepository.php index 870b1e4..a600ae5 100644 --- a/extensions/plugi-ext-blog/admin/Classes/PostsRepository.php +++ b/extensions/plugi-ext-blog/admin/Classes/PostsRepository.php @@ -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 === '') { diff --git a/extensions/plugi-ext-blog/admin/Views/EditPost.php b/extensions/plugi-ext-blog/admin/Views/EditPost.php index aacdcea..c0c2e98 100644 --- a/extensions/plugi-ext-blog/admin/Views/EditPost.php +++ b/extensions/plugi-ext-blog/admin/Views/EditPost.php @@ -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/'))); ?>
    @@ -57,7 +60,36 @@ $categories = (new CategoriesRepository())->getAllForAdmin();
    -

    Body content is rendered as escaped plain text on the public page.

    +

    Use Markdown for headings, links, lists, and emphasis.

    +
    +
    + + +
    + +
    +

    Alt text comes from the media library; the image Markdown is inserted at the cursor.

    +
    +
    + + +

    Choose an image from the existing media library.

    @@ -89,4 +121,32 @@ $categories = (new CategoriesRepository())->getAllForAdmin(); Cancel
    - \ No newline at end of file + + + \ No newline at end of file diff --git a/extensions/plugi-ext-blog/blocks/post-detail/view.php b/extensions/plugi-ext-blog/blocks/post-detail/view.php index 900a38b..50c365f 100644 --- a/extensions/plugi-ext-blog/blocks/post-detail/view.php +++ b/extensions/plugi-ext-blog/blocks/post-detail/view.php @@ -31,6 +31,12 @@ $post = is_string($slug) && $slug !== ''

    -
    + + +
    + <?= phpb_e($featuredImageAlt) ?> +
    + +
    render($post['body']) ?>
    \ No newline at end of file diff --git a/extensions/plugi-ext-blog/blocks/post-list/view.php b/extensions/plugi-ext-blog/blocks/post-list/view.php index 8c46b65..de8a85c 100644 --- a/extensions/plugi-ext-blog/blocks/post-list/view.php +++ b/extensions/plugi-ext-blog/blocks/post-list/view.php @@ -31,6 +31,12 @@ $searchParameters = $search === '' ? [] : ['q' => $search];
    + + +
    + <?= phpb_e($featuredImageAlt) ?> +
    +
    diff --git a/extensions/plugi-ext-blog/config.php b/extensions/plugi-ext-blog/config.php index 132045b..1cb9949 100644 --- a/extensions/plugi-ext-blog/config.php +++ b/extensions/plugi-ext-blog/config.php @@ -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', diff --git a/extensions/plugi-ext-blog/routes/savePost.php b/extensions/plugi-ext-blog/routes/savePost.php index 12ac4f9..808281b 100644 --- a/extensions/plugi-ext-blog/routes/savePost.php +++ b/extensions/plugi-ext-blog/routes/savePost.php @@ -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) { diff --git a/extensions/plugi-ext-blog/tests/BlogRepositoriesTest.php b/extensions/plugi-ext-blog/tests/BlogRepositoriesTest.php index ad2f907..42cea6e 100644 --- a/extensions/plugi-ext-blog/tests/BlogRepositoriesTest.php +++ b/extensions/plugi-ext-blog/tests/BlogRepositoriesTest.php @@ -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" & ', +]); +$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' => '&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](javascript:alert).\n\n- first item\n- second item\n\n1. first numbered item\n2. second numbered item\n\n![Inline & ]](https://images.example/photo.jpg)\n![Unsafe JavaScript](javascript:alert)\n![Encoded JavaScript](javascript:alert)\n![Unsafe data](data:text/html;base64,abc)\n\n&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 "featured" & <cover>"'), '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 "featured" & <cover>"'), '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, '

    Older published post

    '), '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, '