Added language-specific syntax highlighting support to the markdown editor and preview. New code-highlighter assets are registered for public pages and admin headers. The PostContentRenderer detects language identifiers in code fences to apply appropriate CSS classes for highlighting. Tests verify the highlighting works correctly and unsafe content is escaped properly.
444 lines
32 KiB
PHP
444 lines
32 KiB
PHP
<?php
|
|
|
|
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';
|
|
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';
|
|
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
|
|
{
|
|
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,
|
|
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,
|
|
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');
|
|
}
|
|
|
|
function renderBlogAdminList(): string
|
|
{
|
|
ob_start();
|
|
include dirname(__DIR__) . '/admin/Views/ListPosts.php';
|
|
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();
|
|
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(in_array('/admin/assets/markdown-editor.js', array_column($blogConfig['assets'], 'src'), true) && in_array('/admin/assets/markdown-editor.css', array_column($blogConfig['assets'], 'src'), true), 'The editor script and stylesheet should be registered as extension assets.');
|
|
$publicAssets = array_values(array_filter($blogConfig['assets'], fn(array $asset): bool => $asset['location'] === 'footer'));
|
|
$adminAssets = array_values(array_filter($blogConfig['assets'], fn(array $asset): bool => $asset['location'] === 'admin-header'));
|
|
assertBlog(in_array(['src' => '/assets/code-highlighter.css', 'type' => 'style', 'location' => 'footer'], $publicAssets, true) && in_array(['src' => '/assets/code-highlighter.js', 'type' => 'script', 'location' => 'footer'], $publicAssets, true), 'The highlighter assets should be registered for public pages.');
|
|
assertBlog(in_array(['src' => '/assets/code-highlighter.css', 'type' => 'style', 'location' => 'admin-header'], $adminAssets, true) && in_array(['src' => '/assets/code-highlighter.js', 'type' => 'script', 'location' => 'admin-header'], $adminAssets, true), 'The highlighter assets should be registered for admin pages.');
|
|
assertBlog(array_search('/assets/code-highlighter.js', array_column($adminAssets, 'src'), true) < array_search('/admin/assets/markdown-editor.js', array_column($adminAssets, 'src'), true), 'The admin highlighter should load before the Markdown editor.');
|
|
$highlighterSource = file_get_contents(dirname(__DIR__) . '/assets/src/code-highlighter.js');
|
|
$editorSource = file_get_contents(dirname(__DIR__) . '/admin/assets/src/markdown-editor.js');
|
|
assertBlog(str_contains($highlighterSource, 'highlightPage') && str_contains($highlighterSource, "document.addEventListener('DOMContentLoaded'"), 'The highlighter should initialize code blocks on initial page content.');
|
|
assertBlog(str_contains($editorSource, 'window.blogCodeHighlighter?.highlight(preview)'), 'The editor should highlight preview code after replacing its contents.');
|
|
assertBlog(count(array_intersect(['/ext--blog/save-post', '/ext--blog/preview-post', '/ext--blog/delete-post', '/ext--blog/save-category', '/ext--blog/delete-category'], array_keys(\Plugi\Extensions::getRoutes()))) === 5, 'Blog post and category 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.');
|
|
$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' => "## 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\n\n\n\n<script>alert(\"x\")</script>&safe\n\n---\n\n> Quoted **text**.\n\n```php\n<script>alert(\"code\")</script>\n```\n\n~~~php\" onmouseover=\"alert(1)\n<script>alert(1)</script>\n~~~",
|
|
'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' => '',
|
|
]);
|
|
$_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.');
|
|
|
|
$editorHtml = renderBlogEditor((int) $post['id']);
|
|
assertBlog(str_contains($editorHtml, '<textarea id="post-body" name="body"') && str_contains($editorHtml, 'Post body'), 'The visible fallback textarea should retain and submit the stored body value.');
|
|
assertBlog(str_contains($editorHtml, 'id="post-body-toolbar"') && str_contains($editorHtml, 'data-format="bold"') && str_contains($editorHtml, 'data-format="heading"'), 'The editor should provide accessible Markdown formatting controls.');
|
|
assertBlog(str_contains($editorHtml, 'data-format="list"') && str_contains($editorHtml, 'data-format="ordered-list"') && str_contains($editorHtml, 'data-format="quote"') && str_contains($editorHtml, 'data-format="horizontal-rule"') && str_contains($editorHtml, 'data-format="code-block"'), 'The editor toolbar should offer unordered and ordered lists, quotes, horizontal rules, and code blocks.');
|
|
assertBlog(str_contains($editorHtml, 'id="post-body-editor"') && str_contains($editorHtml, 'id="post-body-preview"') && str_contains($editorHtml, 'id="post-body-view-tabs"'), 'The editor should include a CodeMirror mount and a preview toggle in the editor workspace.');
|
|
assertBlog(str_contains($editorHtml, 'data-view="write"') && str_contains($editorHtml, 'data-view="preview"') && str_contains($editorHtml, 'role="tabpanel"') && str_contains($editorHtml, 'aria-live="polite"'), 'The editor and preview tabs should expose accessible panels and status.');
|
|
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.');
|
|
assertBlog(str_contains($editorHtml, 'window.blogMarkdownEditor.insertAtCursor(markdown)'), 'The inline picker should insert at the CodeMirror cursor when the editor is initialized.');
|
|
$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, '<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, '<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, '<hr class="my-6 border-base-300">'), 'The detail block should render Markdown horizontal rules.');
|
|
assertBlog(str_contains($detailHtml, '<blockquote class="border-l-4 border-base-300 pl-4 text-base-content/80"><p>Quoted <strong>text</strong>.</p></blockquote>'), 'The detail block should render Markdown blockquotes with inline formatting.');
|
|
assertBlog(str_contains($detailHtml, '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code class="language-php"><script>alert("code")</script></code></pre>'), 'The detail block should add a language class and escape fenced code.');
|
|
assertBlog(str_contains($detailHtml, '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code><script>alert(1)</script></code></pre>') && !str_contains($detailHtml, 'onmouseover='), 'Malformed fence info should not create attributes, and its code should remain escaped.');
|
|
assertBlog(str_contains($detailHtml, '<img src="https://images.example/photo.jpg" alt="Inline & ]" 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, '<script>alert("x")</script>&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 "featured" & <cover>"'), '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.');
|
|
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',
|
|
'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 && $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.');
|
|
|
|
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($posts->destroy($post['id']) === true, 'The remaining draft 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.');
|
|
$phpb_config = ['website_manager' => ['url' => '/website-manager']];
|
|
$_GET = [];
|
|
assertBlog(str_contains(renderBlogAdminList(), 'No posts yet'), 'The admin list should show its empty-list state when no posts exist.');
|
|
|
|
for ($index = 1; $index <= 12; $index++) {
|
|
$number = str_pad((string) $index, 2, '0', STR_PAD_LEFT);
|
|
$batchPost = $posts->create([
|
|
'title' => 'Pagination batch ' . $number,
|
|
'slug' => 'pagination-batch-' . $number,
|
|
'excerpt' => 'Batch excerpt',
|
|
'body' => 'Batch body',
|
|
'category_id' => '',
|
|
'status' => $index === 12 ? 'draft' : 'published',
|
|
'published_at' => '2025-01-' . $number . 'T00:00',
|
|
]);
|
|
$phpb_db->query('UPDATE test_ext__blog_posts SET updated_at = ? WHERE id = ?', ['2025-02-' . $number . ' 00:00:00', $batchPost['id']]);
|
|
}
|
|
|
|
foreach ([
|
|
'title' => 'TitleSearchMarker',
|
|
'slug' => 'slugsearchmarker',
|
|
'excerpt' => 'ExcerptSearchMarker',
|
|
'body' => 'BodySearchMarker',
|
|
] as $field => $term) {
|
|
$fieldPost = [
|
|
'title' => 'Field-only test post',
|
|
'slug' => 'field-only-test-post',
|
|
'excerpt' => 'Field-only excerpt',
|
|
'body' => 'Field-only body',
|
|
'category_id' => '',
|
|
'status' => 'published',
|
|
'published_at' => '2025-03-01T00:00',
|
|
];
|
|
$fieldPost[$field] = $term;
|
|
$fieldPost['slug'] = $field === 'slug' ? $term : 'field-only-' . $field;
|
|
$fieldPost = $posts->create($fieldPost);
|
|
$adminMatch = $posts->getPageForAdmin($term, 1);
|
|
$publicMatch = $posts->getPageForListing($term, 1);
|
|
assertBlog($adminMatch['total'] === 1 && $adminMatch['posts'][0]['slug'] === $fieldPost['slug'], 'Admin search should match the ' . $field . ' field.');
|
|
assertBlog($publicMatch['total'] === 1 && $publicMatch['posts'][0]['slug'] === $fieldPost['slug'], 'Public search should match the ' . $field . ' field.');
|
|
}
|
|
|
|
foreach ([
|
|
['term' => '100%', 'match' => 'literal-percent', 'title' => 'Price 100% complete', 'decoy' => 'wildcard-percent-decoy', 'decoyTitle' => 'Price 100X complete'],
|
|
['term' => 'under_score', 'match' => 'literal-underscore', 'title' => 'under_score example', 'decoy' => 'wildcard-underscore-decoy', 'decoyTitle' => 'underXscore example'],
|
|
['term' => 'bang!mark', 'match' => 'literal-escape-character', 'title' => 'bang!mark example', 'decoy' => 'escape-character-decoy', 'decoyTitle' => 'bangXmark example'],
|
|
] as $literalSearch) {
|
|
foreach ([[$literalSearch['match'], $literalSearch['title']], [$literalSearch['decoy'], $literalSearch['decoyTitle']]] as [$slug, $title]) {
|
|
$posts->create([
|
|
'title' => $title,
|
|
'slug' => $slug,
|
|
'excerpt' => '',
|
|
'body' => 'Search wildcard regression test',
|
|
'category_id' => '',
|
|
'status' => 'published',
|
|
'published_at' => '2025-03-01T00:00',
|
|
]);
|
|
}
|
|
$adminMatch = $posts->getPageForAdmin($literalSearch['term'], 1);
|
|
$publicMatch = $posts->getPageForListing($literalSearch['term'], 1);
|
|
assertBlog($adminMatch['total'] === 1 && $adminMatch['posts'][0]['slug'] === $literalSearch['match'], 'Admin search should treat LIKE metacharacters literally.');
|
|
assertBlog($publicMatch['total'] === 1 && $publicMatch['posts'][0]['slug'] === $literalSearch['match'], 'Public search should treat LIKE metacharacters literally.');
|
|
}
|
|
|
|
$adminFirstPage = $posts->getPageForAdmin('pagination', 1);
|
|
$adminLastPage = $posts->getPageForAdmin('pagination', 2);
|
|
assertBlog($adminFirstPage['total'] === 12 && count($adminFirstPage['posts']) === 10, 'Admin pagination should report all matching posts and cap each page at ten.');
|
|
assertBlog($adminFirstPage['posts'][0]['slug'] === 'pagination-batch-12' && $adminFirstPage['posts'][9]['slug'] === 'pagination-batch-03', 'Admin pages should preserve the newest-updated-first order.');
|
|
assertBlog(count($adminLastPage['posts']) === 2 && $adminLastPage['posts'][0]['slug'] === 'pagination-batch-02', 'The admin final page should contain the remaining posts in order.');
|
|
assertBlog($posts->getPageForAdmin('pagination', 0)['posts'][0]['slug'] === 'pagination-batch-12', 'Invalid low page numbers should normalize to the first page.');
|
|
assertBlog($posts->getPageForAdmin('pagination', PHP_INT_MAX)['posts'][0]['slug'] === 'pagination-batch-02', 'Oversized page numbers should safely resolve to the last matching page.');
|
|
|
|
$publicFirstPage = $posts->getPageForListing('pagination', 1);
|
|
$publicLastPage = $posts->getPageForListing('pagination', 2);
|
|
assertBlog($publicFirstPage['total'] === 11 && count($publicFirstPage['posts']) === 10, 'Public pagination should exclude the matching draft and report published totals.');
|
|
assertBlog($publicFirstPage['posts'][0]['slug'] === 'pagination-batch-11', 'Public pages should preserve newest-published-first order.');
|
|
assertBlog(count($publicLastPage['posts']) === 1 && $publicLastPage['posts'][0]['slug'] === 'pagination-batch-01', 'The public final page should contain its remaining published post.');
|
|
$noMatches = $posts->getPageForAdmin("pagination' OR '1'='1", 1);
|
|
assertBlog($noMatches['total'] === 0 && $noMatches['posts'] === [], 'Search input should be treated as a value rather than SQL.');
|
|
|
|
$_SERVER['HTTPS'] = 'on';
|
|
$_SERVER['SERVER_NAME'] = 'blog.example';
|
|
$_SERVER['SERVER_PORT'] = 443;
|
|
$_ENV['BASE_URL'] = 'https://blog.example/app';
|
|
$_SERVER['REQUEST_URI'] = '/app/news?keep=old';
|
|
$_GET = ['q' => 'pagination', 'page' => '2'];
|
|
$publicSearchPage = renderBlogListing();
|
|
assertBlog(str_contains($publicSearchPage, 'Pagination batch 01') && !str_contains($publicSearchPage, 'Pagination batch 11'), 'The public block should render only the requested search page.');
|
|
assertBlog(str_contains($publicSearchPage, 'action="https://blog.example/app/news"') && str_contains($publicSearchPage, 'name="q" value="pagination"'), 'The public search form should submit to the current path and retain its search value.');
|
|
assertBlog(str_contains($publicSearchPage, 'href="https://blog.example/app/news?q=pagination&page=1"') && str_contains($publicSearchPage, 'Page 2 of 2'), 'Public pagination should retain the search term and current page position.');
|
|
$_GET = ['q' => 'pagination', 'page' => '0'];
|
|
assertBlog(str_contains(renderBlogListing(), 'Pagination batch 11'), 'Invalid public page values should safely show the first page.');
|
|
$_GET = ['q' => 'no-such-post'];
|
|
$publicNoMatches = renderBlogListing();
|
|
assertBlog(str_contains($publicNoMatches, 'No published posts match "no-such-post"') && !str_contains($publicNoMatches, 'No published posts yet.'), 'The public block should distinguish no matches from an empty blog.');
|
|
|
|
$_GET = ['q' => 'pagination', 'page' => '99', 'posts_page' => '2'];
|
|
$adminSearchPage = renderBlogAdminList();
|
|
assertBlog(str_contains($adminSearchPage, 'Pagination batch 02') && str_contains($adminSearchPage, 'Pagination batch 01') && !str_contains($adminSearchPage, 'Pagination batch 12'), 'The admin list should render only the requested page.');
|
|
assertBlog(str_contains($adminSearchPage, 'name="tab" value="ext--blog"') && str_contains($adminSearchPage, 'name="q" value="pagination"'), 'The admin search form should retain the extension route and search term.');
|
|
assertBlog(str_contains($adminSearchPage, 'href="https://blog.example/app/website-manager?tab=ext--blog&action=posts&q=pagination&posts_page=1"') && str_contains($adminSearchPage, 'Page 2 of 2'), 'Admin pagination should preserve the extension route, search term, and posts_page parameter.');
|
|
$_GET = ['q' => 'pagination', 'page' => '2', 'posts_page' => '1'];
|
|
$adminFirstPageHtml = renderBlogAdminList();
|
|
assertBlog(str_contains($adminFirstPageHtml, 'Pagination batch 12') && str_contains($adminFirstPageHtml, '>Draft</span>'), 'The admin list should include matching drafts.');
|
|
$_GET = ['q' => 'pagination', 'page' => '2', 'posts_page' => '0'];
|
|
assertBlog(str_contains(renderBlogAdminList(), 'Pagination batch 12'), 'Invalid admin page values should safely show the first page.');
|
|
$_GET = ['q' => 'no-such-post'];
|
|
$adminNoMatches = renderBlogAdminList();
|
|
assertBlog(str_contains($adminNoMatches, 'No posts found for "no-such-post"') && !str_contains($adminNoMatches, 'No posts yet'), 'The admin list should distinguish no matches from an empty post list.');
|
|
|
|
fwrite(STDOUT, "Blog repository tests passed.\n"); |