Compare commits

12 Commits
Author SHA1 Message Date
deepDiverPaul f01cad090c Merge pull request 'Feature/ext-blog' (#14) from feature/ext-blog into main
Reviewed-on: #14
2026-12-02 10:22:46 +00:00
deepDiverPaul 6f0e39b5f5 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 10:20:36 +00:00
deepDiverPaul 745f33f17d feat(ext-blog): Add markdown editor bundling and dependencies 2026-12-02 10:20:36 +00:00
deepDiverPaul 2d4b196b04 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 10:20:36 +00:00
deepDiverPaul e97d96c1f5 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 10:20:36 +00:00
deepDiverPaul 32582e9279 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 10:20:36 +00:00
deepDiverPaul f35645132e Add blog extension 2026-12-02 10:20:36 +00:00
deepDiverPaul 47214e0bbc Merge pull request 'fix(security): Add security hardening and CSRF protection.' (#13) from security into main
Reviewed-on: #13
2026-12-02 10:20:04 +00: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
deepDiverPaul 6f02b0bc8d Merge pull request 'Extensions' (#12) from feat-extensions-add-extension-enable-dis into main
Reviewed-on: #12
2026-12-01 10:05:05 +00:00
deepDiverPaul 2e42cd00d2 feat(extensions): Add extension enable/disable toggle and loading logic
The settings view now renders a toggle switch for each extension to enable or disable it. The `Plugi` class includes a new method to load extensions based on their enabled state. Tests verify the activation logic and settings persistence.
2026-12-01 10:28:46 +01:00
deepDiverPaul 515e4cac1f feat(ext-tracking): Add tracking extension for HTML/JS snippets
Adds a new extension allowing injection of custom code into the page head. Includes an admin interface for saving snippets, secure save routes with CSRF protection, and tests verifying the functionality. Also updates core Extensions.php to support callable HTML blocks for lazy evaluation.
2026-11-30 22:51:03 +01:00
59 changed files with 3979 additions and 93 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\.
+3 -2
View File
@@ -2,8 +2,9 @@ FROM php:8.4-apache-bookworm
WORKDIR "/var/www/html"
RUN apt-get update; \
docker-php-ext-install pdo_mysql; \
apt-get -y --no-install-recommends install \
git; \
git \
libonig-dev; \
docker-php-ext-install mbstring pdo_mysql; \
apt-get clean; \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*
+25
View File
@@ -0,0 +1,25 @@
# 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 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 or update the extension-owned post and category tables, including the optional featured-image field.
3. Add categories if useful, then create posts as drafts or publish them from the Blog section.
## Create the public pages
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.
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,61 @@
<?php
namespace Plugi\Extensions\Blog;
use InvalidArgumentException;
use Plugi\Repositories\BaseRepository;
class CategoriesRepository extends BaseRepository
{
protected $table = 'ext__blog_categories';
public function create(array $data)
{
return parent::create($this->validatedData($data));
}
public function update($instance, array $data)
{
$id = is_array($instance) ? ($instance['id'] ?? null) : ($instance->id ?? null);
if (!is_numeric($id) || (int) $id < 1 || $this->findWithId($id) === null) {
return false;
}
return parent::update(['id' => (int) $id], $this->validatedData($data, (int) $id));
}
public function getAllForAdmin(): array
{
return $this->db->select("SELECT * FROM {$this->table} ORDER BY name ASC, id ASC", []);
}
public function destroy($id)
{
if (!is_numeric($id) || (int) $id < 1) {
return false;
}
return $this->db->transaction(function () use ($id) {
return (new PostsRepository())->clearCategory((int) $id) && parent::destroy((int) $id);
});
}
private function validatedData(array $data, ?int $categoryId = null): array
{
$name = is_string($data['name'] ?? null) ? trim($data['name']) : '';
$slug = is_string($data['slug'] ?? null) ? trim($data['slug']) : '';
if ($name === '' || mb_strlen($name) > 255) {
throw new InvalidArgumentException('A category name of 1–255 characters is required.');
}
if (strlen($slug) > 191 || !preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug)) {
throw new InvalidArgumentException('Use a lowercase slug with letters, numbers, and single hyphens.');
}
foreach ($this->findWhere('slug', $slug) as $category) {
if ((int) $category['id'] !== $categoryId) {
throw new InvalidArgumentException('That category slug is already in use.');
}
}
return ['name' => $name, 'slug' => $slug];
}
}
@@ -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');
}
}
@@ -0,0 +1,217 @@
<?php
namespace Plugi\Extensions\Blog;
use DateTimeImmutable;
use InvalidArgumentException;
use Plugi\Repositories\BaseRepository;
class PostsRepository extends BaseRepository
{
public const POSTS_PER_PAGE = 10;
protected $table = 'ext__blog_posts';
public function create(array $data)
{
return parent::create($this->validatedData($data));
}
public function update($instance, array $data)
{
$id = is_array($instance) ? ($instance['id'] ?? null) : ($instance->id ?? null);
if (!is_numeric($id) || (int) $id < 1 || $this->findWithId($id) === null) {
return false;
}
return parent::update(['id' => (int) $id], $this->validatedData($data, (int) $id));
}
public function getAllForAdmin(): array
{
return $this->db->select("SELECT * FROM {$this->table} ORDER BY updated_at DESC, id DESC", []);
}
public function getPublishedForListing(): array
{
$categoriesTable = $_ENV['DATABASE_PREFIX'] . 'ext__blog_categories';
$uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads';
$posts = $this->db->select(
"SELECT posts.*, categories.name AS category_name, featured_image.public_id AS featured_image_public_id, featured_image.original_file AS featured_image_original_file, featured_image.alt_text AS featured_image_alt_text FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id LEFT JOIN {$uploadsTable} featured_image ON featured_image.public_id = posts.featured_image_id AND LOWER(featured_image.mime_type) LIKE 'image/%' WHERE posts.status = ? ORDER BY posts.published_at DESC, posts.id DESC",
['published']
);
return array_map(fn(array $post): array => $this->resolveFeaturedImage($post), $posts);
}
public function getPageForAdmin(string $search, int $page): array
{
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
{
$categoriesTable = $_ENV['DATABASE_PREFIX'] . 'ext__blog_categories';
$uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads';
$from = $publishedOnly
? "FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id 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[] = '(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, $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, 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 isset($posts[0]) ? $this->resolveFeaturedImage($posts[0]) : null;
}
public function clearCategory(int $categoryId): bool
{
return $this->db->query("UPDATE {$this->table} SET category_id = NULL WHERE category_id = ?", [$categoryId]);
}
private function validatedData(array $data, ?int $postId = null): array
{
$title = is_string($data['title'] ?? null) ? trim($data['title']) : '';
$slug = is_string($data['slug'] ?? null) ? trim($data['slug']) : '';
$excerpt = is_string($data['excerpt'] ?? null) ? trim($data['excerpt']) : '';
$body = is_string($data['body'] ?? null) ? $data['body'] : '';
$status = is_string($data['status'] ?? null) ? $data['status'] : '';
if ($title === '' || mb_strlen($title) > 255) {
throw new InvalidArgumentException('A title of 1–255 characters is required.');
}
if (strlen($slug) > 191 || !preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug)) {
throw new InvalidArgumentException('Use a lowercase slug with letters, numbers, and single hyphens.');
}
foreach ($this->findWhere('slug', $slug) as $post) {
if ((int) $post['id'] !== $postId) {
throw new InvalidArgumentException('That post slug is already in use.');
}
}
if (!in_array($status, ['draft', 'published'], true)) {
throw new InvalidArgumentException('Choose draft or published status.');
}
if ($status === 'published' && trim($body) === '') {
throw new InvalidArgumentException('Add the post body before publishing.');
}
$categoryId = $data['category_id'] ?? '';
if ($categoryId === '' || $categoryId === null) {
$categoryId = null;
} elseif (!is_scalar($categoryId) || !ctype_digit((string) $categoryId) || (int) $categoryId < 1 || (new CategoriesRepository())->findWithId((int) $categoryId) === null) {
throw new InvalidArgumentException('Choose an existing category.');
} else {
$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 [
'title' => $title,
'slug' => $slug,
'excerpt' => $excerpt,
'body' => $body,
'featured_image_id' => $featuredImageId,
'category_id' => $categoryId,
'status' => $status,
'published_at' => $publishedAt,
];
}
private function resolveFeaturedImage(array $post): array
{
$publicId = $post['featured_image_public_id'] ?? null;
$originalFile = $post['featured_image_original_file'] ?? null;
if (is_string($publicId) && $publicId !== '' && is_string($originalFile) && $originalFile !== '') {
$image = new \Plugi\UploadedFile();
$image->public_id = $publicId;
$image->original_file = $originalFile;
$post['featured_image_url'] = $image->getUrl();
} else {
$post['featured_image_url'] = null;
$post['featured_image_alt_text'] = null;
}
unset($post['featured_image_public_id'], $post['featured_image_original_file']);
return $post;
}
private function validatedPublicationDate(mixed $value, string $status): ?string
{
if ($value === null || $value === '') {
return $status === 'published' ? date('Y-m-d H:i:s') : null;
}
if (!is_string($value)) {
throw new InvalidArgumentException('Enter a valid publication date.');
}
$value = trim($value);
$format = str_contains($value, 'T') ? 'Y-m-d\\TH:i' : 'Y-m-d H:i:s';
$date = DateTimeImmutable::createFromFormat('!' . $format, $value);
$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()) {
throw new InvalidArgumentException('Publication dates cannot be in the future.');
}
return $date->format('Y-m-d H:i:s');
}
}
@@ -0,0 +1,192 @@
<?php
use Plugi\Extensions\Blog\CategoriesRepository;
use Plugi\Extensions\Blog\PostsRepository;
use Plugi\Repositories\UploadRepository;
$postsRepository = new PostsRepository();
$post = [
'title' => '',
'slug' => '',
'excerpt' => '',
'body' => '',
'featured_image_id' => null,
'category_id' => null,
'status' => 'draft',
'published_at' => null,
];
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'])) : '';
$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">
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'posts']) ?>" class="btn btn-ghost btn-square btn-sm" aria-label="Back to posts" title="Back to posts">
<i class="ph-duotone ph-arrow-left text-xl" aria-hidden="true"></i>
</a>
<div class="space-y-1">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-primary">Blog editor</p>
<h2 class="text-xl font-bold tracking-tight"><?= $isEditing ? 'Edit post' : 'New post' ?></h2>
<p class="text-sm text-base-content/60">Save as a draft or publish the article.</p>
</div>
</div>
</header>
<form action="/ext--blog/save-post" method="post" class="space-y-6">
<?php phpb_csrf_field(); ?>
<?php if ($isEditing): ?>
<input type="hidden" name="id" value="<?= phpb_e((string) $post['id']) ?>">
<?php endif; ?>
<section class="card border border-base-300 bg-base-100 shadow-sm">
<div class="card-body gap-5 p-4 sm:p-6 lg:p-8">
<div>
<label for="post-title" class="label"><span class="label-text font-medium">Title</span></label>
<input id="post-title" type="text" name="title" maxlength="255" required value="<?= phpb_e($post['title']) ?>" class="input w-full">
</div>
<div>
<label for="post-slug" class="label"><span class="label-text font-medium">Slug</span></label>
<input id="post-slug" type="text" name="slug" maxlength="191" pattern="[a-z0-9]+(-[a-z0-9]+)*" required value="<?= phpb_e($post['slug']) ?>" class="input w-full" aria-describedby="post-slug-help">
<p id="post-slug-help" class="mt-1 text-sm text-base-content/60">Use lowercase letters, numbers, and hyphens.</p>
</div>
<div>
<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-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>
<label for="post-category" class="label"><span class="label-text font-medium">Category</span></label>
<select id="post-category" name="category_id" class="select w-full">
<option value="">No category</option>
<?php foreach ($categories as $category): ?>
<option value="<?= phpb_e((string) $category['id']) ?>" <?= (string) $category['id'] === (string) $post['category_id'] ? 'selected' : '' ?>><?= phpb_e($category['name']) ?></option>
<?php endforeach; ?>
</select>
</div>
<div>
<label for="post-status" class="label"><span class="label-text font-medium">Status</span></label>
<select id="post-status" name="status" class="select w-full">
<option value="draft" <?= $post['status'] === 'draft' ? 'selected' : '' ?>>Draft</option>
<option value="published" <?= $post['status'] === 'published' ? 'selected' : '' ?>>Published</option>
</select>
</div>
</div>
<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>
</div>
</div>
</section>
<div class="flex flex-wrap justify-end gap-3">
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'posts']) ?>" class="btn btn-ghost">Cancel</a>
<button type="submit" class="btn btn-primary">Save post</button>
</div>
</form>
<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>
@@ -0,0 +1,82 @@
<?php
use Plugi\Extensions\Blog\CategoriesRepository;
$categoriesRepository = new CategoriesRepository();
$categories = $categoriesRepository->getAllForAdmin();
$category = ['name' => '', 'slug' => ''];
if (isset($_GET['id']) && ctype_digit((string) $_GET['id'])) {
$category = $categoriesRepository->findWithId($_GET['id']) ?? $category;
}
$isEditing = isset($category['id']);
?>
<section class="space-y-5">
<header 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">Categories</h2>
<p class="text-sm text-base-content/60">Organize posts with one optional category each.</p>
</header>
<form action="/ext--blog/save-category" method="post" class="card border border-base-300 bg-base-100 shadow-sm">
<?php phpb_csrf_field(); ?>
<?php if ($isEditing): ?>
<input type="hidden" name="id" value="<?= phpb_e((string) $category['id']) ?>">
<?php endif; ?>
<div class="card-body gap-4 p-4 sm:p-6">
<h3 class="card-title text-lg"><?= $isEditing ? 'Edit category' : 'New category' ?></h3>
<div class="grid gap-4 sm:grid-cols-2">
<div>
<label for="category-name" class="label"><span class="label-text font-medium">Name</span></label>
<input id="category-name" type="text" name="name" maxlength="255" required value="<?= phpb_e($category['name']) ?>" class="input w-full">
</div>
<div>
<label for="category-slug" class="label"><span class="label-text font-medium">Slug</span></label>
<input id="category-slug" type="text" name="slug" maxlength="191" pattern="[a-z0-9]+(-[a-z0-9]+)*" required value="<?= phpb_e($category['slug']) ?>" class="input w-full">
</div>
</div>
<div class="flex flex-wrap justify-end gap-3">
<?php if ($isEditing): ?>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'categories']) ?>" class="btn btn-ghost">Cancel</a>
<?php endif; ?>
<button type="submit" class="btn btn-primary"><?= $isEditing ? 'Save category' : 'Add category' ?></button>
</div>
</div>
</form>
<?php if (empty($categories)): ?>
<div class="card border border-dashed border-base-300 bg-base-100 shadow-sm" role="status">
<div class="card-body items-center px-5 py-10 text-center">
<h3 class="card-title text-lg">No categories yet</h3>
<p class="text-sm text-base-content/60">Create a category above to make it available to posts.</p>
</div>
</div>
<?php else: ?>
<div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
<table class="table table-zebra w-full min-w-[32rem]">
<thead><tr><th>Name</th><th>Slug</th><th class="w-40 text-right">Actions</th></tr></thead>
<tbody>
<?php foreach ($categories as $item): ?>
<tr>
<td><?= phpb_e($item['name']) ?></td>
<td><span class="font-mono text-sm"><?= phpb_e($item['slug']) ?></span></td>
<td>
<div class="flex items-center justify-end gap-1">
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'categories', 'id' => $item['id']]) ?>" class="btn btn-ghost btn-square btn-sm" title="Edit category" aria-label="Edit <?= phpb_e($item['name']) ?>">
<i class="ph-duotone ph-pencil-line text-lg" aria-hidden="true"></i>
</a>
<form action="/ext--blog/delete-category" method="post" onsubmit="return confirm('Delete this category? Posts will remain uncategorized.')">
<?php phpb_csrf_field(); ?>
<input type="hidden" name="id" value="<?= phpb_e((string) $item['id']) ?>">
<button type="submit" class="btn btn-ghost btn-square btn-sm text-error" title="Delete category" aria-label="Delete <?= phpb_e($item['name']) ?>">
<i class="ph-duotone ph-trash text-lg" aria-hidden="true"></i>
</button>
</form>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</section>
@@ -0,0 +1,128 @@
<?php
use Plugi\Extensions\Blog\CategoriesRepository;
use Plugi\Extensions\Blog\PostsRepository;
$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) {
$categoryNames[$category['id']] = $category['name'];
}
?>
<section class="space-y-5">
<header class="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
<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"><?= 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>
New post
</a>
</header>
<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">
<i class="text-3xl ph-duotone ph-article" aria-hidden="true"></i>
</span>
<h3 class="card-title mt-1 text-lg">No posts yet</h3>
<p class="max-w-md text-sm leading-relaxed text-base-content/60">Create a draft or publish your first article.</p>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'editPost']) ?>" class="btn btn-primary mt-2">
<i class="ph-duotone ph-plus" aria-hidden="true"></i>
Create your first post
</a>
</div>
</div>
<?php else: ?>
<div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
<table class="table table-zebra w-full min-w-[48rem]">
<thead>
<tr>
<th>Title</th>
<th>Category</th>
<th>Status</th>
<th>Published</th>
<th class="w-40 text-right">Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($posts as $post): ?>
<tr>
<td>
<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($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>
<div class="flex items-center justify-end gap-1">
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'editPost', 'id' => $post['id']]) ?>" class="btn btn-ghost btn-square btn-sm" title="Edit post" aria-label="Edit <?= phpb_e($post['title']) ?>">
<i class="ph-duotone ph-pencil-line text-lg" aria-hidden="true"></i>
</a>
<form action="/ext--blog/delete-post" method="post" onsubmit="return confirm('Delete this post?')">
<?php phpb_csrf_field(); ?>
<input type="hidden" name="id" value="<?= phpb_e((string) $post['id']) ?>">
<button type="submit" class="btn btn-ghost btn-square btn-sm text-error" title="Delete post" aria-label="Delete <?= phpb_e($post['title']) ?>">
<i class="ph-duotone ph-trash text-lg" aria-hidden="true"></i>
</button>
</form>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</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;
},
};
});
+38
View File
@@ -0,0 +1,38 @@
<?php
$modules = [
'posts' => [
'include' => __DIR__ . '/Views/ListPosts.php',
'label' => 'Posts',
'icon' => 'ph-article',
'inMenu' => true,
],
'categories' => [
'include' => __DIR__ . '/Views/ListCategories.php',
'label' => 'Categories',
'icon' => 'ph-tag',
'inMenu' => true,
],
'editPost' => [
'include' => __DIR__ . '/Views/EditPost.php',
'inMenu' => false,
],
];
$activeModule = isset($_GET['action']) && array_key_exists($_GET['action'], $modules) ? $_GET['action'] : 'posts';
?>
<nav class="mb-6 overflow-x-auto" aria-label="Blog extension navigation">
<div class="tabs tabs-box w-max min-w-full bg-base-200/50">
<?php foreach ($modules as $name => $module): ?>
<?php if (!$module['inMenu']) continue; ?>
<a class="tab gap-2 <?= $name === $activeModule ? 'tab-active' : '' ?>" <?= $name === $activeModule ? 'aria-current="page"' : '' ?> href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => $name]) ?>">
<i class="ph-duotone <?= phpb_e($module['icon']) ?>" aria-hidden="true"></i>
<?= phpb_e($module['label']) ?>
</a>
<?php endforeach; ?>
</div>
</nav>
<div class="w-full">
<?php include $modules[$activeModule]['include']; ?>
</div>
@@ -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();
}
@@ -0,0 +1,8 @@
<?php
return [
'title' => 'Blog Post',
'category' => 'Blog',
'icon' => 'ph ph-article',
'cache' => false,
];
@@ -0,0 +1,42 @@
<?php
$slug = phpb_route_parameter('slug');
$post = is_string($slug) && $slug !== ''
? (new \Plugi\Extensions\Blog\PostsRepository())->findPublishedBySlug($slug)
: null;
?>
<?php if ($post === null): ?>
<section class="card border border-base-300 bg-base-100 shadow-sm" aria-labelledby="blog-post-not-found">
<div class="card-body">
<h1 id="blog-post-not-found" class="card-title">Article not found</h1>
<p class="text-base-content/70">This article is unavailable or may no longer be published.</p>
</div>
</section>
<?php else: ?>
<article class="mx-auto w-full max-w-3xl space-y-8">
<header class="space-y-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 endif; ?>
<?php endif; ?>
</div>
<h1 class="text-3xl font-bold tracking-tight text-base-content sm:text-4xl"><?= phpb_e($post['title']) ?></h1>
<?php if ($post['excerpt'] !== ''): ?>
<p class="text-lg leading-relaxed text-base-content/70"><?= phpb_e($post['excerpt']) ?></p>
<?php endif; ?>
</header>
<?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; ?>
@@ -0,0 +1,8 @@
<?php
return [
'title' => 'Published Posts',
'category' => 'Blog',
'icon' => 'ph ph-article',
'cache' => false,
];
@@ -0,0 +1,87 @@
<?php
$postsRepository = new \Plugi\Extensions\Blog\PostsRepository();
$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);
$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">
<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 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): ?>
<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 endif; ?>
<?php endif; ?>
</div>
<h2 class="card-title text-xl">
<a class="link link-hover" href="<?= phpb_e(phpb_full_url('/blog/' . rawurlencode($post['slug']))) ?>"><?= phpb_e($post['title']) ?></a>
</h2>
<?php if ($post['excerpt'] !== ''): ?>
<p class="whitespace-pre-line text-base-content/80"><?= phpb_e($post['excerpt']) ?></p>
<?php endif; ?>
<div class="card-actions mt-auto justify-end">
<a class="btn btn-ghost btn-sm" href="<?= phpb_e(phpb_full_url('/blog/' . rawurlencode($post['slug']))) ?>">
Read article<span class="sr-only">: <?= phpb_e($post['title']) ?></span>
<i class="ph ph-arrow-right" aria-hidden="true"></i>
</a>
</div>
</div>
</article>
<?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,
});
+71
View File
@@ -0,0 +1,71 @@
<?php
return [
'title' => 'Blog',
'author' => 'Paul Spenke',
'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' => [
'title' => 'varchar(255) NOT NULL',
'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',
'created_at' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP',
'updated_at' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
],
'uniqueKeys' => [
'slug' => ['slug'],
],
],
'categories' => [
'columns' => [
'name' => 'varchar(255) NOT NULL',
'slug' => 'varchar(191) NOT NULL',
'created_at' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP',
'updated_at' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
],
'uniqueKeys' => [
'slug' => ['slug'],
],
],
],
];
+22
View File
@@ -0,0 +1,22 @@
<?php
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',
]);
Extensions::addBlocks([
'post-list' => __DIR__ . '/blocks/post-list',
'post-detail' => __DIR__ . '/blocks/post-detail',
]);
Extensions::registerBackend('blog', [
'title' => 'Blog',
'include' => __DIR__ . '/admin/blog.php',
'icon' => '<i class="ph ph-article"></i>',
]);
+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,24 @@
<?php
phpb_requires_authenticated();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
exit();
}
if (!phpb_validate_csrf()) {
http_response_code(403);
exit();
}
$deleted = false;
try {
if (isset($_POST['id']) && is_string($_POST['id']) && ctype_digit($_POST['id']) && (int) $_POST['id'] > 0) {
$deleted = (new \Plugi\Extensions\Blog\CategoriesRepository())->destroy((int) $_POST['id']);
}
} catch (\Throwable) {
$deleted = false;
}
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'categories']), [
'message-type' => $deleted ? 'success' : 'error',
'message' => $deleted ? 'Category deleted; associated posts are uncategorized.' : 'The category could not be deleted.',
]);
@@ -0,0 +1,24 @@
<?php
phpb_requires_authenticated();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
exit();
}
if (!phpb_validate_csrf()) {
http_response_code(403);
exit();
}
$deleted = false;
try {
if (isset($_POST['id']) && is_string($_POST['id']) && ctype_digit($_POST['id']) && (int) $_POST['id'] > 0) {
$deleted = (new \Plugi\Extensions\Blog\PostsRepository())->destroy((int) $_POST['id']);
}
} catch (\Throwable) {
$deleted = false;
}
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'posts']), [
'message-type' => $deleted ? 'success' : 'error',
'message' => $deleted ? 'Post deleted.' : 'The post could not be deleted.',
]);
@@ -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.']);
}
@@ -0,0 +1,30 @@
<?php
phpb_requires_authenticated();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
exit();
}
if (!phpb_validate_csrf()) {
http_response_code(403);
exit();
}
$categoriesRepository = new \Plugi\Extensions\Blog\CategoriesRepository();
$redirectUrl = phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'categories']);
$data = array_intersect_key($_POST, array_flip(['name', 'slug']));
try {
if (isset($_POST['id']) && is_string($_POST['id']) && ctype_digit($_POST['id']) && (int) $_POST['id'] > 0) {
$saved = $categoriesRepository->update(['id' => (int) $_POST['id']], $data);
} elseif (!isset($_POST['id'])) {
$saved = $categoriesRepository->create($data);
} else {
$saved = false;
}
$message = $saved ? ['message-type' => 'success', 'message' => 'Category saved.'] : ['message-type' => 'error', 'message' => 'The category could not be saved.'];
} catch (\InvalidArgumentException $exception) {
$message = ['message-type' => 'error', 'message' => $exception->getMessage()];
} catch (\Throwable) {
$message = ['message-type' => 'error', 'message' => 'The category could not be saved. Check that the slug is unique.'];
}
phpb_redirect($redirectUrl, $message);
@@ -0,0 +1,31 @@
<?php
phpb_requires_authenticated();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
exit();
}
if (!phpb_validate_csrf()) {
http_response_code(403);
exit();
}
$postsRepository = new \Plugi\Extensions\Blog\PostsRepository();
$redirectUrl = phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'posts']);
$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) {
$saved = $postsRepository->update(['id' => (int) $_POST['id']], $data);
} elseif (!isset($_POST['id'])) {
$saved = $postsRepository->create($data);
} else {
$saved = false;
}
$message = $saved ? ['message-type' => 'success', 'message' => 'Post saved.'] : ['message-type' => 'error', 'message' => 'The post could not be saved.'];
} catch (\InvalidArgumentException $exception) {
$message = ['message-type' => 'error', 'message' => $exception->getMessage()];
} catch (\Throwable) {
$message = ['message-type' => 'error', 'message' => 'The post could not be saved. Check that the slug is unique.'];
}
phpb_redirect($redirectUrl, $message);
@@ -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");
}
@@ -0,0 +1,444 @@
<?php
use Plugi\Core\DB;
use Plugi\Extensions\Blog\CategoriesRepository;
use Plugi\Extensions\Blog\PostsRepository;
use Plugi\Repositories\UploadRepository;
require_once dirname(__DIR__, 3) . '/plugi-core/src/Extensions.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Core/DB.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Core/helpers.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Repositories/BaseRepository.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Repositories/UploadRepository.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/UploadedFile.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Contracts/PageContract.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Contracts/ThemeContract.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Page.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Modules/GrapesJS/PageRenderer.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Modules/GrapesJS/Block/BaseModel.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Modules/GrapesJS/Block/BaseController.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/ThemeBlock.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Modules/GrapesJS/Block/BlockRenderer.php';
require_once dirname(__DIR__) . '/admin/Classes/PostsRepository.php';
require_once dirname(__DIR__) . '/admin/Classes/CategoriesRepository.php';
require_once dirname(__DIR__) . '/admin/Classes/PostContentRenderer.php';
$blogConfig = require dirname(__DIR__) . '/config.php';
\Plugi\Extensions::registerConfig('blog', $blogConfig);
require_once dirname(__DIR__) . '/extension.php';
assertBlog(($blogConfig['tables']['posts']['columns']['featured_image_id'] ?? null) === 'varchar(50) NULL', 'Featured image metadata should be declared as nullable extension schema.');
class BlogTestDatabase extends DB
{
public function __construct()
{
$this->pdo = new PDO('sqlite::memory:');
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->databaseName = 'blog_test';
}
public function createSchema(): void
{
$this->query('CREATE TABLE test_ext__blog_posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title VARCHAR(255) NOT NULL,
slug VARCHAR(191) NOT NULL UNIQUE,
excerpt TEXT NOT NULL,
body TEXT NOT NULL,
featured_image_id VARCHAR(50) NULL,
category_id INTEGER NULL,
status VARCHAR(20) NOT NULL,
published_at DATETIME NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)');
$this->query('CREATE TABLE test_uploads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
public_id VARCHAR(50) NOT NULL UNIQUE,
original_file VARCHAR(512) NOT NULL,
mime_type VARCHAR(50) NOT NULL,
server_file VARCHAR(512) NOT NULL,
alt_text VARCHAR(1000) NOT NULL DEFAULT "",
folder VARCHAR(255) NOT NULL DEFAULT ""
)');
$this->query('CREATE TABLE test_ext__blog_categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(255) NOT NULL,
slug VARCHAR(191) NOT NULL UNIQUE,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)');
}
}
class BlogTestTheme implements \Plugi\Contracts\ThemeContract
{
public function getThemeBlocks()
{
return [];
}
public function getThemeLayouts()
{
return [];
}
public function getFolder()
{
return '';
}
}
function assertBlog(bool $condition, string $message): void
{
if (!$condition) {
throw new RuntimeException($message);
}
}
function expectBlogValidation(callable $callback, string $message): void
{
try {
$callback();
} catch (InvalidArgumentException) {
return;
}
throw new RuntimeException($message);
}
function renderBlogBlock(string $slug): string
{
$theme = new BlogTestTheme();
$page = new \Plugi\Page();
$themeBlock = new \Plugi\ThemeBlock($theme, \Plugi\Extensions::getBlock($slug), true, $slug);
return (new \Plugi\Modules\GrapesJS\Block\BlockRenderer($theme, $page))->render($themeBlock);
}
function renderBlogListing(): string
{
return renderBlogBlock('post-list');
}
function renderBlogDetail(?string $slug): string
{
$GLOBALS['phpb_route_parameters'] = $slug === null ? [] : ['slug' => $slug];
return renderBlogBlock('post-detail');
}
function renderBlogAdminList(): string
{
ob_start();
include dirname(__DIR__) . '/admin/Views/ListPosts.php';
return (string) ob_get_clean();
}
function renderBlogEditor(int $postId): string
{
$_GET = ['id' => (string) $postId];
ob_start();
include dirname(__DIR__) . '/admin/Views/EditPost.php';
return (string) ob_get_clean();
}
$_ENV['DATABASE_PREFIX'] = 'test_';
$phpb_db = new BlogTestDatabase();
$phpb_db->createSchema();
assertBlog(isset($phpb_db->getDBDefinition()['ext__blog_posts'], $phpb_db->getDBDefinition()['ext__blog_categories']), 'The blog tables should be included in the core database definition.');
assertBlog(isset(\Plugi\Extensions::getBackends()['ext--blog']), 'The blog admin backend should be registered.');
assertBlog(in_array('/admin/assets/markdown-editor.js', array_column($blogConfig['assets'], 'src'), true) && in_array('/admin/assets/markdown-editor.css', array_column($blogConfig['assets'], 'src'), true), 'The editor script and stylesheet should be registered as extension assets.');
$publicAssets = array_values(array_filter($blogConfig['assets'], fn(array $asset): bool => $asset['location'] === 'footer'));
$adminAssets = array_values(array_filter($blogConfig['assets'], fn(array $asset): bool => $asset['location'] === 'admin-header'));
assertBlog(in_array(['src' => '/assets/code-highlighter.css', 'type' => 'style', 'location' => 'footer'], $publicAssets, true) && in_array(['src' => '/assets/code-highlighter.js', 'type' => 'script', 'location' => 'footer'], $publicAssets, true), 'The highlighter assets should be registered for public pages.');
assertBlog(in_array(['src' => '/assets/code-highlighter.css', 'type' => 'style', 'location' => 'admin-header'], $adminAssets, true) && in_array(['src' => '/assets/code-highlighter.js', 'type' => 'script', 'location' => 'admin-header'], $adminAssets, true), 'The highlighter assets should be registered for admin pages.');
assertBlog(array_search('/assets/code-highlighter.js', array_column($adminAssets, 'src'), true) < array_search('/admin/assets/markdown-editor.js', array_column($adminAssets, 'src'), true), 'The admin highlighter should load before the Markdown editor.');
$highlighterSource = file_get_contents(dirname(__DIR__) . '/assets/src/code-highlighter.js');
$editorSource = file_get_contents(dirname(__DIR__) . '/admin/assets/src/markdown-editor.js');
assertBlog(str_contains($highlighterSource, 'highlightPage') && str_contains($highlighterSource, "document.addEventListener('DOMContentLoaded'"), 'The highlighter should initialize code blocks on initial page content.');
assertBlog(str_contains($editorSource, 'window.blogCodeHighlighter?.highlight(preview)'), 'The editor should highlight preview code after replacing its contents.');
assertBlog(count(array_intersect(['/ext--blog/save-post', '/ext--blog/preview-post', '/ext--blog/delete-post', '/ext--blog/save-category', '/ext--blog/delete-category'], array_keys(\Plugi\Extensions::getRoutes()))) === 5, 'Blog post and category routes should be registered.');
assertBlog(\Plugi\Extensions::getBlock('post-list') === dirname(__DIR__) . '/blocks/post-list', 'The published-post block should be registered.');
assertBlog((require dirname(__DIR__) . '/blocks/post-list/config.php')['cache'] === false, 'The listing block should avoid stale cached post data.');
assertBlog(\Plugi\Extensions::getBlock('post-detail') === dirname(__DIR__) . '/blocks/post-detail', 'The post-detail block should be registered.');
assertBlog((require dirname(__DIR__) . '/blocks/post-detail/config.php')['cache'] === false, 'The detail block should avoid stale route-specific output.');
$posts = new PostsRepository();
$categories = new CategoriesRepository();
$category = $categories->create(['name' => 'News', 'slug' => 'news']);
assertBlog(is_array($category) && (int) $category['id'] > 0, 'Category creation should return the new category.');
$phpb_db->query('INSERT INTO test_uploads (public_id, original_file, mime_type, server_file, alt_text) VALUES (?, ?, ?, ?, ?)', [
'blog-cover-1', 'cover.jpg', 'image/jpeg', 'cover.jpg', 'A "featured" & <cover>',
]);
$phpb_db->query('INSERT INTO test_uploads (public_id, original_file, mime_type, server_file, alt_text) VALUES (?, ?, ?, ?, ?)', [
'blog-document-1', 'notes.pdf', 'application/pdf', 'notes.pdf', 'A document',
]);
$post = $posts->create([
'title' => 'First post',
'slug' => 'first-post',
'excerpt' => 'A short summary',
'body' => 'Post body',
'featured_image_id' => 'blog-cover-1',
'category_id' => $category['id'],
'status' => 'published',
'published_at' => '',
]);
assertBlog(is_array($post) && $post['status'] === 'published', 'A valid published post should be created.');
assertBlog($post['published_at'] !== null, 'Publishing without a date should set the current publication timestamp.');
assertBlog($post['featured_image_id'] === 'blog-cover-1', 'A valid image upload reference should be persisted on the post.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Missing featured image', 'slug' => 'missing-featured-image', 'excerpt' => '', 'body' => 'Body', 'featured_image_id' => 'missing-upload', 'category_id' => '', 'status' => 'draft', 'published_at' => '',
]), 'Missing upload references should be rejected.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Non-image featured image', 'slug' => 'non-image-featured-image', 'excerpt' => '', 'body' => 'Body', 'featured_image_id' => 'blog-document-1', 'category_id' => '', 'status' => 'draft', 'published_at' => '',
]), 'Non-image upload references should be rejected.');
$olderPost = $posts->create([
'title' => 'Older published post',
'slug' => 'older-published-post',
'excerpt' => 'Older excerpt',
'body' => "## Markdown heading\n\nA **bold** and *emphasized* phrase with `inline code`, a [safe link](https://example.com), an [unsafe link](javascript:alert), and an [encoded unsafe link](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);
$datedPost = $posts->create([
'title' => 'Dated draft',
'slug' => 'dated-draft',
'excerpt' => '',
'body' => " Draft body\n",
'category_id' => '',
'status' => 'draft',
'published_at' => $pastPublication,
]);
$secondPost = $posts->create([
'title' => 'Second post',
'slug' => 'second-post',
'excerpt' => '',
'body' => '',
'category_id' => $category['id'],
'status' => 'draft',
'published_at' => '',
]);
$_ENV['BASE_URL'] = 'https://blog.example';
$phpb_config = ['website_manager' => ['url' => '/website-manager'], 'general' => ['uploads_url' => '/uploads']];
$publishedPosts = $posts->getPublishedForListing();
assertBlog(count($publishedPosts) === 2, 'The public listing should exclude drafts.');
assertBlog($publishedPosts[0]['slug'] === $post['slug'] && $publishedPosts[0]['category_name'] === 'News', 'Published posts should be newest first and include their category name.');
assertBlog($publishedPosts[1]['slug'] === $olderPost['slug'], 'Older published posts should follow newer posts.');
$editorHtml = renderBlogEditor((int) $post['id']);
assertBlog(str_contains($editorHtml, '<textarea id="post-body" name="body"') && str_contains($editorHtml, 'Post body'), 'The visible fallback textarea should retain and submit the stored body value.');
assertBlog(str_contains($editorHtml, 'id="post-body-toolbar"') && str_contains($editorHtml, 'data-format="bold"') && str_contains($editorHtml, 'data-format="heading"'), 'The editor should provide accessible Markdown formatting controls.');
assertBlog(str_contains($editorHtml, 'data-format="list"') && str_contains($editorHtml, 'data-format="ordered-list"') && str_contains($editorHtml, 'data-format="quote"') && str_contains($editorHtml, 'data-format="horizontal-rule"') && str_contains($editorHtml, 'data-format="code-block"'), 'The editor toolbar should offer unordered and ordered lists, quotes, horizontal rules, and code blocks.');
assertBlog(str_contains($editorHtml, 'id="post-body-editor"') && str_contains($editorHtml, 'id="post-body-preview"') && str_contains($editorHtml, 'id="post-body-view-tabs"'), 'The editor should include a CodeMirror mount and a preview toggle in the editor workspace.');
assertBlog(str_contains($editorHtml, 'data-view="write"') && str_contains($editorHtml, 'data-view="preview"') && str_contains($editorHtml, 'role="tabpanel"') && str_contains($editorHtml, 'aria-live="polite"'), 'The editor and preview tabs should expose accessible panels and status.');
assertBlog(str_contains($editorHtml, 'name="featured_image_id"') && str_contains($editorHtml, 'value="blog-cover-1" selected'), 'The editor should select a post featured image.');
assertBlog(!str_contains($editorHtml, 'notes.pdf'), 'The featured-image selector should omit non-image uploads.');
assertBlog(str_contains($editorHtml, 'id="post-inline-image"') && str_contains($editorHtml, 'id="insert-post-inline-image"'), 'The editor should offer a control for inserting inline images.');
assertBlog(str_contains($editorHtml, 'data-url="https://blog.example/uploads/blog-cover-1/cover.jpg"') && str_contains($editorHtml, 'data-alt="A &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, 'src="https://blog.example/uploads/blog-cover-1/cover.jpg" alt="A &quot;featured&quot; &amp; &lt;cover&gt;"'), 'The public listing should display a featured image with escaped alt text.');
assertBlog(strpos($listingHtml, 'first-post') < strpos($listingHtml, 'older-published-post'), 'The rendered listing should preserve newest-first order.');
assertBlog(!str_contains($listingHtml, 'dated-draft') && !str_contains($listingHtml, 'second-post'), 'Draft posts should not appear in the rendered listing.');
$detailHtml = renderBlogDetail('older-published-post');
assertBlog(str_contains($detailHtml, '<h1 class="text-3xl font-bold tracking-tight text-base-content sm:text-4xl">Older published post</h1>'), 'The detail block should resolve a published post from the named slug route parameter.');
assertBlog(str_contains($detailHtml, '<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.');
assertBlog(str_contains(renderBlogDetail('second-post'), 'Article not found'), 'A draft post should render a not-found state.');
assertBlog($datedPost['published_at'] === str_replace('T', ' ', $pastPublication) . ':00', 'A valid local publication date should be normalized for storage.');
assertBlog($datedPost['body'] === " Draft body\n", 'Post body whitespace should be preserved.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Invalid date', 'slug' => 'invalid-date', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => 'not-a-date',
]), 'Invalid publication dates should be rejected.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Future date', 'slug' => 'future-date', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => date('Y-m-d\\TH:i', time() + 86400),
]), 'Future publication dates should be rejected.');
$updated = $posts->update(['id' => $post['id']], [
'title' => 'Updated post',
'slug' => 'updated-post',
'excerpt' => '',
'body' => 'Updated body',
'featured_image_id' => '',
'category_id' => '',
'status' => 'draft',
'published_at' => '',
]);
assertBlog($updated === true, 'An existing post should update.');
$updatedPost = $posts->findWithId($post['id']);
assertBlog($updatedPost['title'] === 'Updated post' && $updatedPost['category_id'] === null && $updatedPost['published_at'] === null && $updatedPost['featured_image_id'] === null, 'Post updates should persist edited fields and clear optional values.');
assertBlog(is_array($secondPost), 'A draft with an empty body should be saved.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Duplicate post', 'slug' => 'second-post', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => '',
]), 'Duplicate post slugs should be rejected.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Bad slug', 'slug' => 'Invalid Slug', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => '',
]), 'Invalid post slugs should be rejected.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Bad status', 'slug' => 'bad-status', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'scheduled', 'published_at' => '',
]), 'Unsupported post statuses should be rejected.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Missing category', 'slug' => 'missing-category', 'excerpt' => '', 'body' => '', 'category_id' => '999', 'status' => 'draft', 'published_at' => '',
]), 'Unknown categories should be rejected.');
expectBlogValidation(fn() => $posts->create([
'title' => 'No body', 'slug' => 'no-body', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'published', 'published_at' => '',
]), 'Published posts should require body content.');
expectBlogValidation(fn() => $categories->create(['name' => 'Duplicate', 'slug' => 'news']), 'Duplicate category slugs should be rejected.');
expectBlogValidation(fn() => $categories->create(['name' => 'Bad slug', 'slug' => 'not a slug']), 'Invalid category slugs should be rejected.');
$updatedCategory = $categories->update(['id' => $category['id']], ['name' => 'Announcements', 'slug' => 'announcements']);
assertBlog($updatedCategory === true, 'An existing category should update.');
assertBlog($categories->destroy($category['id']) === true, 'A category should be deleted.');
assertBlog($posts->findWithId($secondPost['id'])['category_id'] === null, 'Deleting a category should detach its posts.');
assertBlog($posts->destroy($secondPost['id']) === true, 'A post should be deleted.');
assertBlog($posts->destroy($datedPost['id']) === true, 'A dated post should be deleted.');
assertBlog($posts->destroy($olderPost['id']) === true, 'An older published post should be deleted.');
assertBlog($posts->destroy($post['id']) === true, 'The remaining draft should be deleted.');
assertBlog($categories->findWithId($category['id']) === null && $posts->findWithId($secondPost['id']) === null, 'Deleted records should no longer be found.');
assertBlog(str_contains(renderBlogListing(), 'No published posts yet.'), 'The listing should show an empty state when no posts are published.');
$phpb_config = ['website_manager' => ['url' => '/website-manager']];
$_GET = [];
assertBlog(str_contains(renderBlogAdminList(), 'No posts yet'), 'The admin list should show its empty-list state when no posts exist.');
for ($index = 1; $index <= 12; $index++) {
$number = str_pad((string) $index, 2, '0', STR_PAD_LEFT);
$batchPost = $posts->create([
'title' => 'Pagination batch ' . $number,
'slug' => 'pagination-batch-' . $number,
'excerpt' => 'Batch excerpt',
'body' => 'Batch body',
'category_id' => '',
'status' => $index === 12 ? 'draft' : 'published',
'published_at' => '2025-01-' . $number . 'T00:00',
]);
$phpb_db->query('UPDATE test_ext__blog_posts SET updated_at = ? WHERE id = ?', ['2025-02-' . $number . ' 00:00:00', $batchPost['id']]);
}
foreach ([
'title' => 'TitleSearchMarker',
'slug' => 'slugsearchmarker',
'excerpt' => 'ExcerptSearchMarker',
'body' => 'BodySearchMarker',
] as $field => $term) {
$fieldPost = [
'title' => 'Field-only test post',
'slug' => 'field-only-test-post',
'excerpt' => 'Field-only excerpt',
'body' => 'Field-only body',
'category_id' => '',
'status' => 'published',
'published_at' => '2025-03-01T00:00',
];
$fieldPost[$field] = $term;
$fieldPost['slug'] = $field === 'slug' ? $term : 'field-only-' . $field;
$fieldPost = $posts->create($fieldPost);
$adminMatch = $posts->getPageForAdmin($term, 1);
$publicMatch = $posts->getPageForListing($term, 1);
assertBlog($adminMatch['total'] === 1 && $adminMatch['posts'][0]['slug'] === $fieldPost['slug'], 'Admin search should match the ' . $field . ' field.');
assertBlog($publicMatch['total'] === 1 && $publicMatch['posts'][0]['slug'] === $fieldPost['slug'], 'Public search should match the ' . $field . ' field.');
}
foreach ([
['term' => '100%', 'match' => 'literal-percent', 'title' => 'Price 100% complete', 'decoy' => 'wildcard-percent-decoy', 'decoyTitle' => 'Price 100X complete'],
['term' => 'under_score', 'match' => 'literal-underscore', 'title' => 'under_score example', 'decoy' => 'wildcard-underscore-decoy', 'decoyTitle' => 'underXscore example'],
['term' => 'bang!mark', 'match' => 'literal-escape-character', 'title' => 'bang!mark example', 'decoy' => 'escape-character-decoy', 'decoyTitle' => 'bangXmark example'],
] as $literalSearch) {
foreach ([[$literalSearch['match'], $literalSearch['title']], [$literalSearch['decoy'], $literalSearch['decoyTitle']]] as [$slug, $title]) {
$posts->create([
'title' => $title,
'slug' => $slug,
'excerpt' => '',
'body' => 'Search wildcard regression test',
'category_id' => '',
'status' => 'published',
'published_at' => '2025-03-01T00:00',
]);
}
$adminMatch = $posts->getPageForAdmin($literalSearch['term'], 1);
$publicMatch = $posts->getPageForListing($literalSearch['term'], 1);
assertBlog($adminMatch['total'] === 1 && $adminMatch['posts'][0]['slug'] === $literalSearch['match'], 'Admin search should treat LIKE metacharacters literally.');
assertBlog($publicMatch['total'] === 1 && $publicMatch['posts'][0]['slug'] === $literalSearch['match'], 'Public search should treat LIKE metacharacters literally.');
}
$adminFirstPage = $posts->getPageForAdmin('pagination', 1);
$adminLastPage = $posts->getPageForAdmin('pagination', 2);
assertBlog($adminFirstPage['total'] === 12 && count($adminFirstPage['posts']) === 10, 'Admin pagination should report all matching posts and cap each page at ten.');
assertBlog($adminFirstPage['posts'][0]['slug'] === 'pagination-batch-12' && $adminFirstPage['posts'][9]['slug'] === 'pagination-batch-03', 'Admin pages should preserve the newest-updated-first order.');
assertBlog(count($adminLastPage['posts']) === 2 && $adminLastPage['posts'][0]['slug'] === 'pagination-batch-02', 'The admin final page should contain the remaining posts in order.');
assertBlog($posts->getPageForAdmin('pagination', 0)['posts'][0]['slug'] === 'pagination-batch-12', 'Invalid low page numbers should normalize to the first page.');
assertBlog($posts->getPageForAdmin('pagination', PHP_INT_MAX)['posts'][0]['slug'] === 'pagination-batch-02', 'Oversized page numbers should safely resolve to the last matching page.');
$publicFirstPage = $posts->getPageForListing('pagination', 1);
$publicLastPage = $posts->getPageForListing('pagination', 2);
assertBlog($publicFirstPage['total'] === 11 && count($publicFirstPage['posts']) === 10, 'Public pagination should exclude the matching draft and report published totals.');
assertBlog($publicFirstPage['posts'][0]['slug'] === 'pagination-batch-11', 'Public pages should preserve newest-published-first order.');
assertBlog(count($publicLastPage['posts']) === 1 && $publicLastPage['posts'][0]['slug'] === 'pagination-batch-01', 'The public final page should contain its remaining published post.');
$noMatches = $posts->getPageForAdmin("pagination' OR '1'='1", 1);
assertBlog($noMatches['total'] === 0 && $noMatches['posts'] === [], 'Search input should be treated as a value rather than SQL.');
$_SERVER['HTTPS'] = 'on';
$_SERVER['SERVER_NAME'] = 'blog.example';
$_SERVER['SERVER_PORT'] = 443;
$_ENV['BASE_URL'] = 'https://blog.example/app';
$_SERVER['REQUEST_URI'] = '/app/news?keep=old';
$_GET = ['q' => 'pagination', 'page' => '2'];
$publicSearchPage = renderBlogListing();
assertBlog(str_contains($publicSearchPage, 'Pagination batch 01') && !str_contains($publicSearchPage, 'Pagination batch 11'), 'The public block should render only the requested search page.');
assertBlog(str_contains($publicSearchPage, 'action="https://blog.example/app/news"') && str_contains($publicSearchPage, 'name="q" value="pagination"'), 'The public search form should submit to the current path and retain its search value.');
assertBlog(str_contains($publicSearchPage, 'href="https://blog.example/app/news?q=pagination&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");
}
@@ -0,0 +1,26 @@
<?php
$snippet = \Plugi\Setting::get('ext--tracking--head') ?? '';
?>
<section class="card border border-base-300/60 bg-base-100 shadow-sm" aria-labelledby="tracking-settings-title">
<div class="card-body gap-5 p-4 sm:p-6 lg:p-8">
<div>
<h2 class="card-title text-xl" id="tracking-settings-title">Tracking snippet</h2>
<p class="mt-1 text-sm text-base-content/60">Add one HTML or JavaScript snippet to the public page head.</p>
</div>
<div class="alert alert-warning" role="alert">
<i class="ph ph-warning-circle" aria-hidden="true"></i>
<span>Saved code is inserted as-is and executes on every public page. Only save code you trust.</span>
</div>
<form method="post" action="<?= phpb_e(phpb_full_url('/ext--tracking/save')) ?>" class="space-y-4">
<?php phpb_csrf_field(); ?>
<div class="form-control w-full">
<label class="label" for="tracking-snippet">
<span class="label-text">HTML / JavaScript</span>
</label>
<textarea id="tracking-snippet" name="snippet" rows="14" spellcheck="false" class="textarea textarea-bordered w-full font-mono"><?= phpb_e($snippet) ?></textarea>
</div>
<button type="submit" class="btn btn-primary">Save snippet</button>
</form>
</div>
</section>
+9
View File
@@ -0,0 +1,9 @@
<?php
return [
'title' => 'Tracking',
'author' => 'Paul Spenke',
'identifier' => 'tracking',
'licence' => 'MIT',
'version' => '1.0.0',
];
@@ -0,0 +1,16 @@
<?php
use Plugi\Extensions;
use Plugi\Setting;
Extensions::addRoutes([
'/ext--tracking/save' => __DIR__ . '/routes/save.php',
]);
Extensions::registerBackend('tracking', [
'title' => 'Tracking',
'include' => __DIR__ . '/admin/tracking.php',
'icon' => '<i class="ph ph-code"></i>',
]);
Extensions::registerHtmlBlock(static fn (): string => Setting::get('ext--tracking--head') ?? '', 'head');
@@ -0,0 +1,22 @@
<?php
phpb_requires_authenticated();
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !phpb_validate_csrf()) {
http_response_code(403);
exit('Forbidden');
}
if (!isset($_POST['snippet']) || !is_string($_POST['snippet'])) {
http_response_code(400);
exit('Invalid snippet');
}
$saved = (new \Plugi\Repositories\SettingRepository())->updateSettings([
'ext--tracking--head' => $_POST['snippet'],
]);
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--tracking']), [
'message-type' => $saved ? 'success' : 'error',
'message' => $saved ? 'Tracking snippet saved.' : 'Tracking snippet could not be saved.',
]);
@@ -0,0 +1,185 @@
<?php
require_once __DIR__ . '/../../../plugi-core/src/Contracts/SettingRepositoryContract.php';
require_once __DIR__ . '/../../../plugi-core/src/Core/DB.php';
require_once __DIR__ . '/../../../plugi-core/src/Extensions.php';
require_once __DIR__ . '/../../../plugi-core/src/Repositories/BaseRepository.php';
require_once __DIR__ . '/../../../plugi-core/src/Repositories/SettingRepository.php';
require_once __DIR__ . '/../../../plugi-core/src/Contracts/SettingContract.php';
require_once __DIR__ . '/../../../plugi-core/src/Setting.php';
function phpb_remove_non_alpha_numeric(string $value): string
{
return preg_replace('/\W*/', '', $value);
}
class TrackingTestDatabase extends \Plugi\Core\DB
{
public function __construct()
{
$this->pdo = new PDO('sqlite::memory:');
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->exec('CREATE TABLE settings (id INTEGER PRIMARY KEY AUTOINCREMENT, setting TEXT NOT NULL UNIQUE, value TEXT NOT NULL, is_array INTEGER NOT NULL DEFAULT 0)');
$this->databaseName = 'tracking_test';
}
}
class TrackingTestRedirect extends RuntimeException
{
public function __construct(public string $url, public array $flashData)
{
parent::__construct('Redirect requested.');
}
}
class TrackingTestAuthenticationRequired extends RuntimeException
{
}
function phpb_requires_authenticated(): void
{
if (!($GLOBALS['trackingTestAuthenticated'] ?? false)) {
throw new TrackingTestAuthenticationRequired();
}
}
function phpb_validate_csrf(): bool
{
return $GLOBALS['trackingTestCsrfValid'] ?? false;
}
function phpb_e(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
function phpb_csrf_field(): void
{
echo '<input type="hidden" name="_token" value="test">';
}
function phpb_full_url(string $path): string
{
return '/plugi' . $path;
}
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 TrackingTestRedirect($url, $flashData);
}
require __DIR__ . '/../extension.php';
if (realpath(\Plugi\Extensions::getRoute('/ext--tracking/save')) !== realpath(__DIR__ . '/../routes/save.php')) {
throw new RuntimeException('The Tracking save route should be registered.');
}
if (realpath(\Plugi\Extensions::getBackends()['ext--tracking']['include'] ?? '') !== realpath(__DIR__ . '/../admin/tracking.php')) {
throw new RuntimeException('The Tracking Website Manager backend should be registered.');
}
$_ENV['DATABASE_PREFIX'] = '';
$phpb_db = new TrackingTestDatabase();
ob_start();
require __DIR__ . '/../admin/tracking.php';
$trackingEditor = ob_get_clean();
if (!str_contains($trackingEditor, 'action="/plugi/ext--tracking/save"')) {
throw new RuntimeException('The Tracking editor should post to its registered extension route.');
}
if (($argv[1] ?? null) === 'csrf-rejection') {
$snippet = '<script>window.tracking = "saved";</script>';
(new \Plugi\Repositories\SettingRepository())->updateSettings([
'ext--tracking--head' => $snippet,
]);
$GLOBALS['trackingTestAuthenticated'] = true;
$GLOBALS['trackingTestCsrfValid'] = false;
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = ['snippet' => '<script>window.tracking = "invalid-csrf";</script>'];
register_shutdown_function(static function () use ($phpb_db, $snippet): void {
if (http_response_code() !== 403) {
fwrite(STDERR, "Invalid CSRF should return HTTP 403.\n");
exit(1);
}
$saved = $phpb_db->select('SELECT value FROM settings WHERE setting = ?', ['ext--tracking--head']);
if (($saved[0]['value'] ?? null) !== $snippet) {
fwrite(STDERR, "Invalid CSRF must not change the saved snippet.\n");
exit(1);
}
fwrite(STDOUT, "PASS: authenticated invalid-CSRF requests are rejected without changing the saved snippet.\n");
});
require __DIR__ . '/../routes/save.php';
throw new RuntimeException('Authenticated requests with invalid CSRF should be rejected.');
}
if (\Plugi\Extensions::getHtmlBlocks('head') !== '') {
throw new RuntimeException('An unset tracking snippet should add no head output.');
}
$GLOBALS['trackingTestAuthenticated'] = true;
$GLOBALS['trackingTestCsrfValid'] = true;
$_SERVER['REQUEST_METHOD'] = 'POST';
$snippet = "<script>window.tracking = 'saved';</script>";
$_POST = ['snippet' => $snippet];
try {
require __DIR__ . '/../routes/save.php';
} catch (TrackingTestRedirect $redirect) {
if ($redirect->url !== 'website_manager?tab=ext--tracking' || $redirect->flashData['message-type'] !== 'success') {
throw new RuntimeException('Saving should redirect back to the Tracking editor with success feedback.');
}
}
$saved = $phpb_db->select('SELECT value FROM settings WHERE setting = ?', ['ext--tracking--head']);
if (($saved[0]['value'] ?? null) !== $snippet) {
throw new RuntimeException('The submitted snippet should be persisted unchanged.');
}
$settingsProperty = new ReflectionProperty(\Plugi\Setting::class, 'settings');
$settingsProperty->setValue(null, null);
if (\Plugi\Extensions::getHtmlBlocks('head') !== $snippet) {
throw new RuntimeException('The saved tracking snippet should be emitted unchanged in head output.');
}
$GLOBALS['trackingTestAuthenticated'] = false;
$_POST['snippet'] = '<script>window.tracking = "unauthorized";</script>';
try {
require __DIR__ . '/../routes/save.php';
throw new RuntimeException('Unauthenticated requests should be rejected.');
} catch (TrackingTestAuthenticationRequired) {
}
$saved = $phpb_db->select('SELECT value FROM settings WHERE setting = ?', ['ext--tracking--head']);
if (($saved[0]['value'] ?? null) !== $snippet) {
throw new RuntimeException('Unauthenticated requests must not change the saved snippet.');
}
$process = proc_open([PHP_BINARY, __FILE__, 'csrf-rejection'], [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
], $pipes);
if (!is_resource($process)) {
throw new RuntimeException('Could not start the invalid-CSRF route test.');
}
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
$error = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$status = proc_close($process);
if ($status !== 0 || !str_contains($output, 'PASS: authenticated invalid-CSRF requests are rejected')) {
throw new RuntimeException(sprintf('The invalid-CSRF route test failed (status %d): %s%s', $status, $output, $error));
}
fwrite(STDOUT, "PASS: tracking snippets are saved unchanged; authentication and CSRF are required.\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": {
+7 -3
View File
@@ -68,10 +68,10 @@ class Extensions
/**
* Register an HtmlBlock.
* @param string $html
* @param string|callable $html
* @param string $location
*/
public static function registerHtmlBlock(string $html, string $location = 'head') {
public static function registerHtmlBlock(string|callable $html, string $location = 'head') {
self::$htmlBlocks[$location][] = $html;
}
@@ -245,7 +245,11 @@ class Extensions
*/
public static function getHtmlBlocks(string $location = 'head'): string
{
return implode('', self::$htmlBlocks[$location]);
$html = '';
foreach (self::$htmlBlocks[$location] as $block) {
$html .= is_string($block) ? $block : $block();
}
return $html;
}
/**
@@ -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>
@@ -1,6 +1,7 @@
<?php
use Plugi\Extensions;
use Plugi\Setting;
$activeLanguages = phpb_active_languages();
?>
@@ -104,57 +105,59 @@ $activeLanguages = phpb_active_languages();
</section>
</div>
<div id="settings-panel-3" class="space-y-6" role="tabpanel" aria-labelledby="settings-tab-3" tabindex="0" x-show="activeTab === 3">
<div class="flex flex-col gap-4">
<?php foreach (Extensions::getConfigs() as $extKey => $config):
if (count(Extensions::getSettings($extKey)) === 0) {
continue;
} ?>
<details class="collapse collapse-arrow border border-base-300 bg-base-100">
<summary class="collapse-title text-lg font-semibold"><?= phpb_e(
$config["title"],
) ?></summary>
<div class="collapse-content">
<div class="space-y-4">
<?php foreach (
Extensions::getSettings($extKey)
as $setting
): ?>
<?php if ($setting["type"] === "text"): ?>
<label class="form-control w-full gap-2">
<span class="label-text"><?= phpb_e(
$setting["label"] ?:
$setting["name"],
) ?></span>
<input type="text" name="<?= phpb_e(
$setting["key"],
) ?>" value="<?= phpb_e(
<?php foreach (Extensions::getConfigs() as $extKey => $config):
$extensionSettings = Extensions::getSettings($extKey);
$activationKey = "extensions--{$extKey}--enabled";
?>
<section class="space-y-4 rounded-box border border-base-300 bg-base-100 p-4 sm:p-6">
<div class="flex items-center justify-between gap-4">
<h3 class="text-lg font-semibold"><?= phpb_e($config["title"]) ?></h3>
<label class="label cursor-pointer gap-3">
<span class="label-text">Enabled</span>
<input type="hidden" name="<?= phpb_e($activationKey) ?>" value="0">
<input type="checkbox" name="<?= phpb_e($activationKey) ?>" value="1" class="toggle toggle-primary" aria-label="Enable <?= phpb_e($config["title"]) ?>" <?= Setting::get($activationKey) === "1" ? "checked" : "" ?> />
</label>
</div>
<?php if ($extensionSettings !== []): ?>
<details class="collapse collapse-arrow border border-base-300 bg-base-100">
<summary class="collapse-title text-base font-semibold">Extension settings</summary>
<div class="collapse-content">
<div class="space-y-4">
<?php foreach ($extensionSettings as $setting): ?>
<?php if ($setting["type"] === "text"): ?>
<label class="form-control w-full gap-2">
<span class="label-text"><?= phpb_e(
$setting["label"] ?: $setting["name"],
) ?></span>
<input type="text" name="<?= phpb_e(
$setting["key"],
) ?>" value="<?= phpb_e(
$setting["value"],
) ?>" class="input input-bordered w-full" />
</label>
<?php endif; ?>
<?php if ($setting["type"] === "toggle"): ?>
<div class="form-control" x-data="{state: <?= phpb_e(
$setting["value"],
) ?>}">
<label class="label cursor-pointer">
<span class="label-text"><?= phpb_e(
$setting["label"] ?:
$setting["name"],
) ?></span>
<input type='hidden' :value="state" name="<?= phpb_e(
$setting["key"],
) ?>">
<input type="checkbox" class="toggle" x-model="state" />
</label>
</div>
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
<?php if ($setting["type"] === "toggle"): ?>
<div class="form-control" x-data="{state: <?= phpb_e(
$setting["value"],
) ?>}">
<label class="label cursor-pointer">
<span class="label-text"><?= phpb_e(
$setting["label"] ?: $setting["name"],
) ?></span>
<input type='hidden' :value="state" name="<?= phpb_e(
$setting["key"],
) ?>">
<input type="checkbox" class="toggle" x-model="state" />
</label>
</div>
<?php endif; ?>
<?php endforeach; ?>
</div>
</div>
</div>
</details>
<?php
endforeach; ?>
</div>
</details>
<?php endif; ?>
</section>
<?php endforeach; ?>
</div>
<div class="flex justify-end border-t border-base-300 pt-6">
<button type="submit" class="btn btn-primary">
+21 -10
View File
@@ -82,6 +82,7 @@ class Plugi
$this->setDatabaseConnection();
$this->checkDatabaseDefinition();
$this->hydrateConfig();
$this->loadEnabledExtensions();
}
// init the default authentication, if enabled
@@ -160,20 +161,10 @@ class Plugi
$extensionFile = 'extensions/' . $extFolder . '/extension.php';
$configFile = 'extensions/' . $extFolder . '/config.php';
if ($entry->isDir() && ! $entry->isDot() && file_exists($extensionFile) && file_exists($configFile)) {
require $extensionFile;
$extConfig = include($configFile);
$extConfig['dir'] = 'extensions/' . $extFolder;
$extKey = $extConfig['identifier'];
Extensions::registerConfig($extKey, $extConfig);
if(array_key_exists('assets', $extConfig) && is_array($extConfig['assets'])){
foreach ($extConfig['assets'] as $asset) {
Extensions::registerAsset(
'/extensions/'.$extFolder.$asset['src'],
$asset['type'],
$asset['location'],
);
}
}
if(array_key_exists('settings', $extConfig) && is_array($extConfig['settings'])){
Extensions::addSettings(array_map(function ($setting) use($extKey){
$setting['key'] = 'ext--' . $extKey . '--' . $setting['name'];
@@ -186,6 +177,26 @@ class Plugi
}
}
public function loadEnabledExtensions()
{
foreach (Extensions::getConfigs() as $extKey => $extConfig) {
if (Setting::get('extensions--' . $extKey . '--enabled') !== '1') {
continue;
}
require $extConfig['dir'] . '/extension.php';
if (array_key_exists('assets', $extConfig) && is_array($extConfig['assets'])) {
foreach ($extConfig['assets'] as $asset) {
Extensions::registerAsset(
'/extensions/' . basename($extConfig['dir']) . $asset['src'],
$asset['type'],
$asset['location'],
);
}
}
}
}
/**
* Set the Plugi configuration to the given array.
*
+148
View File
@@ -0,0 +1,148 @@
<?php
use Plugi\Core\DB;
use Plugi\Extensions;
use Plugi\Plugi;
use Plugi\Setting;
chdir(dirname(__DIR__, 2));
require_once __DIR__ . '/../src/Extensions.php';
require_once __DIR__ . '/../src/Contracts/SettingContract.php';
require_once __DIR__ . '/../src/Contracts/SettingRepositoryContract.php';
require_once __DIR__ . '/../src/Setting.php';
require_once __DIR__ . '/../src/Core/DB.php';
require_once __DIR__ . '/../src/Repositories/BaseRepository.php';
require_once __DIR__ . '/../src/Repositories/SettingRepository.php';
require_once __DIR__ . '/../src/Plugi.php';
function phpb_config(string $key)
{
$value = $GLOBALS['phpb_config'];
foreach (explode('.', $key) as $part) {
if (! is_array($value) || ! array_key_exists($part, $value)) {
return null;
}
$value = $value[$part];
}
return $value;
}
function phpb_instance(string $name, array $params = []): ?string
{
return $name === 'setting' ? Setting::class : null;
}
function phpb_current_language(): string
{
return 'en';
}
function phpb_remove_non_alpha_numeric(string $value): string
{
return preg_replace('/[^a-zA-Z0-9]/', '', $value);
}
class ExtensionActivationTestDatabase extends DB
{
public function __construct()
{
$this->pdo = new PDO('sqlite::memory:');
$this->pdo->exec('CREATE TABLE settings (id INTEGER PRIMARY KEY AUTOINCREMENT, setting TEXT UNIQUE, value TEXT, is_array INTEGER)');
$this->databaseName = 'extension_activation_test';
}
public function setActivation(?string $value): void
{
if ($value === null) {
$statement = $this->pdo->prepare('DELETE FROM settings WHERE setting = ?');
$statement->execute(['extensions--form--enabled']);
return;
}
$statement = $this->pdo->prepare('INSERT OR REPLACE INTO settings (setting, value, is_array) VALUES (?, ?, 0)');
$statement->execute(['extensions--form--enabled', $value]);
}
}
class ExtensionActivationTestPlugi extends Plugi
{
public function setDatabaseConnection()
{
global $phpb_db;
$phpb_db = $GLOBALS['extensionActivationTestDatabase'];
}
public function checkDatabaseDefinition()
{
}
public function loadTranslations($language)
{
}
}
$database = new ExtensionActivationTestDatabase();
$GLOBALS['extensionActivationTestDatabase'] = $database;
$_ENV['DATABASE_PREFIX'] = '';
$settingValues = new ReflectionProperty(Setting::class, 'settings');
$registryDefaults = [
'settings' => [],
'configs' => [],
'backends' => [],
'routes' => [],
'blocks' => [],
'layouts' => [],
'assets' => ['header' => [], 'footer' => [], 'admin-header' => [], 'admin-footer' => []],
'htmlBlocks' => ['head' => [], 'body-start' => [], 'body-end' => [], 'admin-head' => [], 'admin-body-start' => [], 'admin-body-end' => []],
];
$config = [
'general' => ['language' => 'en'],
'storage' => ['use_database' => true],
'auth' => ['use_login' => false],
'website_manager' => ['use_website_manager' => false],
'theme' => ['folder' => dirname(__DIR__, 2) . '/themes', 'active_theme' => 'default'],
];
$boot = static function (?string $activationState) use ($database, $registryDefaults, $settingValues, $config): void {
$database->setActivation($activationState);
$settingValues->setValue(null, null);
foreach ($registryDefaults as $property => $value) {
(new ReflectionProperty(Extensions::class, $property))->setValue(null, $value);
}
new ExtensionActivationTestPlugi($config);
};
$boot('1');
if (! isset(Extensions::getRoutes()['/ext--form/submit'])
|| ! isset(Extensions::getBackends()['ext--form'])
|| ! isset(Extensions::getBlocks()['form-wrapper'])) {
throw new RuntimeException('A persisted enabled state should register the extension during bootstrap.');
}
if (! str_contains(Extensions::getHeaderAssets(), '/extensions/plugi-ext-form/assets/dist.css')
|| ! str_contains(Extensions::getFooterAssets(), '/extensions/plugi-ext-form/assets/dist.js')) {
throw new RuntimeException('A persisted enabled state should register config-declared assets during bootstrap.');
}
$boot('0');
if (Extensions::getRoutes() !== [] || Extensions::getBackends() !== [] || Extensions::getBlocks() !== []) {
throw new RuntimeException('A persisted disabled state should not register runtime features during bootstrap.');
}
if (Extensions::getHeaderAssets() !== '' || Extensions::getFooterAssets() !== '' || Extensions::getHtmlBlocks('head') !== '') {
throw new RuntimeException('A persisted disabled state should not register assets or HTML hooks during bootstrap.');
}
$configs = Extensions::getConfigs();
if (! isset($configs['form']['settings'][0]['name']) || $configs['form']['settings'][0]['name'] !== 'email') {
throw new RuntimeException('Disabled extensions should retain their settings metadata.');
}
$db = (new ReflectionClass(DB::class))->newInstanceWithoutConstructor();
if (! isset($db->getDBDefinition()['ext__form_entries'])) {
throw new RuntimeException('Disabled extensions should retain their schema definitions.');
}
$boot(null);
if (Extensions::getRoutes() !== [] || Extensions::getBackends() !== [] || Extensions::getBlocks() !== []) {
throw new RuntimeException('An absent activation state should remain disabled during bootstrap.');
}
fwrite(STDOUT, "PASS: bootstrap loads only extensions with a persisted enabled state.\n");
@@ -0,0 +1,25 @@
<?php
use Plugi\Extensions;
require_once __DIR__ . '/../src/Extensions.php';
$callbackValue = '<script>window.tracking = "first";</script>';
Extensions::registerHtmlBlock('<meta name="static" content="unchanged">', 'head');
Extensions::registerHtmlBlock(static function () use (&$callbackValue): string {
return $callbackValue;
}, 'head');
$expected = '<meta name="static" content="unchanged">' . $callbackValue;
if (Extensions::getHtmlBlocks('head') !== $expected) {
throw new RuntimeException('Static and callback HTML blocks should render in registration order.');
}
$callbackValue = '<script>window.tracking = "updated";</script>';
$expected = '<meta name="static" content="unchanged">' . $callbackValue;
if (Extensions::getHtmlBlocks('head') !== $expected) {
throw new RuntimeException('HTML-block callbacks should be evaluated each time their location is retrieved.');
}
fwrite(STDOUT, "PASS: HTML blocks render strings and lazy callbacks.\n");
+136
View File
@@ -0,0 +1,136 @@
<?php
use Plugi\Core\DB;
use Plugi\Extensions;
use Plugi\Plugi;
use Plugi\Repositories\SettingRepository;
use Plugi\Setting;
chdir(dirname(__DIR__, 2));
require_once __DIR__ . '/../src/Extensions.php';
require_once __DIR__ . '/../src/Contracts/SettingContract.php';
require_once __DIR__ . '/../src/Contracts/SettingRepositoryContract.php';
require_once __DIR__ . '/../src/Setting.php';
require_once __DIR__ . '/../src/Core/DB.php';
require_once __DIR__ . '/../src/Repositories/BaseRepository.php';
require_once __DIR__ . '/../src/Repositories/SettingRepository.php';
require_once __DIR__ . '/../src/Plugi.php';
function phpb_active_languages(): array
{
return ['en' => []];
}
function phpb_config(string $key): ?string
{
return match ($key) {
'general.language' => 'en',
'theme.active_theme' => 'default',
default => null,
};
}
function phpb_csrf_field(): void
{
echo '<input type="hidden" name="_csrf_token" value="test-token">';
}
function phpb_e($value): string
{
return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}
function phpb_instance(string $name): string
{
return Setting::class;
}
function phpb_themes(): array
{
return ['default' => ['title' => 'Default']];
}
function phpb_trans(string $key): array|string
{
return $key === 'languages' ? ['en' => 'English'] : $key;
}
function phpb_url(string $module, array $parameters = []): string
{
return '/' . $module;
}
function phpb_remove_non_alpha_numeric(string $value): string
{
return preg_replace('/[^a-zA-Z0-9]/', '', $value);
}
class ExtensionSettingsTestDatabase extends DB
{
public function __construct()
{
$this->pdo = new PDO('sqlite::memory:');
$this->pdo->exec('CREATE TABLE settings (id INTEGER PRIMARY KEY AUTOINCREMENT, setting TEXT, value TEXT, is_array INTEGER)');
$this->databaseName = 'extension_settings_test';
}
}
$settingValues = new ReflectionProperty(Setting::class, 'settings');
$settingValues->setValue(null, []);
$plugi = new Plugi();
$plugi->loadExtensions();
Extensions::addSettings([[
'name' => 'enabled',
'key' => 'ext--form--enabled',
'type' => 'text',
'label' => 'Extension field named enabled',
'default' => '',
]]);
$renderSettings = static function (): string {
ob_start();
require __DIR__ . '/../src/Modules/WebsiteManager/resources/views/tabs/settings.php';
return ob_get_clean();
};
$uncheckedSettings = $renderSettings();
foreach (Extensions::getConfigs() as $extKey => $config) {
if (substr_count($uncheckedSettings, 'name="extensions--' . $extKey . '--enabled"') !== 2) {
throw new RuntimeException('Each discovered extension should submit both enabled and disabled values.');
}
}
if (preg_match('/<input type="checkbox" name="extensions--sitemap--enabled" value="1"[^>]*checked/', $uncheckedSettings)) {
throw new RuntimeException('An extension without a saved state should render disabled.');
}
if (strpos($uncheckedSettings, 'name="extensions--form--enabled" value="0"') > strpos($uncheckedSettings, 'name="extensions--form--enabled" value="1"')) {
throw new RuntimeException('The disabled value must precede the checkbox so checked values override it.');
}
if (substr_count($uncheckedSettings, 'name="ext--form--enabled"') !== 1) {
throw new RuntimeException('An extension setting named enabled should not share the activation control name.');
}
$settingValues->setValue(null, ['extensions--form--enabled' => '1', 'ext--form--enabled' => 'kept']);
$checkedSettings = $renderSettings();
if (! preg_match('/<input type="checkbox" name="extensions--form--enabled" value="1"[^>]*checked/', $checkedSettings)) {
throw new RuntimeException('An enabled extension should render its switch as checked.');
}
if (! preg_match('/<input type="text" name="ext--form--enabled" value="kept"/', $checkedSettings)) {
throw new RuntimeException('An extension setting named enabled should retain its submitted value.');
}
$_ENV['DATABASE_PREFIX'] = '';
$database = new ExtensionSettingsTestDatabase();
$phpb_db = $database;
$settingRepository = new SettingRepository();
if (! $settingRepository->updateSettings(['extensions--form--enabled' => '1'])
|| ! $settingRepository->updateSettings(['extensions--form--enabled' => '0'])) {
throw new RuntimeException('The settings repository should persist both enabled and disabled values.');
}
$saved = $database->select('SELECT value FROM settings WHERE setting = ?', ['extensions--form--enabled']);
if (($saved[0]['value'] ?? null) !== '0') {
throw new RuntimeException('Saving an unchecked extension switch should replace its earlier enabled state.');
}
fwrite(STDOUT, "PASS: extension switches render and persist explicit on/off values.\n");
@@ -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();