Compare commits

..
Author SHA1 Message Date
deepDiverPaul 58e05e88ae feat(ext-blog): Add timezone support for blog publication dates and search
Configure `general.timezone` in root config to control blog publication input and display. Update PostsRepository to validate dates against the site timezone and enforce a minimum search length for public queries. Modify admin views to display publication dates in the site's local timezone and update search labels. Add tests for the new timezone handling and search validation logic.
2026-12-02 12:08:45 +01:00
deepDiverPaul 8ebed89e73 feat(ext-blog): Add syntax highlighting for code blocks
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.
2026-12-02 11:09:09 +01:00
deepDiverPaul e0767b65e6 feat(ext-blog): Add markdown editor bundling and dependencies 2026-12-02 11:09:09 +01:00
deepDiverPaul 19e6b1a332 feat(ext-blog): Add rich Markdown editor for blog posts
Replace the plain textarea with a CodeMirror-based editor supporting syntax highlighting, formatting toolbar (bold, italic, lists, code blocks), and a live preview toggle. Update PostContentRenderer to handle new Markdown syntax (blockquotes, fenced code blocks). Add a preview endpoint for rendering content without saving.
2026-12-02 11:09:09 +01:00
deepDiverPaul d035a18ee6 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.
2026-12-02 11:09:09 +01:00
deepDiverPaul d2802f728f feat(ext-blog): Add pagination and search to blog post listing
The PostsRepository now includes methods for fetching paginated and searched posts. The admin and public views include search forms, pagination controls, and display total counts instead of just post counts. Tests verify the new functionality including special character search handling and pagination limits.
2026-12-02 11:09:09 +01:00
deepDiverPaul 5ffc191488 Add blog extension 2026-12-02 11:09:09 +01:00
deepDiverPaul b44b1bfc72 fix(security): Add security hardening and CSRF protection.
Added .htaccess rules to deny access to hidden files. Escaped JSON output in views to prevent XSS attacks. Converted delete links and forms to use POST with CSRF tokens. Enforced POST method on sensitive routes. Added tests to verify these security controls.
2026-12-02 11:07:41 +01:00
40 changed files with 2394 additions and 77 deletions
+5
View File
@@ -1,5 +1,10 @@
<FilesMatch "^\.">
Require all denied
</FilesMatch>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule (^|/)\.(?!well-known/) - [F,L]
# Redirect non-www. to www. (except when on a subdomain)
# RewriteCond %{HTTP_HOST} !^www\.
+1
View File
@@ -11,6 +11,7 @@ return [
*/
"general" => [
"language" => "en",
"timezone" => "UTC",
"assets_url" => "/plugi-core/dist",
"uploads_url" => "/uploads",
],
+11 -3
View File
@@ -1,19 +1,27 @@
# 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.
Set `general.timezone` in the root `config.php` to the site's IANA timezone (for example, `Europe/Berlin`); it defaults to `UTC` and controls blog publication input and display. Publication dates are stored as site-local `DATETIME` values, so existing installations should configure the timezone that matches their existing post dates.
## Create the public pages
1. Create a regular Plugi page with the route `/blog` and add the **Published Posts** block. It lists published posts newest first; drafts are never shown.
1. Create a regular Plugi page with the route `/blog` and add the **Published Posts** block. It lists published posts newest first; drafts are never shown. Public search matches titles, slugs, and excerpts (at least three characters), not full post bodies.
2. Create another regular page with the route `/blog/{slug}` and add the **Blog Post** block. The core router supplies the named `slug` parameter to the block.
3. Apply the site’s normal page layout and theme to both pages. Their presentation remains controlled by the page builder and theme.
The detail block displays a not-found state for a missing, unknown, or unpublished slug. The blog blocks are not page-cached so publishing or editing content is reflected on the next request. Authors, tags, scheduling, RSS, and translated posts are not included in this release.
Keep `/blog` and `/blog/{slug}` unique among the site’s page routes.
## Authoring content and images
Write post bodies in Markdown using the syntax-highlighted source editor. Its toolbar inserts bold, italic, headings, links, unordered and ordered lists, blockquotes, horizontal rules, inline code, and fenced code blocks; the live preview uses the same server-side renderer as the public detail page. If JavaScript is unavailable, the source textarea remains usable and can still save the post. The detail page supports headings, paragraphs and line breaks, bold and italic text, inline code, links, ordered and unordered lists, blockquotes, horizontal rules, and fenced code blocks. Add a language identifier after the opening fence (for example, `php`) to enable language-specific highlighting. Bash, CSS, diff, HTML/XML, JavaScript/TypeScript, JSON, Markdown, PHP, Python, SQL, and YAML are highlighted; unlabeled blocks are auto-detected from this set, and other language labels remain plain text. Code-block contents are rendered as escaped text before highlighting. 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,186 @@
<?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 = [];
$quote = [];
$flush = function () use (&$blocks, &$paragraph, &$listType, &$listItems, &$quote): 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 = [];
}
if ($quote !== []) {
$blocks[] = '<blockquote class="border-l-4 border-base-300 pl-4 text-base-content/80"><p>' . nl2br($this->renderInline(implode("\n", $quote))) . '</p></blockquote>';
$quote = [];
}
};
$fence = null;
$fenceLanguage = null;
$codeLines = [];
foreach (preg_split('/\R/', $markdown) ?: [] as $line) {
if ($fence !== null) {
if (preg_match('/^ {0,3}(`{3,}|~{3,})[ \t]*$/', $line, $matches)
&& $matches[1][0] === $fence[0]
&& strlen($matches[1]) >= strlen($fence)) {
$codeClass = $fenceLanguage === null ? '' : ' class="language-' . $fenceLanguage . '"';
$blocks[] = '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code' . $codeClass . '>' . $this->escape(implode("\n", $codeLines)) . '</code></pre>';
$fence = null;
$fenceLanguage = null;
$codeLines = [];
continue;
}
$codeLines[] = $line;
continue;
}
if (preg_match('/^ {0,3}(`{3,}|~{3,})(.*)$/', $line, $matches)) {
$flush();
$fence = $matches[1];
$info = trim($matches[2]);
$fenceLanguage = preg_match('/^([A-Za-z0-9][A-Za-z0-9_+-]*)(?:[ \t]+|$)/', $info, $languageMatches)
? $languageMatches[1]
: null;
$codeLines = [];
continue;
}
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}(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})$/', $line)) {
$flush();
$blocks[] = '<hr class="my-6 border-base-300">';
continue;
}
if (preg_match('/^ {0,3}> ?(.*)$/', $line, $matches)) {
if ($paragraph !== [] || $listType !== null) {
$flush();
}
$quote[] = $matches[1];
continue;
}
if ($quote !== []) {
$flush();
}
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();
if ($fence !== null) {
$codeClass = $fenceLanguage === null ? '' : ' class="language-' . $fenceLanguage . '"';
$blocks[] = '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code' . $codeClass . '>' . $this->escape(implode("\n", $codeLines)) . '</code></pre>';
}
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');
}
}
@@ -3,11 +3,15 @@
namespace Plugi\Extensions\Blog;
use DateTimeImmutable;
use DateTimeZone;
use InvalidArgumentException;
use Plugi\Repositories\BaseRepository;
class PostsRepository extends BaseRepository
{
public const POSTS_PER_PAGE = 10;
public const MIN_PUBLIC_SEARCH_LENGTH = 3;
protected $table = 'ext__blog_posts';
public function create(array $data)
@@ -30,24 +34,75 @@ class PostsRepository extends BaseRepository
return $this->db->select("SELECT * FROM {$this->table} ORDER BY updated_at DESC, id DESC", []);
}
public function getPublishedForListing(): array
public function getPageForAdmin(string $search, int $page): array
{
return $this->getPostPage($search, $page, false);
}
public function getPageForListing(string $search, int $page): array
{
return $this->getPostPage($search, $page, true);
}
private function getPostPage(string $search, int $page, bool $publishedOnly): array
{
$search = trim($search);
if ($publishedOnly && $search !== '' && mb_strlen($search) < self::MIN_PUBLIC_SEARCH_LENGTH) {
return ['posts' => [], 'total' => 0];
}
$categoriesTable = $_ENV['DATABASE_PREFIX'] . 'ext__blog_categories';
return $this->db->select(
"SELECT posts.*, categories.name AS category_name FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id WHERE posts.status = ? ORDER BY posts.published_at DESC, posts.id DESC",
['published']
$uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads';
$from = $publishedOnly
? "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 = [];
if ($publishedOnly) {
$filters[] = 'posts.status = ?';
$parameters[] = 'published';
}
if (trim($search) !== '') {
$filters[] = $publishedOnly
? '(posts.title LIKE ? ESCAPE \'!\' OR posts.slug LIKE ? ESCAPE \'!\' OR posts.excerpt LIKE ? ESCAPE \'!\')'
: '(posts.title LIKE ? ESCAPE \'!\' OR posts.slug LIKE ? ESCAPE \'!\' OR posts.excerpt LIKE ? ESCAPE \'!\' OR posts.body LIKE ? ESCAPE \'!\')';
$pattern = '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], trim($search)) . '%';
array_push($parameters, $pattern, $pattern, $pattern);
if (!$publishedOnly) {
$parameters[] = $pattern;
}
}
$where = $filters === [] ? '' : ' WHERE ' . implode(' AND ', $filters);
$total = $this->db->select("SELECT COUNT(*) AS total {$from}{$where}", $parameters)[0]['total'] ?? 0;
$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, 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];
}
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
@@ -90,6 +145,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 [
@@ -97,16 +169,35 @@ 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
{
$timezone = new DateTimeZone((string) (phpb_config('general.timezone') ?: 'UTC'));
if ($value === null || $value === '') {
return $status === 'published' ? date('Y-m-d H:i:s') : null;
return $status === 'published' ? (new DateTimeImmutable('now', $timezone))->format('Y-m-d H:i:s') : null;
}
if (!is_string($value)) {
throw new InvalidArgumentException('Enter a valid publication date.');
@@ -114,12 +205,12 @@ class PostsRepository extends BaseRepository
$value = trim($value);
$format = str_contains($value, 'T') ? 'Y-m-d\\TH:i' : 'Y-m-d H:i:s';
$date = DateTimeImmutable::createFromFormat('!' . $format, $value);
$date = DateTimeImmutable::createFromFormat('!' . $format, $value, $timezone);
$errors = DateTimeImmutable::getLastErrors();
if ($date === false || ($errors !== false && ($errors['warning_count'] > 0 || $errors['error_count'] > 0)) || $date->format($format) !== $value) {
throw new InvalidArgumentException('Enter a valid publication date.');
}
if ($date > new DateTimeImmutable()) {
if ($date > new DateTimeImmutable('now', $timezone)) {
throw new InvalidArgumentException('Publication dates cannot be in the future.');
}
@@ -2,13 +2,16 @@
use Plugi\Extensions\Blog\CategoriesRepository;
use Plugi\Extensions\Blog\PostsRepository;
use Plugi\Repositories\UploadRepository;
$postsRepository = new PostsRepository();
$timezone = new \DateTimeZone((string) (phpb_config('general.timezone') ?: 'UTC'));
$post = [
'title' => '',
'slug' => '',
'excerpt' => '',
'body' => '',
'featured_image_id' => null,
'category_id' => null,
'status' => 'draft',
'published_at' => null,
@@ -17,8 +20,9 @@ if (isset($_GET['id']) && ctype_digit((string) $_GET['id'])) {
$post = $postsRepository->findWithId($_GET['id']) ?? $post;
}
$isEditing = isset($post['id']);
$publishedAt = $post['published_at'] ? date('Y-m-d\TH:i', strtotime($post['published_at'])) : '';
$publishedAt = $post['published_at'] ? (new \DateTimeImmutable($post['published_at'], $timezone))->format('Y-m-d\TH:i') : '';
$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">
@@ -54,10 +58,74 @@ $categories = (new CategoriesRepository())->getAllForAdmin();
<label for="post-excerpt" class="label"><span class="label-text font-medium">Excerpt</span></label>
<textarea id="post-excerpt" name="excerpt" rows="3" class="textarea w-full"><?= phpb_e($post['excerpt']) ?></textarea>
</div>
<div class="space-y-3">
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<label for="post-body" class="label py-0"><span class="label-text font-medium">Post content</span></label>
<div id="post-body-view-tabs" role="tablist" class="tabs tabs-box hidden w-fit" aria-label="Post body view" hidden>
<button id="post-body-write-tab" type="button" role="tab" class="tab tab-active" aria-controls="post-body-write-panel" aria-selected="true" tabindex="0" data-view="write">Write</button>
<button id="post-body-preview-tab" type="button" role="tab" class="tab" aria-controls="post-body-preview-panel" aria-selected="false" tabindex="-1" data-view="preview">Preview</button>
</div>
</div>
<div id="post-body-write-panel" role="tabpanel" aria-labelledby="post-body-write-tab" tabindex="0" class="space-y-3">
<div class="overflow-hidden rounded-box border border-base-300 bg-base-100 shadow-sm">
<div id="post-body-toolbar" class="hidden flex flex-wrap gap-1 border-b border-base-300 bg-base-200/50 px-3 py-2" role="toolbar" aria-label="Markdown formatting" hidden>
<button type="button" class="btn btn-ghost btn-sm" data-format="bold" aria-label="Bold" title="Bold">Bold</button>
<button type="button" class="btn btn-ghost btn-sm" data-format="italic" aria-label="Italic" title="Italic">Italic</button>
<button type="button" class="btn btn-ghost btn-sm" data-format="heading" aria-label="Heading" title="Heading">Heading</button>
<button type="button" class="btn btn-ghost btn-sm" data-format="link" aria-label="Link" title="Link">Link</button>
<button type="button" class="btn btn-ghost btn-sm" data-format="list" aria-label="Bulleted list" title="Bulleted list">Bullets</button>
<button type="button" class="btn btn-ghost btn-sm" data-format="ordered-list" aria-label="Numbered list" title="Numbered list">Numbered list</button>
<button type="button" class="btn btn-ghost btn-sm" data-format="quote" aria-label="Blockquote" title="Blockquote">Quote</button>
<button type="button" class="btn btn-ghost btn-sm" data-format="horizontal-rule" aria-label="Horizontal rule" title="Horizontal rule">Rule</button>
<button type="button" class="btn btn-ghost btn-sm" data-format="code" aria-label="Inline code" title="Inline code">Code</button>
<button type="button" class="btn btn-ghost btn-sm" data-format="code-block" aria-label="Code block" title="Code block">Code block</button>
</div>
<div id="post-body-editor" class="blog-markdown-editor hidden w-full" hidden></div>
<textarea id="post-body" name="body" rows="16" class="textarea w-full rounded-none border-0 font-mono" aria-describedby="post-body-help"><?= phpb_e($post['body']) ?></textarea>
<p id="post-body-help" class="border-t border-base-300 px-4 py-2 text-sm text-base-content/60">Use Markdown for headings, lists, quotes, rules, code blocks, links, and emphasis.</p>
</div>
<div class="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="text-sm text-base-content/60">Alt text comes from the media library; the image Markdown is inserted at the cursor.</p>
</div>
<section id="post-body-preview-panel" role="tabpanel" aria-labelledby="post-body-preview-tab" tabindex="0" class="hidden" hidden>
<div class="min-h-96 overflow-hidden rounded-box border border-base-300 bg-base-100 shadow-sm">
<div class="flex flex-col gap-2 border-b border-base-300 bg-base-200/50 px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h3 id="post-body-preview-heading" class="font-semibold">Live preview</h3>
<p class="text-sm text-base-content/60">Rendered like the published post.</p>
</div>
<p id="post-body-preview-status" class="text-sm text-base-content/60" role="status" aria-live="polite">Waiting for the preview…</p>
</div>
<div id="post-body-preview" class="min-h-80 space-y-4 p-5 sm:p-8" role="region" aria-label="Rendered post preview" aria-busy="false"></div>
</div>
</section>
</div>
<div>
<label for="post-body" class="label"><span class="label-text font-medium">Body</span></label>
<textarea id="post-body" name="body" rows="12" class="textarea w-full" aria-describedby="post-body-help"><?= phpb_e($post['body']) ?></textarea>
<p id="post-body-help" class="mt-1 text-sm text-base-content/60">Body content is rendered as escaped plain text on the public page.</p>
<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>
@@ -80,7 +148,7 @@ $categories = (new CategoriesRepository())->getAllForAdmin();
<div>
<label for="post-published-at" class="label"><span class="label-text font-medium">Publication date</span></label>
<input id="post-published-at" type="datetime-local" name="published_at" value="<?= phpb_e($publishedAt) ?>" class="input w-full" aria-describedby="post-published-at-help">
<p id="post-published-at-help" class="mt-1 text-sm text-base-content/60">Leave blank to use the current time when publishing. Future dates are not supported.</p>
<p id="post-published-at-help" class="mt-1 text-sm text-base-content/60">Times use the site timezone (<?= phpb_e($timezone->getName()) ?>). Leave blank to use the current time when publishing. Future dates are not supported.</p>
</div>
</div>
</section>
@@ -90,3 +158,36 @@ $categories = (new CategoriesRepository())->getAllForAdmin();
<button type="submit" class="btn btn-primary">Save post</button>
</div>
</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})`;
if (window.blogMarkdownEditor && window.blogMarkdownEditor.insertAtCursor(markdown)) {
return;
}
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.dispatchEvent(new Event('input', { bubbles: true }));
body.focus();
});
})();
</script>
@@ -3,7 +3,20 @@
use Plugi\Extensions\Blog\CategoriesRepository;
use Plugi\Extensions\Blog\PostsRepository;
$posts = (new PostsRepository())->getAllForAdmin();
$postsRepository = new PostsRepository();
$search = is_string($_GET['q'] ?? null) ? trim($_GET['q']) : '';
$pageValue = $_GET['posts_page'] ?? null;
$page = is_string($pageValue) ? filter_var($pageValue, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) : false;
$page = $page === false ? 1 : $page;
$pageResult = $postsRepository->getPageForAdmin($search, $page);
$totalPages = max(1, (int) ceil($pageResult['total'] / PostsRepository::POSTS_PER_PAGE));
if ($page > $totalPages) {
$page = $totalPages;
}
$posts = $pageResult['posts'];
$searchParameters = $search === '' ? [] : ['q' => $search];
$adminPostsUrl = phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'posts']);
$websiteManagerUrl = phpb_url('website_manager');
$categories = (new CategoriesRepository())->getAllForAdmin();
$categoryNames = [];
foreach ($categories as $category) {
@@ -15,7 +28,7 @@ foreach ($categories as $category) {
<div class="space-y-1">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-primary">Blog extension</p>
<h2 class="text-xl font-bold tracking-tight text-base-content">Posts</h2>
<p class="text-sm text-base-content/60"><?= count($posts) ?> post<?= count($posts) !== 1 ? 's' : '' ?></p>
<p class="text-sm text-base-content/60"><?= phpb_e((string) $pageResult['total']) ?> post<?= $pageResult['total'] !== 1 ? 's' : '' ?></p>
</div>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'editPost']) ?>" class="btn btn-primary">
<i class="ph-duotone ph-plus" aria-hidden="true"></i>
@@ -23,7 +36,22 @@ foreach ($categories as $category) {
</a>
</header>
<?php if (empty($posts)): ?>
<form class="flex flex-col gap-3 sm:flex-row sm:items-end" method="get" action="<?= phpb_e($websiteManagerUrl) ?>">
<input type="hidden" name="tab" value="ext--blog">
<input type="hidden" name="action" value="posts">
<label class="flex w-full max-w-md flex-col gap-2">
<span class="text-sm font-medium">Search posts</span>
<input class="input w-full" type="search" name="q" value="<?= phpb_e($search) ?>">
</label>
<button class="btn" type="submit">Search</button>
</form>
<?php if ($pageResult['total'] === 0 && $search !== ''): ?>
<div class="alert alert-info" role="status">
No posts found for &quot;<?= phpb_e($search) ?>&quot;.
<a class="link link-hover" href="<?= phpb_e($adminPostsUrl) ?>">Clear search</a>
</div>
<?php elseif ($pageResult['total'] === 0): ?>
<div class="card border border-dashed border-base-300 bg-base-100 shadow-sm" role="status">
<div class="card-body items-center gap-3 px-5 py-12 text-center sm:py-16">
<span class="grid size-14 place-items-center rounded-2xl bg-primary/10 text-primary">
@@ -45,7 +73,7 @@ foreach ($categories as $category) {
<th>Title</th>
<th>Category</th>
<th>Status</th>
<th>Published</th>
<th>Published (site time)</th>
<th class="w-40 text-right">Actions</th>
</tr>
</thead>
@@ -56,7 +84,7 @@ foreach ($categories as $category) {
<div class="font-medium"><?= phpb_e($post['title']) ?></div>
<div class="text-xs text-base-content/60">/<?= phpb_e($post['slug']) ?></div>
</td>
<td><?= phpb_e($categoryNames[$post['category_id']] ?? '—') ?></td>
<td><?= phpb_e($post['category_id'] === null ? '—' : ($categoryNames[$post['category_id']] ?? '—')) ?></td>
<td><span class="badge <?= $post['status'] === 'published' ? 'badge-success' : 'badge-warning' ?>"><?= phpb_e(ucfirst($post['status'])) ?></span></td>
<td><?= phpb_e($post['published_at'] ?? '—') ?></td>
<td>
@@ -79,4 +107,22 @@ foreach ($categories as $category) {
</table>
</div>
<?php endif; ?>
<?php if ($totalPages > 1): ?>
<nav class="flex justify-center" aria-label="Admin post pages">
<div class="join">
<?php if ($page > 1): ?>
<a class="join-item btn btn-sm" rel="prev" href="<?= phpb_e($adminPostsUrl . '&' . http_build_query($searchParameters + ['posts_page' => $page - 1])) ?>">Previous</a>
<?php else: ?>
<span class="join-item btn btn-sm btn-disabled" aria-disabled="true">Previous</span>
<?php endif; ?>
<span class="join-item btn btn-sm btn-disabled" aria-current="page">Page <?= phpb_e($page) ?> of <?= phpb_e($totalPages) ?></span>
<?php if ($page < $totalPages): ?>
<a class="join-item btn btn-sm" rel="next" href="<?= phpb_e($adminPostsUrl . '&' . http_build_query($searchParameters + ['posts_page' => $page + 1])) ?>">Next</a>
<?php else: ?>
<span class="join-item btn btn-sm btn-disabled" aria-disabled="true">Next</span>
<?php endif; ?>
</div>
</nav>
<?php endif; ?>
</section>
@@ -0,0 +1,31 @@
.blog-markdown-editor .cm-editor {
border: 0;
border-radius: 0;
height: clamp(20rem, 55vh, 38rem);
color: var(--color-base-content);
background: var(--color-base-100);
}
.blog-markdown-editor .cm-editor.cm-focused {
outline: 0;
box-shadow: inset 0 0 0 2px var(--color-primary);
}
.blog-markdown-editor .cm-scroller {
min-height: 0;
font-family: var(--default-mono-font, monospace);
}
.blog-markdown-editor .cm-content {
padding: 1rem 0.75rem;
line-height: 1.65;
}
.blog-markdown-editor .cm-line {
padding-inline: 0.25rem;
}
.blog-markdown-editor .cm-activeLineGutter {
color: var(--color-primary);
font-weight: 600;
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,302 @@
import { markdown } from '@codemirror/lang-markdown';
import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands';
import { HighlightStyle, bracketMatching, indentOnInput, syntaxHighlighting } from '@codemirror/language';
import { drawSelection, EditorView, highlightActiveLine, highlightActiveLineGutter, keymap, lineNumbers } from '@codemirror/view';
import { tags } from '@lezer/highlight';
document.addEventListener('DOMContentLoaded', () => {
const textarea = document.getElementById('post-body');
const editorMount = document.getElementById('post-body-editor');
const toolbar = document.getElementById('post-body-toolbar');
const viewTabs = document.getElementById('post-body-view-tabs');
const writePanel = document.getElementById('post-body-write-panel');
const previewPanel = document.getElementById('post-body-preview-panel');
if (!textarea || !editorMount || !toolbar || !viewTabs || !writePanel || !previewPanel) {
return;
}
let editor;
try {
editor = new EditorView({
doc: textarea.value,
extensions: [
markdown(),
lineNumbers(),
highlightActiveLineGutter(),
highlightActiveLine(),
drawSelection(),
history(),
indentOnInput(),
bracketMatching(),
syntaxHighlighting(HighlightStyle.define([
{ tag: tags.heading, color: 'var(--color-primary)', fontWeight: '700' },
{ tag: tags.strong, color: 'var(--color-base-content)', fontWeight: '700' },
{ tag: tags.emphasis, color: 'var(--color-base-content)', fontStyle: 'italic' },
{ tag: tags.link, color: 'var(--color-primary)', textDecoration: 'underline' },
{ tag: tags.url, color: 'var(--color-primary)' },
{ tag: tags.monospace, color: 'var(--color-base-content)', backgroundColor: 'var(--color-base-200)' },
{ tag: tags.quote, color: 'var(--color-base-content)', fontStyle: 'italic' },
{ tag: tags.strikethrough, color: 'var(--color-base-content)', textDecoration: 'line-through' },
])),
EditorView.theme({
'&': { color: 'var(--color-base-content)', backgroundColor: 'var(--color-base-100)' },
'.cm-content': { caretColor: 'var(--color-primary)' },
'.cm-cursor, .cm-dropCursor': { borderLeftColor: 'var(--color-primary)' },
'.cm-selectionBackground, &.cm-focused .cm-selectionBackground': { backgroundColor: 'color-mix(in oklab, var(--color-primary) 35%, transparent)' },
'.cm-gutters': { color: 'var(--color-base-content)', backgroundColor: 'var(--color-base-200)', borderRight: '1px solid var(--color-base-300)' },
'.cm-activeLine, .cm-activeLineGutter': { backgroundColor: 'color-mix(in oklab, var(--color-base-200) 70%, transparent)' },
'.cm-matchingBracket': { backgroundColor: 'var(--color-base-200)', outline: '1px solid var(--color-primary)' },
}),
keymap.of([...defaultKeymap, ...historyKeymap, indentWithTab]),
EditorView.lineWrapping,
EditorView.contentAttributes.of({
'aria-label': 'Post body Markdown',
'aria-describedby': 'post-body-help',
}),
EditorView.updateListener.of((update) => {
if (update.docChanged) {
textarea.value = update.state.doc.toString();
textarea.dispatchEvent(new Event('input', { bubbles: true }));
}
}),
],
parent: editorMount,
});
} catch (error) {
console.error('Could not initialize the blog Markdown editor.', error);
return;
}
editorMount.hidden = false;
editorMount.classList.remove('hidden');
toolbar.hidden = false;
toolbar.classList.remove('hidden');
textarea.hidden = true;
const tabs = Array.from(viewTabs.querySelectorAll('[role="tab"]'));
const activateView = (view, focus = false) => {
const showPreview = view === 'preview';
tabs.forEach((tab) => {
const active = tab.dataset.view === view;
tab.setAttribute('aria-selected', String(active));
tab.tabIndex = active ? 0 : -1;
tab.classList.toggle('tab-active', active);
if (focus && active) {
tab.focus();
}
});
writePanel.hidden = showPreview;
writePanel.classList.toggle('hidden', showPreview);
previewPanel.hidden = !showPreview;
previewPanel.classList.toggle('hidden', !showPreview);
};
activateView('write');
viewTabs.hidden = false;
viewTabs.classList.remove('hidden');
viewTabs.addEventListener('click', (event) => {
const tab = event.target.closest('[role="tab"][data-view]');
if (tab) {
activateView(tab.dataset.view);
}
});
viewTabs.addEventListener('keydown', (event) => {
const currentIndex = tabs.indexOf(document.activeElement);
if (currentIndex < 0) {
return;
}
const nextIndex = event.key === 'ArrowRight'
? (currentIndex + 1) % tabs.length
: event.key === 'ArrowLeft'
? (currentIndex - 1 + tabs.length) % tabs.length
: event.key === 'Home'
? 0
: event.key === 'End'
? tabs.length - 1
: -1;
if (nextIndex !== -1) {
event.preventDefault();
activateView(tabs[nextIndex].dataset.view, true);
}
});
const applyFormatting = (button) => {
const selection = editor.state.selection.main;
const format = button.dataset.format;
if (format === 'horizontal-rule') {
const line = editor.state.doc.lineAt(selection.from);
const insert = line.text ? '\n\n---' : '---';
editor.dispatch({
changes: { from: line.to, to: line.to, insert },
selection: { anchor: line.to + insert.length },
});
editor.focus();
return;
}
if (format === 'code-block' || format === 'quote') {
const firstLine = editor.state.doc.lineAt(selection.from);
const lastLine = editor.state.doc.lineAt(selection.to);
const selectedText = editor.state.doc.sliceString(firstLine.from, lastLine.to);
const lines = selectedText.split('\n');
const insert = format === 'code-block'
? `\`\`\`\n${selectedText || 'Code block'}\n\`\`\``
: lines.every((line) => line.startsWith('> '))
? lines.map((line) => line.slice(2)).join('\n')
: lines.map((line) => `> ${line || 'Quote'}`).join('\n');
editor.dispatch({
changes: { from: firstLine.from, to: lastLine.to, insert },
selection: format === 'code-block'
? { anchor: firstLine.from + 4, head: firstLine.from + 4 + (selectedText || 'Code block').length }
: { anchor: firstLine.from, head: firstLine.from + insert.length },
});
editor.focus();
return;
}
if (format === 'heading' || format === 'list' || format === 'ordered-list') {
const line = editor.state.doc.lineAt(selection.from);
const prefix = format === 'heading' ? '## ' : format === 'ordered-list' ? '1. ' : '- ';
const hasPrefix = format === 'ordered-list'
? /^\d+[.)]\s/.test(line.text)
: format === 'list'
? /^[-*+]\s/.test(line.text)
: line.text.startsWith(prefix);
const lineText = hasPrefix
? line.text.replace(format === 'ordered-list' ? /^\d+[.)]\s/ : format === 'list' ? /^[-*+]\s/ : /^## /, '')
: `${prefix}${line.text || (format === 'heading' ? 'Heading' : 'List item')}`;
const selectedFrom = line.from + (hasPrefix ? 0 : prefix.length);
editor.dispatch({
changes: { from: line.from, to: line.to, insert: lineText },
selection: { anchor: selectedFrom, head: line.from + lineText.length },
});
editor.focus();
return;
}
const formats = {
bold: ['**', '**', 'bold text'],
italic: ['*', '*', 'italic text'],
link: ['[', '](https://example.com)', 'link text'],
code: ['`', '`', 'code'],
};
const [before, after, placeholder] = formats[format] || [];
if (before === undefined) {
return;
}
const selectedText = editor.state.sliceDoc(selection.from, selection.to);
const text = selectedText || placeholder;
editor.dispatch({
changes: { from: selection.from, to: selection.to, insert: `${before}${text}${after}` },
selection: {
anchor: selection.from + before.length,
head: selection.from + before.length + text.length,
},
});
editor.focus();
};
toolbar.addEventListener('click', (event) => {
const button = event.target.closest('button[data-format]');
if (button) {
applyFormatting(button);
}
});
const form = textarea.form;
form?.addEventListener('submit', () => {
textarea.value = editor.state.doc.toString();
});
const preview = document.getElementById('post-body-preview');
const previewStatus = document.getElementById('post-body-preview-status');
if (form && preview && previewStatus) {
let previewTimer;
let previewRequestId = 0;
let activePreviewRequest = null;
const setPreviewStatus = (message, isError = false) => {
previewStatus.textContent = message;
previewStatus.classList.toggle('text-error', isError);
previewStatus.classList.toggle('text-base-content/60', !isError);
};
const schedulePreview = () => {
window.clearTimeout(previewTimer);
const requestId = ++previewRequestId;
activePreviewRequest?.abort();
activePreviewRequest = null;
preview.replaceChildren();
preview.setAttribute('aria-busy', 'true');
setPreviewStatus('Updating preview…');
previewTimer = window.setTimeout(async () => {
const csrfToken = form.querySelector('[name="_csrf_token"]')?.value || '';
if (!csrfToken) {
if (requestId === previewRequestId) {
setPreviewStatus('Preview unavailable. Your Markdown is unchanged and can still be saved.', true);
preview.setAttribute('aria-busy', 'false');
}
return;
}
const request = new AbortController();
activePreviewRequest = request;
const requestBody = new FormData();
requestBody.set('body', textarea.value);
requestBody.set('_csrf_token', csrfToken);
try {
const response = await fetch('/ext--blog/preview-post', {
method: 'POST',
body: requestBody,
credentials: 'same-origin',
headers: { Accept: 'application/json' },
signal: request.signal,
});
const result = await response.json();
if (requestId !== previewRequestId) {
return;
}
if (!response.ok || !result || typeof result.html !== 'string') {
throw new Error('Preview request failed.');
}
preview.innerHTML = result.html;
window.blogCodeHighlighter?.highlight(preview);
setPreviewStatus(result.html === '' ? 'The post body is empty.' : 'Preview updated.');
} catch (error) {
if (error.name !== 'AbortError' && requestId === previewRequestId) {
setPreviewStatus('Preview unavailable. Your Markdown is unchanged and can still be saved.', true);
}
} finally {
if (requestId === previewRequestId) {
activePreviewRequest = null;
preview.setAttribute('aria-busy', 'false');
}
}
}, 300);
};
textarea.addEventListener('input', schedulePreview);
schedulePreview();
}
window.blogMarkdownEditor = {
insertAtCursor(markdown) {
const selection = editor.state.selection.main;
const document = editor.state.doc;
const before = selection.from > 0 && !/\s/.test(document.sliceString(selection.from - 1, selection.from)) ? ' ' : '';
const after = selection.to < document.length && !/\s/.test(document.sliceString(selection.to, selection.to + 1)) ? ' ' : '';
const insertion = `${before}${markdown}${after}`;
editor.dispatch({
changes: { from: selection.from, to: selection.to, insert: insertion },
selection: { anchor: selection.from + insertion.length },
});
editor.focus();
return true;
},
};
});
@@ -0,0 +1,48 @@
.hljs {
color: var(--color-base-content);
}
.hljs-comment,
.hljs-quote {
opacity: 0.7;
font-style: italic;
}
.hljs-keyword,
.hljs-selector-tag,
.hljs-literal,
.hljs-section {
color: var(--color-primary);
}
.hljs-string,
.hljs-title,
.hljs-name,
.hljs-type,
.hljs-attribute,
.hljs-symbol,
.hljs-bullet,
.hljs-addition {
color: var(--color-success);
}
.hljs-number,
.hljs-regexp,
.hljs-variable,
.hljs-template-variable {
color: var(--color-secondary);
}
.hljs-built_in,
.hljs-class .hljs-title {
color: var(--color-info);
}
.hljs-meta,
.hljs-meta .hljs-keyword {
color: var(--color-warning);
}
.hljs-deletion {
color: var(--color-error);
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,33 @@
import hljs from 'highlight.js/lib/core';
import bash from 'highlight.js/lib/languages/bash';
import css from 'highlight.js/lib/languages/css';
import diff from 'highlight.js/lib/languages/diff';
import javascript from 'highlight.js/lib/languages/javascript';
import json from 'highlight.js/lib/languages/json';
import markdown from 'highlight.js/lib/languages/markdown';
import php from 'highlight.js/lib/languages/php';
import python from 'highlight.js/lib/languages/python';
import sql from 'highlight.js/lib/languages/sql';
import typescript from 'highlight.js/lib/languages/typescript';
import xml from 'highlight.js/lib/languages/xml';
import yaml from 'highlight.js/lib/languages/yaml';
Object.entries({ bash, css, diff, javascript, json, markdown, php, python, sql, typescript, xml, yaml })
.forEach(([name, language]) => hljs.registerLanguage(name, language));
window.blogCodeHighlighter = {
highlight(root = document) {
root.querySelectorAll('pre code:not(.hljs)').forEach((code) => {
const language = code.className.match(/(?:^|\s)language-([^\s]+)/)?.[1];
if (language && !hljs.getLanguage(language)) return;
hljs.highlightElement(code);
});
},
};
const highlightPage = () => window.blogCodeHighlighter.highlight(document);
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', highlightPage, { once: true });
} else {
highlightPage();
}
@@ -1,6 +1,7 @@
<?php
$slug = phpb_route_parameter('slug');
$timezone = new \DateTimeZone((string) (phpb_config('general.timezone') ?: 'UTC'));
$post = is_string($slug) && $slug !== ''
? (new \Plugi\Extensions\Blog\PostsRepository())->findPublishedBySlug($slug)
: null;
@@ -20,9 +21,9 @@ $post = is_string($slug) && $slug !== ''
<span class="badge badge-outline"><?= phpb_e($post['category_name']) ?></span>
<?php endif; ?>
<?php if (!empty($post['published_at'])): ?>
<?php $publishedTimestamp = strtotime($post['published_at']); ?>
<?php if ($publishedTimestamp !== false): ?>
<time datetime="<?= phpb_e(date('c', $publishedTimestamp)) ?>"><?= phpb_e(date('F j, Y', $publishedTimestamp)) ?></time>
<?php $publishedDate = date_create($post['published_at'], $timezone); ?>
<?php if ($publishedDate !== false): ?>
<time datetime="<?= phpb_e($publishedDate->format('c')) ?>"><?= phpb_e($publishedDate->format('F j, Y')) ?></time>
<?php endif; ?>
<?php endif; ?>
</div>
@@ -31,6 +32,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; ?>
@@ -1,23 +1,55 @@
<?php
$posts = (new \Plugi\Extensions\Blog\PostsRepository())->getPublishedForListing();
$postsRepository = new \Plugi\Extensions\Blog\PostsRepository();
$timezone = new \DateTimeZone((string) (phpb_config('general.timezone') ?: 'UTC'));
$search = is_string($_GET['q'] ?? null) ? trim($_GET['q']) : '';
$pageValue = $_GET['page'] ?? null;
$page = is_string($pageValue) ? filter_var($pageValue, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) : false;
$page = $page === false ? 1 : $page;
$listingPath = isset($_SERVER['SERVER_NAME'], $_SERVER['REQUEST_URI']) ? phpb_full_url(phpb_current_relative_url(true)) : '/';
$pageResult = $postsRepository->getPageForListing($search, $page);
$searchTooShort = $search !== '' && mb_strlen($search) < \Plugi\Extensions\Blog\PostsRepository::MIN_PUBLIC_SEARCH_LENGTH;
$totalPages = max(1, (int) ceil($pageResult['total'] / \Plugi\Extensions\Blog\PostsRepository::POSTS_PER_PAGE));
if ($page > $totalPages) {
$page = $totalPages;
}
$posts = $pageResult['posts'];
$searchParameters = $search === '' ? [] : ['q' => $search];
?>
<section class="space-y-6" aria-label="Blog posts">
<?php if (empty($posts)): ?>
<div class="alert alert-info" role="status">No published posts yet.</div>
<form class="flex flex-col gap-3 sm:flex-row sm:items-end" method="get" action="<?= phpb_e($listingPath) ?>">
<label class="flex w-full max-w-md flex-col gap-2">
<span class="text-sm font-medium">Search titles, slugs, and excerpts (3+ characters)</span>
<input class="input w-full" type="search" name="q" value="<?= phpb_e($search) ?>" />
</label>
<button class="btn" type="submit">Search</button>
</form>
<?php if ($searchTooShort): ?>
<div class="alert alert-info" role="status">Enter at least <?= \Plugi\Extensions\Blog\PostsRepository::MIN_PUBLIC_SEARCH_LENGTH ?> characters to search.</div>
<?php elseif ($pageResult['total'] === 0): ?>
<div class="alert alert-info" role="status">
<?= $search === '' ? 'No published posts yet.' : 'No published posts match &quot;' . phpb_e($search) . '&quot;.' ?>
</div>
<?php else: ?>
<div class="grid gap-6 md:grid-cols-2">
<?php foreach ($posts as $post): ?>
<article class="card h-full border border-base-300 bg-base-100 shadow-sm">
<?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'])): ?>
<span class="badge badge-outline"><?= phpb_e($post['category_name']) ?></span>
<?php endif; ?>
<?php if (!empty($post['published_at'])): ?>
<?php $publishedTimestamp = strtotime($post['published_at']); ?>
<?php if ($publishedTimestamp !== false): ?>
<time datetime="<?= phpb_e(date('c', $publishedTimestamp)) ?>"><?= phpb_e(date('F j, Y', $publishedTimestamp)) ?></time>
<?php $publishedDate = date_create($post['published_at'], $timezone); ?>
<?php if ($publishedDate !== false): ?>
<time datetime="<?= phpb_e($publishedDate->format('c')) ?>"><?= phpb_e($publishedDate->format('F j, Y')) ?></time>
<?php endif; ?>
<?php endif; ?>
</div>
@@ -38,4 +70,22 @@ $posts = (new \Plugi\Extensions\Blog\PostsRepository())->getPublishedForListing(
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php if ($totalPages > 1): ?>
<nav class="flex justify-center" aria-label="Blog post pages">
<div class="join">
<?php if ($page > 1): ?>
<a class="join-item btn btn-sm" rel="prev" href="<?= phpb_e($listingPath . '?' . http_build_query($searchParameters + ['page' => $page - 1])) ?>">Previous</a>
<?php else: ?>
<span class="join-item btn btn-sm btn-disabled" aria-disabled="true">Previous</span>
<?php endif; ?>
<span class="join-item btn btn-sm btn-disabled" aria-current="page">Page <?= phpb_e($page) ?> of <?= phpb_e($totalPages) ?></span>
<?php if ($page < $totalPages): ?>
<a class="join-item btn btn-sm" rel="next" href="<?= phpb_e($listingPath . '?' . http_build_query($searchParameters + ['page' => $page + 1])) ?>">Next</a>
<?php else: ?>
<span class="join-item btn btn-sm btn-disabled" aria-disabled="true">Next</span>
<?php endif; ?>
</div>
</nav>
<?php endif; ?>
</section>
+17
View File
@@ -0,0 +1,17 @@
import { rolldown } from 'rolldown';
const bundle = await rolldown({ input: 'admin/assets/src/markdown-editor.js' });
await bundle.write({
file: 'admin/assets/markdown-editor.js',
format: 'iife',
sourcemap: true,
minify: true,
});
const highlighterBundle = await rolldown({ input: 'assets/src/code-highlighter.js' });
await highlighterBundle.write({
file: 'assets/code-highlighter.js',
format: 'iife',
sourcemap: true,
minify: true,
});
+33
View File
@@ -6,6 +6,38 @@ return [
'identifier' => 'blog',
'licence' => 'MIT',
'version' => '1.0.0',
'assets' => [
[
'src' => '/assets/code-highlighter.css',
'type' => 'style',
'location' => 'footer',
],
[
'src' => '/assets/code-highlighter.js',
'type' => 'script',
'location' => 'footer',
],
[
'src' => '/assets/code-highlighter.css',
'type' => 'style',
'location' => 'admin-header',
],
[
'src' => '/assets/code-highlighter.js',
'type' => 'script',
'location' => 'admin-header',
],
[
'src' => '/admin/assets/markdown-editor.css',
'type' => 'style',
'location' => 'admin-header',
],
[
'src' => '/admin/assets/markdown-editor.js',
'type' => 'script',
'location' => 'admin-header',
],
],
'tables' => [
'posts' => [
'columns' => [
@@ -13,6 +45,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',
+1
View File
@@ -4,6 +4,7 @@ use Plugi\Extensions;
Extensions::addRoutes([
'/ext--blog/save-post' => __DIR__ . '/routes/savePost.php',
'/ext--blog/preview-post' => __DIR__ . '/routes/previewPost.php',
'/ext--blog/delete-post' => __DIR__ . '/routes/deletePost.php',
'/ext--blog/save-category' => __DIR__ . '/routes/saveCategory.php',
'/ext--blog/delete-category' => __DIR__ . '/routes/deleteCategory.php',
+582
View File
@@ -0,0 +1,582 @@
{
"name": "plugi-ext-blog",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "plugi-ext-blog",
"dependencies": {
"@codemirror/commands": "^6.11.2",
"@codemirror/lang-markdown": "^6.5.3",
"@codemirror/language": "^6.13.1",
"@codemirror/view": "^6.44.2",
"@lezer/highlight": "^1.2.5",
"highlight.js": "^11.11.1"
},
"devDependencies": {
"rolldown": "^1.3.3"
}
},
"node_modules/@codemirror/autocomplete": {
"version": "6.20.4",
"resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.4.tgz",
"integrity": "sha512-yF8RhOf2SXlg00+qtupzLhrglcas61boqaONiNcbPIebHCpJocpqTBA6dyrtUrQO47hqyTdeob/3XnYilT7TaQ==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0"
}
},
"node_modules/@codemirror/commands": {
"version": "6.11.2",
"resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.11.2.tgz",
"integrity": "sha512-NbH6Q9lmcXvf9s5/mMJIwL2Hjl2NEdsN/dDlezGnaFOQgNZ59dT7ndKUf21/PIjJacD/Ti2Ifi4TsBkO6WHvsg==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.7.0",
"@codemirror/view": "^6.27.0",
"@lezer/common": "^1.1.0"
}
},
"node_modules/@codemirror/lang-css": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz",
"integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@lezer/common": "^1.0.2",
"@lezer/css": "^1.1.7"
}
},
"node_modules/@codemirror/lang-html": {
"version": "6.4.12",
"resolved": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.12.tgz",
"integrity": "sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/lang-css": "^6.0.0",
"@codemirror/lang-javascript": "^6.0.0",
"@codemirror/language": "^6.4.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0",
"@lezer/css": "^1.1.0",
"@lezer/html": "^1.3.12"
}
},
"node_modules/@codemirror/lang-javascript": {
"version": "6.2.5",
"resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz",
"integrity": "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.6.0",
"@codemirror/lint": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0",
"@lezer/javascript": "^1.0.0"
}
},
"node_modules/@codemirror/lang-markdown": {
"version": "6.5.3",
"resolved": "https://registry.npmjs.org/@codemirror/lang-markdown/-/lang-markdown-6.5.3.tgz",
"integrity": "sha512-gNfFYi5jS6JkWD5kLW3cXB3g2uMYec9wzjYurMLDHeB0P2Ppc/Qe8UtDv7EBR5BzPQbkaW3/50+7qLtS//1Pqw==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.7.1",
"@codemirror/lang-html": "^6.0.0",
"@codemirror/language": "^6.3.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.0.0",
"@lezer/common": "^1.2.1",
"@lezer/markdown": "^1.0.0"
}
},
"node_modules/@codemirror/language": {
"version": "6.13.1",
"resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.13.1.tgz",
"integrity": "sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/streamparser": "^6.0.0",
"@codemirror/view": "^6.23.0",
"@lezer/common": "^1.5.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0",
"style-mod": "^4.0.0"
}
},
"node_modules/@codemirror/lint": {
"version": "6.9.8",
"resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.8.tgz",
"integrity": "sha512-qNvtcE73xUto/D1RvtgSRI4A1Hg8ekxlvtZpjHpdpisLBnhyu82EUEJMEgaxkjuQCA8vqnrylENWKOsEDCOHcw==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.42.0",
"crelt": "^1.0.5"
}
},
"node_modules/@codemirror/state": {
"version": "6.7.6",
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.6.tgz",
"integrity": "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==",
"license": "MIT",
"dependencies": {
"@marijn/find-cluster-break": "^1.0.0"
}
},
"node_modules/@codemirror/streamparser": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/@codemirror/streamparser/-/streamparser-6.0.0.tgz",
"integrity": "sha512-JTFPF6xrfjt0mnfGPgzcLiMwYmvIyNaoizp8BYzv8FE8KrT6GBGDZ190rtt+O7Wke3gG/MFHyiY9YGNeimof4w==",
"license": "MIT"
},
"node_modules/@codemirror/view": {
"version": "6.44.2",
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.44.2.tgz",
"integrity": "sha512-7yxTh7+iCbxIV9QCJAVlkYjWV/TCHD0zmLIaIR3NOb47YpCWwVUuFUnHwkRC3z+8cXNgeJzrCy4QtlR3fVt5kg==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.7.0",
"crelt": "^1.0.6",
"style-mod": "^4.1.0",
"w3c-keyname": "^2.2.4"
}
},
"node_modules/@lezer/common": {
"version": "1.5.7",
"resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.7.tgz",
"integrity": "sha512-3+3PN+M/3xSjrlQz8/wBPOl+JYGJ+G37ZszHfnhphFwj41qPUPxsz4WEic3ZyVpL23rX1qefaGqz0lA7jGUqwg==",
"license": "MIT"
},
"node_modules/@lezer/css": {
"version": "1.3.9",
"resolved": "https://registry.npmjs.org/@lezer/css/-/css-1.3.9.tgz",
"integrity": "sha512-ZmzgvTOBdJWGIsY/ItAfN7UW8DV802oZG+jeG6E508SwEzz5YhuAajptpWPICvIyqYAD2+VjMdOS40GgGkyEOQ==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.3.0"
}
},
"node_modules/@lezer/highlight": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.5.tgz",
"integrity": "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.3.0"
}
},
"node_modules/@lezer/html": {
"version": "1.3.13",
"resolved": "https://registry.npmjs.org/@lezer/html/-/html-1.3.13.tgz",
"integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0"
}
},
"node_modules/@lezer/javascript": {
"version": "1.5.7",
"resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.7.tgz",
"integrity": "sha512-o3Rn+TzKuN25sdILOZFXi8hz4K/ed4OK0I+QrAi7Zzn3tXRBZmfsQrZpLX47ZYK/rZU8Vu4jLkz4SOSYRzBfjw==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.1.3",
"@lezer/lr": "^1.3.0"
}
},
"node_modules/@lezer/lr": {
"version": "1.4.13",
"resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.13.tgz",
"integrity": "sha512-Ez6qF9rXdnR/7hTcA6kHq1uTcPV+17hyUFjiHBVYNi0a81TgbkC0SwiNvxcuUMkvX7phuhTHo+QAXh9L2kjGdg==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.0.0"
}
},
"node_modules/@lezer/markdown": {
"version": "1.8.3",
"resolved": "https://registry.npmjs.org/@lezer/markdown/-/markdown-1.8.3.tgz",
"integrity": "sha512-rI5BN6IpWmigtUPwvWvFck8/nptMhyYshEKCnyponMu8B+lBlt1d9rMbwHm4ejS+wd1fwd6P7hgAWZirfZ1lYg==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.5.0",
"@lezer/highlight": "^1.0.0"
}
},
"node_modules/@marijn/find-cluster-break": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz",
"integrity": "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==",
"license": "MIT"
},
"node_modules/@oxc-project/types": {
"version": "0.160.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.160.0.tgz",
"integrity": "sha512-gw4k9syEmnckbOgw2A2FU1TBDdX9hfwV9jEn/uio65pguPzwWiXQS3OIJDMEhv9m06tj9XiEe6RoD0YA+LgreA==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/oxc-project"
}
},
"node_modules/@rolldown/binding-android-arm-eabi": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.3.4.tgz",
"integrity": "sha512-xCW8CkL/ualx/SbYqeG9iK87lJCZGDQ0soE+kaORJ0Bd+pHALyE4qK7BStmEAyYWLEzZ3/biSIpA6/7GDFvzIg==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-android-arm64": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.3.4.tgz",
"integrity": "sha512-5lifIO+b/prcM9sx/bkPN4w6UEToEfQ3gjhx0+0neuL+dkYskI792CfAq03T51jc8JFcaYXs2hi3l8RjiH/VWQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-darwin-arm64": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.3.4.tgz",
"integrity": "sha512-RCgxTI4AJQxhVF//BI3ImQOsXTHrF4Eg+f99jBy8WoETA2kSEGFxpnrVmW0leQq/2aBR4R5AC6csmy3rc66e3Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-darwin-x64": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.3.4.tgz",
"integrity": "sha512-zNPJVVPUaDEj+L0lImoK3rFv2b+Z5gNijI6DWu/fcD3/1TfmRXKb9ZyxbSN+2AhlctqjbNzUvCsMa+EBhnEM4Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-freebsd-x64": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.3.4.tgz",
"integrity": "sha512-upP6g7ZIRy5by1RDQ/EphHIdJ5xK0eUD7sUgfZFWJ49s4XdbYsIvIlAPtrFpayR70Hhf9J22lb4Pm8/9FhrZmg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-arm-gnueabihf": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.3.4.tgz",
"integrity": "sha512-SAX5C5+poMLCxu8dkPF6h5yst40rkzs+9Y3cbPn2OFSydmHjAEprrGi64zGgnYyPIVZfdGUFqJ2fJbfbnHI+mA==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-arm64-gnu": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.3.4.tgz",
"integrity": "sha512-nwHqdlRZS6GWBef3dG5/pMY6RNTBBUjj7s0Da+m6xsFpe7jx6IC46SLZcCu8f46JOfCovZmwnrz51EzGE+7Fyw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-arm64-musl": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.3.4.tgz",
"integrity": "sha512-Gr78X2ur/AgLCkmZgHffk/FerIX8S5zb/eII4bCcvJo0ANzeXhTShahdNbpnY6bpiszIAgIfiuKS9ziziWsamw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-ppc64-gnu": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.3.4.tgz",
"integrity": "sha512-o9Wcn8nWrsQasaBRYM4d//FwhlBsTJYWkPVlhlt6FwzpwEoovY4IopRZjk5Fq3+ntRuSDORJjF/nA8sFeF2q6w==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-s390x-gnu": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.3.4.tgz",
"integrity": "sha512-UDWu4jkVcx2kiBKm3Ec//4lVCbeTWj8gmJ9SyLWCdLWtTlyq7fQVeVV/14nXvRtSLErvJ2+yA/Ux5taS31Y17Q==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-x64-gnu": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.3.4.tgz",
"integrity": "sha512-W9mGtTa0w4fWh8RLMNPyaEhhcuqUfO07Q4I1bBc4PDMNg7gQSw0yPQNQ3D0qwbkXwxbyL4YrIzc8n6k1vuFExQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-x64-musl": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.3.4.tgz",
"integrity": "sha512-8B+ofyQZ7/aCmkqnyMonPr5zKLqMVNczhRGFNtdIuItiwNn8iQWJawMq2E58r7bxD1XEbtRRsULY/eCWwZQ01Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-openharmony-arm64": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.3.4.tgz",
"integrity": "sha512-TlD0FSZaC7o2B4NCe9V5N11ugTnhzTM9ksj4sgRLvrKosDzjEkvlsTX3ehkw4ZlPv8AADimZZTvJGEa16pfXug==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-wasm32-wasi": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.3.4.tgz",
"integrity": "sha512-jwO8P3o53ygo7b5061B7BeaJ1BGv3BKZ6jroFdw/01qWry7Z+qNBlDvulzbTle5s/A0Fc1FRgsTxrke9DvsSbA==",
"cpu": [
"wasm32"
],
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@oxc-project/types": "0.160.0"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
}
},
"node_modules/@rolldown/binding-win32-arm64-msvc": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.3.4.tgz",
"integrity": "sha512-8adGMrNtrdzi2WD1ozhYapER59gD8Q/DV6SCKJlyG2HqULPdeQUBvMa33lTsiEYwIqTZUaIU2MmvPp5f1wbtXA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-win32-x64-msvc": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.3.4.tgz",
"integrity": "sha512-rIMjtESdXJCIoOiUTroQ1Y1rjVDZkuUVRUxs3APX2vNv175D7TDWvzdELiIhzGq9cUNUFat+co+PTmPHPqSREg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/pluginutils": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz",
"integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==",
"dev": true,
"license": "MIT"
},
"node_modules/crelt": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz",
"integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==",
"license": "MIT"
},
"node_modules/highlight.js": {
"version": "11.12.0",
"resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.12.0.tgz",
"integrity": "sha512-nbfWpyRMcMrPMmDwJB+dhX/eiaPKtc2RB+0QZskqJ3WjRA/FDS0e9hZrx8EC/lbEv8gXy98FcDbNa/dspAaJMg==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/rolldown": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.4.tgz",
"integrity": "sha512-p2rq4bfBmF0M6yaR8+A89fbkBQynZI2fxUW4G07eq9kpctAkpo7q5BZ4X4Mo4XZ7HHROu33cX9PeopUFN6u+2Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"@oxc-project/types": "=0.160.0",
"@rolldown/pluginutils": "^1.0.0"
},
"bin": {
"rolldown": "bin/cli.mjs"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"optionalDependencies": {
"@rolldown/binding-android-arm-eabi": "1.3.4",
"@rolldown/binding-android-arm64": "1.3.4",
"@rolldown/binding-darwin-arm64": "1.3.4",
"@rolldown/binding-darwin-x64": "1.3.4",
"@rolldown/binding-freebsd-x64": "1.3.4",
"@rolldown/binding-linux-arm-gnueabihf": "1.3.4",
"@rolldown/binding-linux-arm64-gnu": "1.3.4",
"@rolldown/binding-linux-arm64-musl": "1.3.4",
"@rolldown/binding-linux-ppc64-gnu": "1.3.4",
"@rolldown/binding-linux-s390x-gnu": "1.3.4",
"@rolldown/binding-linux-x64-gnu": "1.3.4",
"@rolldown/binding-linux-x64-musl": "1.3.4",
"@rolldown/binding-openharmony-arm64": "1.3.4",
"@rolldown/binding-wasm32-wasi": "1.3.4",
"@rolldown/binding-win32-arm64-msvc": "1.3.4",
"@rolldown/binding-win32-x64-msvc": "1.3.4"
}
},
"node_modules/style-mod": {
"version": "4.1.5",
"resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.5.tgz",
"integrity": "sha512-WQ2llCZa9sZSkJA+aOwpg5DkfbAXFKGh//t3MRTBeruFiSBC+GXUmbBzrw3bXyboCWAbtCW9InDfBsXrRD/rAg==",
"license": "MIT"
},
"node_modules/w3c-keyname": {
"version": "2.2.8",
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
"integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
"license": "MIT"
}
}
}
+19
View File
@@ -0,0 +1,19 @@
{
"name": "plugi-ext-blog",
"type": "module",
"dependencies": {
"@codemirror/commands": "^6.11.2",
"@codemirror/lang-markdown": "^6.5.3",
"@codemirror/language": "^6.13.1",
"@codemirror/view": "^6.44.2",
"@lezer/highlight": "^1.2.5",
"highlight.js": "^11.11.1"
},
"devDependencies": {
"rolldown": "^1.3.3"
},
"scripts": {
"build": "node build.js",
"test": "node --test tests/CodeHighlighterTest.js"
}
}
@@ -0,0 +1,35 @@
<?php
phpb_requires_authenticated();
$respond = static function (int $status, array $payload): void {
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
};
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
$respond(405, ['error' => 'Preview requests must use POST.']);
return;
}
if (!phpb_validate_csrf()) {
$respond(403, ['error' => 'The preview request could not be verified.']);
return;
}
$body = $_POST['body'] ?? null;
if (!is_string($body)) {
$respond(400, ['error' => 'A Markdown body is required.']);
return;
}
if (strlen($body) > 1000000) {
$respond(413, ['error' => 'The Markdown body is too large to preview.']);
return;
}
try {
$html = (new \Plugi\Extensions\Blog\PostContentRenderer())->render($body);
$respond(200, ['html' => $html]);
} catch (\Throwable) {
$respond(500, ['error' => 'The Markdown preview could not be rendered.']);
}
@@ -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) {
@@ -0,0 +1,118 @@
<?php
namespace Plugi\Extensions\Blog {
class PostsRepository
{
public static int $instances = 0;
public function __construct()
{
self::$instances++;
throw new \RuntimeException('Preview must not access the posts repository.');
}
}
}
namespace {
require_once dirname(__DIR__) . '/admin/Classes/PostContentRenderer.php';
function assertPreviewRoute(bool $condition, string $message): void
{
if (!$condition) {
throw new RuntimeException($message);
}
}
$previewMarkdown = "## Preview\n\nSafe **source**.\n\n- list item\n\n---\n\n> Quoted text.\n\n```php\n<code>safe</code>\n```\n\n~~~php\" onclick=\"alert(1)\n<script>alert(1)</script>\n~~~";
if (($argv[1] ?? '') === '--child') {
$scenario = $argv[2] ?? '';
$GLOBALS['previewAuthenticated'] = $scenario !== 'unauthenticated';
$GLOBALS['previewCsrfValid'] = $scenario !== 'invalid-csrf';
function phpb_requires_authenticated(): void
{
if (!$GLOBALS['previewAuthenticated']) {
http_response_code(403);
exit();
}
}
function phpb_validate_csrf(): bool
{
return $GLOBALS['previewCsrfValid'];
}
register_shutdown_function(static function (): void {
echo "\n__STATUS__" . http_response_code() . "\n";
echo '__REPOSITORY_INSTANTIATIONS__' . \Plugi\Extensions\Blog\PostsRepository::$instances . "\n";
});
$_SERVER['REQUEST_METHOD'] = $scenario === 'non-post' ? 'GET' : 'POST';
$_POST = match ($scenario) {
'invalid-body' => ['body' => ['not', 'markdown']],
'oversized-body' => ['body' => str_repeat('x', 1000001)],
default => ['body' => $previewMarkdown],
};
include dirname(__DIR__) . '/routes/previewPost.php';
exit();
}
function requestPreviewRoute(string $scenario): array
{
$process = proc_open(
[PHP_BINARY, __FILE__, '--child', $scenario],
[0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']],
$pipes,
dirname(__DIR__, 3)
);
if (!is_resource($process)) {
throw new RuntimeException('Could not start the preview route test process.');
}
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
$error = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exitCode = proc_close($process);
if ($exitCode !== 0 || !preg_match('/\n__STATUS__(\d+)\n__REPOSITORY_INSTANTIATIONS__(\d+)\n$/', $output, $matches)) {
throw new RuntimeException('Preview route subprocess failed: ' . $error . $output);
}
$responseLength = strpos($output, "\n__STATUS__");
return [
'status' => (int) $matches[1],
'repository_instances' => (int) $matches[2],
'body' => substr($output, 0, $responseLength),
];
}
foreach ([
'unauthenticated' => 403,
'non-post' => 405,
'invalid-csrf' => 403,
'invalid-body' => 400,
'oversized-body' => 413,
] as $scenario => $expectedStatus) {
$response = requestPreviewRoute($scenario);
assertPreviewRoute($response['status'] === $expectedStatus, 'The preview route should reject ' . $scenario . ' requests.');
assertPreviewRoute($response['repository_instances'] === 0, 'Rejected preview requests must not access saved posts.');
if ($scenario !== 'unauthenticated') {
$payload = json_decode($response['body'], true);
assertPreviewRoute(is_array($payload) && isset($payload['error']), 'Rejected preview requests should return a JSON error.');
}
}
$response = requestPreviewRoute('valid');
$payload = json_decode($response['body'], true);
$expectedHtml = (new \Plugi\Extensions\Blog\PostContentRenderer())->render($previewMarkdown);
assertPreviewRoute($response['status'] === 200, 'A valid preview request should succeed.');
assertPreviewRoute($payload === ['html' => $expectedHtml], 'The preview should return shared renderer output as JSON.');
assertPreviewRoute(str_contains($payload['html'], '<ul class="list-disc') && str_contains($payload['html'], '<hr class="my-6 border-base-300">') && str_contains($payload['html'], '<blockquote') && str_contains($payload['html'], '<pre'), 'The live preview should render lists, horizontal rules, quotes, and code blocks.');
assertPreviewRoute(str_contains($payload['html'], '<code class="language-php">&lt;code&gt;safe&lt;/code&gt;</code>') && str_contains($payload['html'], '<code>&lt;script&gt;alert(1)&lt;/script&gt;</code>') && !str_contains($payload['html'], 'onclick='), 'The preview should keep safe language metadata, reject malformed labels, and escape code.');
assertPreviewRoute($response['repository_instances'] === 0, 'Preview rendering must not read or write saved posts.');
fwrite(STDOUT, "Blog preview route tests passed.\n");
}
@@ -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,
@@ -110,12 +125,40 @@ function renderBlogDetail(?string $slug): string
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_';
$siteTimezone = 'Pacific/Kiritimati';
date_default_timezone_set('Pacific/Pago_Pago');
$phpb_config = ['website_manager' => ['url' => '/website-manager'], 'general' => ['uploads_url' => '/uploads', 'timezone' => $siteTimezone]];
$phpb_db = new BlogTestDatabase();
$phpb_db->createSchema();
assertBlog(isset($phpb_db->getDBDefinition()['ext__blog_posts'], $phpb_db->getDBDefinition()['ext__blog_categories']), 'The blog tables should be included in the core database definition.');
assertBlog(isset(\Plugi\Extensions::getBackends()['ext--blog']), 'The blog admin backend should be registered.');
assertBlog(count(array_intersect(['/ext--blog/save-post', '/ext--blog/delete-post', '/ext--blog/save-category', '/ext--blog/delete-category'], array_keys(\Plugi\Extensions::getRoutes()))) === 4, 'Blog CRUD routes should be registered.');
assertBlog(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.');
@@ -124,29 +167,45 @@ $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.');
$storedPublication = \DateTimeImmutable::createFromFormat('!Y-m-d H:i:s', $post['published_at'], new \DateTimeZone($siteTimezone));
assertBlog($storedPublication !== false && abs($storedPublication->getTimestamp() - time()) < 60, 'The automatic publication timestamp should use the configured site timezone.');
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\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);
$pastPublication = (new \DateTimeImmutable('now', new \DateTimeZone($siteTimezone)))->modify('-1 hour')->format('Y-m-d\\TH:i');
$datedPost = $posts->create([
'title' => 'Dated draft',
'slug' => 'dated-draft',
@@ -165,19 +224,56 @@ $secondPost = $posts->create([
'status' => 'draft',
'published_at' => '',
]);
$publishedPosts = $posts->getPublishedForListing();
assertBlog(count($publishedPosts) === 2, 'The public listing should exclude drafts.');
assertBlog($publishedPosts[0]['slug'] === $post['slug'] && $publishedPosts[0]['category_name'] === 'News', 'Published posts should be newest first and include their category name.');
assertBlog($publishedPosts[1]['slug'] === $olderPost['slug'], 'Older published posts should follow newer posts.');
$_ENV['BASE_URL'] = 'https://blog.example';
$editorHtml = renderBlogEditor((int) $post['id']);
assertBlog(str_contains($editorHtml, 'site timezone (Pacific/Kiritimati)'), 'The editor should identify the timezone used for publication dates.');
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 &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.');
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, 'datetime="2020-01-01T00:00:00+14:00"'), 'Public listing dates should use the configured site timezone.');
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, 'datetime="2020-01-01T00:00:00+14:00"'), 'Public detail dates should use the configured site timezone.');
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, '<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">&lt;script&gt;alert(&quot;code&quot;)&lt;/script&gt;</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>&lt;script&gt;alert(1)&lt;/script&gt;</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 &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.');
@@ -185,11 +281,12 @@ assertBlog(str_contains(renderBlogDetail('second-post'), 'Article not found'), '
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),
'title' => 'Future date', 'slug' => 'future-date', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => (new \DateTimeImmutable('now', new \DateTimeZone($siteTimezone)))->modify('+1 day')->format('Y-m-d\\TH:i'),
]), 'Future publication dates should be rejected.');
$updated = $posts->update(['id' => $post['id']], [
@@ -197,13 +294,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.');
@@ -233,7 +331,122 @@ assertBlog($posts->findWithId($secondPost['id'])['category_id'] === null, 'Delet
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'], 'general' => ['uploads_url' => '/uploads', 'timezone' => $siteTimezone]];
$_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($field === 'body' ? $publicMatch['total'] === 0 : $publicMatch['total'] === 1 && $publicMatch['posts'][0]['slug'] === $fieldPost['slug'], 'Public search should match only title, slug, and excerpt fields.');
}
$shortPublicSearch = $posts->getPageForListing('po', 1);
assertBlog($shortPublicSearch['total'] === 0 && $shortPublicSearch['posts'] === [], 'Public search should ignore queries shorter than three characters.');
$_GET = ['q' => 'po'];
assertBlog(str_contains(renderBlogListing(), 'Enter at least 3 characters to search.'), 'The public listing should explain the minimum search length.');
$_GET = [];
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&amp;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 &quot;no-such-post&quot;') && !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&amp;action=posts&amp;q=pagination&amp;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 &quot;no-such-post&quot;') && !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");
@@ -0,0 +1,44 @@
import assert from 'node:assert/strict';
import test from 'node:test';
const createCodeBlock = (className, text) => {
const classes = new Set(className.split(/\s+/).filter(Boolean));
const code = {
className: [...classes].join(' '),
children: [],
dataset: {},
innerHTML: '',
textContent: text,
classList: {
add(name) {
classes.add(name);
code.className = [...classes].join(' ');
},
},
};
return code;
};
globalThis.document = { readyState: 'complete', querySelectorAll: () => [] };
globalThis.window = {};
await import('../assets/src/code-highlighter.js');
test('unsupported language labels remain plain without interrupting later blocks', () => {
const unsupported = createCodeBlock('language-not-a-language', '<?php echo 1;');
const supported = createCodeBlock('language-php', '<?php echo 1;');
const warnings = [];
const originalWarn = console.warn;
console.warn = (...args) => warnings.push(args);
try {
window.blogCodeHighlighter.highlight({ querySelectorAll: () => [unsupported, supported] });
} finally {
console.warn = originalWarn;
}
assert.deepEqual(warnings, []);
assert.equal(unsupported.className, 'language-not-a-language');
assert.deepEqual(unsupported.dataset, {});
assert.equal(supported.dataset.highlighted, 'yes');
assert.match(supported.innerHTML, /<span class="hljs-/);
});
@@ -17,6 +17,10 @@ if(isset($_GET['id']))
$form = $formsRepository->findWithId($_GET['id']);
$isEditing = isset($form['id']) && $form['id'] > 0;
$fieldsJson = json_encode(json_decode($form['fields']) ?? [], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
$finishersJson = json_encode(json_decode($form['finishers']) ?? [], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
$fieldsJson = $fieldsJson === false ? '[]' : $fieldsJson;
$finishersJson = $finishersJson === false ? '[]' : $finishersJson;
?>
<header class="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
@@ -34,8 +38,8 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
</header>
<script>
const fields = <?= $form["fields"] ?>;
const finishers = <?= $form["finishers"] ?>;
const fields = <?= $fieldsJson ?>;
const finishers = <?= $finishersJson ?>;
const finisherDefinitions = <?= json_encode($finisherDefinitions, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;
</script>
@@ -102,6 +106,7 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
this.fields.splice(toIndex, 0, field);
}
}">
<?php phpb_csrf_field(); ?>
<?php
if(isset($form['id'])) echo '<input type="hidden" name="id" value="'.$form['id'].'">';
?>
@@ -75,9 +75,14 @@ $entries = $entriesRepository->findWhere('formId', $id);
<?php endforeach; ?>
<td>
<div class="flex justify-end">
<a href="/ext--form/delete-entry?id=<?= $entry['id'] ?>&formId=<?= $id ?>" class="btn btn-ghost btn-square btn-sm text-error" title="<?= phpb_trans('website-manager.remove') ?>" aria-label="<?= phpb_trans('website-manager.remove') ?> submission <?= phpb_e($entry['id']) ?>">
<i class="ph-duotone ph-trash text-lg" aria-hidden="true"></i>
</a>
<form action="/ext--form/delete-entry" method="post">
<?php phpb_csrf_field(); ?>
<input type="hidden" name="id" value="<?= phpb_e((string) $entry['id']) ?>">
<input type="hidden" name="formId" value="<?= phpb_e((string) $id) ?>">
<button type="submit" class="btn btn-ghost btn-square btn-sm text-error" title="<?= phpb_trans('website-manager.remove') ?>" aria-label="<?= phpb_trans('website-manager.remove') ?> submission <?= phpb_e($entry['id']) ?>">
<i class="ph-duotone ph-trash text-lg" aria-hidden="true"></i>
</button>
</form>
</div>
</td>
</tr>
@@ -58,9 +58,13 @@ $forms = $formsRepository->getAll();
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'editForm', 'id' => $form['id']]) ?>" class="btn btn-ghost btn-square btn-sm" title="<?= phpb_trans('website-manager.edit') ?>" aria-label="<?= phpb_trans('website-manager.edit') ?> <?= phpb_e($form['name']) ?>">
<i class="ph-duotone ph-pencil-line text-lg" aria-hidden="true"></i>
</a>
<a href="/ext--form/delete-form?id=<?= $form['id'] ?>" class="btn btn-ghost btn-square btn-sm text-error" title="<?= phpb_trans('website-manager.remove') ?>" aria-label="<?= phpb_trans('website-manager.remove') ?> <?= phpb_e($form['name']) ?>">
<i class="ph-duotone ph-trash text-lg" aria-hidden="true"></i>
</a>
<form action="/ext--form/delete-form" method="post">
<?php phpb_csrf_field(); ?>
<input type="hidden" name="id" value="<?= phpb_e((string) $form['id']) ?>">
<button type="submit" class="btn btn-ghost btn-square btn-sm text-error" title="<?= phpb_trans('website-manager.remove') ?>" aria-label="<?= phpb_trans('website-manager.remove') ?> <?= phpb_e($form['name']) ?>">
<i class="ph-duotone ph-trash text-lg" aria-hidden="true"></i>
</button>
</form>
</div>
</td>
</tr>
@@ -1,11 +1,20 @@
<?php
phpb_requires_authenticated();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
return;
}
if (!function_exists('phpb_validate_csrf') || !phpb_validate_csrf()) {
http_response_code(403);
return;
}
$entriesRepository = new \Plugi\Extensions\Form\EntriesRepository();
if(
isset($_GET['id'])
isset($_POST['id'])
) {
$entriesRepository->destroy($_GET['id']);
$entriesRepository->destroy($_POST['id']);
}
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'listEntries', 'id' => $_GET['formId']]));
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'listEntries', 'id' => $_POST['formId'] ?? '']));
@@ -1,13 +1,22 @@
<?php
phpb_requires_authenticated();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
return;
}
if (!function_exists('phpb_validate_csrf') || !phpb_validate_csrf()) {
http_response_code(403);
return;
}
$formsRepository = new \Plugi\Extensions\Form\DefinitionsRepository();
$entriesRepository = new \Plugi\Extensions\Form\EntriesRepository();
if(
isset($_GET['id'])
isset($_POST['id'])
) {
$formsRepository->destroy($_GET['id']);
$entriesRepository->destroyWhere('formId', $_GET['id']);
$formsRepository->destroy($_POST['id']);
$entriesRepository->destroyWhere('formId', $_POST['id']);
}
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'listForms']));
@@ -1,6 +1,15 @@
<?php
phpb_requires_authenticated();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
return;
}
if (!function_exists('phpb_validate_csrf') || !phpb_validate_csrf()) {
http_response_code(403);
return;
}
$formsRepository = new \Plugi\Extensions\Form\DefinitionsRepository();
if(
@@ -0,0 +1,209 @@
<?php
namespace Plugi\Extensions\Form {
class DefinitionsRepository
{
public static array $form = [];
public static array $created = [];
public static array $destroyed = [];
public function findWithId($id)
{
return self::$form;
}
public function create(array $data): null|object|array
{
self::$created[] = $data;
return null;
}
public function update($instance, array $data): void
{
}
public function destroy($id): void
{
self::$destroyed[] = $id;
}
}
class EntriesRepository
{
public static array $destroyed = [];
public static array $deleted = [];
public function destroy($id): void
{
self::$deleted[] = $id;
}
public function destroyWhere($column, $value): void
{
self::$destroyed[] = [$column, $value];
}
}
}
namespace Plugi\Extensions\Form\Finishers {
class FinishersRepository
{
public function getEditorConfig(): array
{
return [];
}
}
}
namespace {
use Plugi\Extensions\Form\DefinitionsRepository;
use Plugi\Extensions\Form\EntriesRepository;
class FormAdminSecurityRedirect extends RuntimeException
{
}
function assertFormAdminSecurity(bool $condition, string $message): void
{
if (!$condition) {
throw new RuntimeException($message);
}
}
function phpb_requires_authenticated(): void
{
if (!($GLOBALS['formAdminSecurityAuthenticated'] ?? false)) {
throw new RuntimeException('The form admin route did not require authentication.');
}
}
function phpb_validate_csrf(): bool
{
return $GLOBALS['formAdminSecurityCsrfValid'] ?? false;
}
function phpb_csrf_field(): void
{
echo '<input type="hidden" name="_csrf_token" value="test-token">';
}
function phpb_e(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
function phpb_url(string $module, array $parameters = []): string
{
return $module . '?' . http_build_query($parameters);
}
function phpb_redirect(string $url, array $flashData = [], int $statusCode = 302): void
{
throw new FormAdminSecurityRedirect();
}
function includeFormSecurityRoute(string $route): void
{
try {
require $route;
} catch (FormAdminSecurityRedirect) {
}
}
$projectRoot = dirname(__DIR__, 3);
$apacheRules = file_get_contents($projectRoot . '/.htaccess');
assertFormAdminSecurity(
is_string($apacheRules) && str_contains($apacheRules, 'Require all denied'),
'Apache must deny requests for hidden files such as the root .env file.'
);
$attack = '</script><script>window.pwned=1</script>';
DefinitionsRepository::$form = [
'id' => 7,
'name' => 'Test form',
'fields' => json_encode([['name' => $attack]]),
'finishers' => '[]',
];
$_GET = ['id' => '7'];
ob_start();
require dirname(__DIR__) . '/admin/Views/EditForm.php';
$editor = ob_get_clean();
assertFormAdminSecurity(
!str_contains($editor, $attack) && str_contains($editor, '\\u003C'),
'Stored form JSON must be escaped before it is emitted inside a script element.'
);
assertFormAdminSecurity(
str_contains($editor, 'name="_csrf_token"'),
'Form saves must submit a CSRF token.'
);
$GLOBALS['formAdminSecurityAuthenticated'] = true;
$GLOBALS['formAdminSecurityCsrfValid'] = false;
$saveRoute = dirname(__DIR__) . '/routes/saveForm.php';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_POST = [];
http_response_code(200);
includeFormSecurityRoute($saveRoute);
assertFormAdminSecurity(http_response_code() === 405, 'Form saves must reject non-POST requests.');
assertFormAdminSecurity(DefinitionsRepository::$created === [], 'A GET request must not save a form.');
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = ['name' => 'Rejected form', 'fields' => '[]', 'finishers' => '[]'];
http_response_code(200);
includeFormSecurityRoute($saveRoute);
assertFormAdminSecurity(http_response_code() === 403, 'Form saves must reject invalid CSRF tokens.');
assertFormAdminSecurity(DefinitionsRepository::$created === [], 'An invalid CSRF token must not save a form.');
$GLOBALS['formAdminSecurityCsrfValid'] = true;
$_POST['_csrf_token'] = 'test-token';
includeFormSecurityRoute($saveRoute);
assertFormAdminSecurity(count(DefinitionsRepository::$created) === 1, 'A valid POST should save a form.');
$deleteRoute = dirname(__DIR__) . '/routes/deleteForm.php';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_GET = ['id' => '7'];
$_POST = [];
http_response_code(200);
includeFormSecurityRoute($deleteRoute);
assertFormAdminSecurity(http_response_code() === 405, 'Form deletion must reject non-POST requests.');
assertFormAdminSecurity(DefinitionsRepository::$destroyed === [], 'A GET request must not delete a form.');
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = ['id' => '7'];
$GLOBALS['formAdminSecurityCsrfValid'] = false;
http_response_code(200);
includeFormSecurityRoute($deleteRoute);
assertFormAdminSecurity(http_response_code() === 403, 'Form deletion must reject invalid CSRF tokens.');
assertFormAdminSecurity(DefinitionsRepository::$destroyed === [], 'An invalid CSRF token must not delete a form.');
$_POST = ['id' => '7', '_csrf_token' => 'test-token'];
$GLOBALS['formAdminSecurityCsrfValid'] = true;
includeFormSecurityRoute($deleteRoute);
assertFormAdminSecurity(DefinitionsRepository::$destroyed === ['7'], 'A valid POST should delete the form.');
assertFormAdminSecurity(EntriesRepository::$destroyed === [['formId', '7']], 'Deleting a form should still delete its entries.');
$deleteEntryRoute = dirname(__DIR__) . '/routes/deleteEntry.php';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_GET = ['id' => '12', 'formId' => '7'];
$_POST = [];
http_response_code(200);
includeFormSecurityRoute($deleteEntryRoute);
assertFormAdminSecurity(http_response_code() === 405, 'Entry deletion must reject non-POST requests.');
assertFormAdminSecurity(EntriesRepository::$deleted === [], 'A GET request must not delete an entry.');
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = ['id' => '12', 'formId' => '7'];
$GLOBALS['formAdminSecurityCsrfValid'] = false;
http_response_code(200);
includeFormSecurityRoute($deleteEntryRoute);
assertFormAdminSecurity(http_response_code() === 403, 'Entry deletion must reject invalid CSRF tokens.');
assertFormAdminSecurity(EntriesRepository::$deleted === [], 'An invalid CSRF token must not delete an entry.');
$_POST['_csrf_token'] = 'test-token';
$GLOBALS['formAdminSecurityCsrfValid'] = true;
includeFormSecurityRoute($deleteEntryRoute);
assertFormAdminSecurity(EntriesRepository::$deleted === ['12'], 'A valid POST should delete an entry.');
fwrite(STDOUT, "PASS: form admin actions require POST and CSRF, and stored JSON is script-safe.\n");
}
+1 -1
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
File diff suppressed because one or more lines are too long
+13 -11
View File
@@ -1217,12 +1217,6 @@
"fsevents": "~2.3.2"
}
},
"node_modules/codemirror": {
"version": "5.63.0",
"resolved": "https://registry.npmjs.org/codemirror/-/codemirror-5.63.0.tgz",
"integrity": "sha512-KlLWRPggDg2rBD1Mx7/EqEhaBdy+ybBCVh/efgjBDsPpMeEu6MbTAJzIT4TuCzvmbTEgvKOGzVT6wdBTNusqrg==",
"license": "MIT"
},
"node_modules/codemirror-formatting": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/codemirror-formatting/-/codemirror-formatting-1.0.0.tgz",
@@ -1338,6 +1332,12 @@
"underscore": "1.13.8"
}
},
"node_modules/grapesjs/node_modules/codemirror": {
"version": "5.63.0",
"resolved": "https://registry.npmjs.org/codemirror/-/codemirror-5.63.0.tgz",
"integrity": "sha512-KlLWRPggDg2rBD1Mx7/EqEhaBdy+ybBCVh/efgjBDsPpMeEu6MbTAJzIT4TuCzvmbTEgvKOGzVT6wdBTNusqrg==",
"license": "MIT"
},
"node_modules/has-flag": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
@@ -2735,11 +2735,6 @@
"readdirp": "~3.6.0"
}
},
"codemirror": {
"version": "5.63.0",
"resolved": "https://registry.npmjs.org/codemirror/-/codemirror-5.63.0.tgz",
"integrity": "sha512-KlLWRPggDg2rBD1Mx7/EqEhaBdy+ybBCVh/efgjBDsPpMeEu6MbTAJzIT4TuCzvmbTEgvKOGzVT6wdBTNusqrg=="
},
"codemirror-formatting": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/codemirror-formatting/-/codemirror-formatting-1.0.0.tgz",
@@ -2826,6 +2821,13 @@
"html-entities": "~1.4.0",
"promise-polyfill": "8.3.0",
"underscore": "1.13.8"
},
"dependencies": {
"codemirror": {
"version": "5.63.0",
"resolved": "https://registry.npmjs.org/codemirror/-/codemirror-5.63.0.tgz",
"integrity": "sha512-KlLWRPggDg2rBD1Mx7/EqEhaBdy+ybBCVh/efgjBDsPpMeEu6MbTAJzIT4TuCzvmbTEgvKOGzVT6wdBTNusqrg=="
}
}
},
"has-flag": {
@@ -151,6 +151,7 @@ class WebsiteManager implements WebsiteManagerContract
exit();
} elseif ($action === "destroy") {
$this->handleDestroy($page);
exit();
}
}
}
@@ -297,6 +298,15 @@ class WebsiteManager implements WebsiteManagerContract
*/
public function handleDestroy(PageContract $page)
{
if (($_SERVER["REQUEST_METHOD"] ?? "") !== "POST") {
http_response_code(405);
return false;
}
if (!function_exists("phpb_validate_csrf") || !phpb_validate_csrf()) {
http_response_code(403);
return false;
}
$pageRepository = new PageRepository();
if (!$pageRepository->destroy($page->getId())) {
phpb_redirect(phpb_url("website_manager"), [
@@ -161,17 +161,20 @@
) ?>" class="btn btn-ghost btn-square btn-sm">
<i class="text-xl ph-duotone ph-gear" aria-hidden="true"></i>
</a>
<a href="<?= phpb_url("website_manager", [
<form method="post" action="<?= phpb_url("website_manager", [
"route" => "page_settings",
"action" => "destroy",
"page" => $page->getId(),
]) ?>" title="<?= phpb_trans(
]) ?>">
<?php phpb_csrf_field(); ?>
<button type="submit" title="<?= phpb_trans(
"website-manager.remove",
) ?>" aria-label="<?= phpb_e(
phpb_trans("website-manager.remove"),
) ?>" class="btn btn-error btn-square btn-sm">
<i class="text-xl ph-duotone ph-trash" aria-hidden="true"></i>
</a>
<i class="text-xl ph-duotone ph-trash" aria-hidden="true"></i>
</button>
</form>
</div>
</td>
</tr>
@@ -1058,6 +1058,38 @@ $cases = [
'Successful deletion did not invalidate every stored localized route: ' . json_encode(PageCreationTestCache::$invalidatedRoutes)
);
},
'website manager page deletion requires POST and a valid CSRF token' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
$websiteManager = new WebsiteManager();
$_SERVER['REQUEST_METHOD'] = 'GET';
$_POST = [];
http_response_code(200);
$websiteManager->handleDestroy($page);
assertPageCreation(http_response_code() === 405, 'Page deletion must reject GET requests.');
assertPageCreation(count($phpb_db->rows('pages')) === 1, 'A GET request deleted a page.');
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = ['_csrf_token' => 'invalid-token'];
http_response_code(200);
$websiteManager->handleDestroy($page);
assertPageCreation(http_response_code() === 403, 'Page deletion must reject invalid CSRF tokens.');
assertPageCreation(count($phpb_db->rows('pages')) === 1, 'An invalid CSRF token deleted a page.');
$_SESSION['phpb_csrf_tokens'] = ['valid-token' => time()];
$_POST = ['_csrf_token' => 'valid-token'];
try {
$websiteManager->handleDestroy($page);
} catch (PageCreationRedirectException $exception) {
assertPageCreation($exception->redirectUrl === '/website_manager', 'Successful deletion redirected to an unexpected page.');
}
assertPageCreation(count($phpb_db->rows('pages')) === 0, 'A valid token did not delete the page.');
},
'failed page deletion rolls back translation cleanup without invalidating caches' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();