Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f35aadafe8 | ||
|
|
50b79fced9 | ||
|
|
45535204a2 | ||
|
|
345a99cf32 | ||
|
|
cf721b04b0 | ||
|
|
0a0c2d9d9b | ||
|
|
b8d75c88c2 | ||
|
|
1da5895309 | ||
|
|
78a283da6b |
@@ -1,10 +1,5 @@
|
|||||||
<FilesMatch "^\.">
|
|
||||||
Require all denied
|
|
||||||
</FilesMatch>
|
|
||||||
|
|
||||||
<IfModule mod_rewrite.c>
|
<IfModule mod_rewrite.c>
|
||||||
RewriteEngine On
|
RewriteEngine On
|
||||||
RewriteRule (^|/)\.(?!well-known/) - [F,L]
|
|
||||||
|
|
||||||
# Redirect non-www. to www. (except when on a subdomain)
|
# Redirect non-www. to www. (except when on a subdomain)
|
||||||
# RewriteCond %{HTTP_HOST} !^www\.
|
# RewriteCond %{HTTP_HOST} !^www\.
|
||||||
|
|||||||
+2
-3
@@ -2,9 +2,8 @@ FROM php:8.4-apache-bookworm
|
|||||||
WORKDIR "/var/www/html"
|
WORKDIR "/var/www/html"
|
||||||
|
|
||||||
RUN apt-get update; \
|
RUN apt-get update; \
|
||||||
|
docker-php-ext-install pdo_mysql; \
|
||||||
apt-get -y --no-install-recommends install \
|
apt-get -y --no-install-recommends install \
|
||||||
git \
|
git; \
|
||||||
libonig-dev; \
|
|
||||||
docker-php-ext-install mbstring pdo_mysql; \
|
|
||||||
apt-get clean; \
|
apt-get clean; \
|
||||||
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*
|
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*
|
||||||
|
|||||||
@@ -13,14 +13,6 @@ Plugi is a website boilerplate with a drag-and-drop page builder.
|
|||||||
|
|
||||||
See the [Plugi documentation](https://plugi.paulspenke.com/) for the full installation guide, including manual deployment, Docker development, security, and troubleshooting.
|
See the [Plugi documentation](https://plugi.paulspenke.com/) for the full installation guide, including manual deployment, Docker development, security, and troubleshooting.
|
||||||
|
|
||||||
## Multilingual pages
|
|
||||||
|
|
||||||
In Website Manager settings, enable the languages the site should use and select a default site language from that enabled list. Older installations without a saved `default_language` continue to use their saved `admin_language` value until a default is saved.
|
|
||||||
|
|
||||||
Each page translation has its own editable route. New routes use `/slug` for the default language and `/{locale}/slug` for other enabled languages. Saving a changed route adds a leading slash, removes trailing and repeated slashes (except `/`), and lowercases static path segments; route matching also ignores case and slash variants. Named parameters such as `{id}` and a trailing `*` wildcard remain supported.
|
|
||||||
|
|
||||||
Changing the default language affects new route suggestions but does not rewrite existing page URLs. Disabling a language makes its routes unavailable publicly while keeping its translations; re-enabling it restores those routes. See the [Plugi documentation](https://plugi.paulspenke.com/) for the full guide.
|
|
||||||
|
|
||||||
## Local Docker development
|
## Local Docker development
|
||||||
|
|
||||||
The supplied Compose stack uses PHP 8.4 and MySQL 8.0 and is for local development only. Copy `.env.dist` to `.env` and `config.dist.php` to `config.php`, replace the sample database and MySQL root passwords, then run:
|
The supplied Compose stack uses PHP 8.4 and MySQL 8.0 and is for local development only. Copy `.env.dist` to `.env` and `config.dist.php` to `config.php`, replace the sample database and MySQL root passwords, then run:
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ return [
|
|||||||
*/
|
*/
|
||||||
"general" => [
|
"general" => [
|
||||||
"language" => "en",
|
"language" => "en",
|
||||||
"timezone" => "UTC",
|
|
||||||
"assets_url" => "/plugi-core/dist",
|
"assets_url" => "/plugi-core/dist",
|
||||||
"uploads_url" => "/uploads",
|
"uploads_url" => "/uploads",
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
# 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.
|
|
||||||
|
|
||||||
Set `general.timezone` in the root `config.php` to the site's IANA timezone (for example, `Europe/Berlin`); it defaults to `UTC` and controls blog publication input and display. Publication dates are stored as site-local `DATETIME` values, so existing installations should configure the timezone that matches their existing post dates.
|
|
||||||
|
|
||||||
## Create the public pages
|
|
||||||
|
|
||||||
1. Create a regular Plugi page with the route `/blog` and add the **Published Posts** block. It lists published posts newest first; drafts are never shown. Public search matches titles, slugs, and excerpts (at least three characters), not full post bodies.
|
|
||||||
2. Create another regular page with the route `/blog/{slug}` and add the **Blog Post** block. The core router supplies the named `slug` parameter to the block.
|
|
||||||
3. Apply the site’s normal page layout and theme to both pages. Their presentation remains controlled by the page builder and theme.
|
|
||||||
|
|
||||||
The detail block displays a not-found state for a missing, unknown, or unpublished slug. The blog blocks are not page-cached so publishing or editing content is reflected on the next request. Authors, tags, scheduling, RSS, and translated posts are not included in this release.
|
|
||||||
|
|
||||||
Keep `/blog` and `/blog/{slug}` unique among the site’s page routes.
|
|
||||||
|
|
||||||
## Authoring content and images
|
|
||||||
|
|
||||||
Write post bodies in Markdown using the syntax-highlighted source editor. Its toolbar inserts bold, italic, headings, links, unordered and ordered lists, blockquotes, horizontal rules, inline code, and fenced code blocks; the live preview uses the same server-side renderer as the public detail page. If JavaScript is unavailable, the source textarea remains usable and can still save the post. The detail page supports headings, paragraphs and line breaks, bold and italic text, inline code, links, ordered and unordered lists, blockquotes, horizontal rules, and fenced code blocks. Add a language identifier after the opening fence (for example, `php`) to enable language-specific highlighting. Bash, CSS, diff, HTML/XML, JavaScript/TypeScript, JSON, Markdown, PHP, Python, SQL, and YAML are highlighted; unlabeled blocks are auto-detected from this set, and other language labels remain plain text. Code-block contents are rendered as escaped text before highlighting. Raw HTML is displayed as text; links only render with relative URLs or `http`, `https`, and `mailto` schemes.
|
|
||||||
|
|
||||||
Choose a featured image from the existing Website Manager media library to show it on post cards and detail pages. Use the editor’s inline-image selector to insert Markdown image syntax at the body cursor; image alt text comes from the selected media item. Inline images render only with relative, `http`, or `https` sources. Unsafe link and image protocols are not rendered.
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
<?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];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,186 +0,0 @@
|
|||||||
<?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');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,219 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Plugi\Extensions\Blog;
|
|
||||||
|
|
||||||
use DateTimeImmutable;
|
|
||||||
use DateTimeZone;
|
|
||||||
use InvalidArgumentException;
|
|
||||||
use Plugi\Repositories\BaseRepository;
|
|
||||||
|
|
||||||
class PostsRepository extends BaseRepository
|
|
||||||
{
|
|
||||||
public const POSTS_PER_PAGE = 10;
|
|
||||||
public const MIN_PUBLIC_SEARCH_LENGTH = 3;
|
|
||||||
|
|
||||||
protected $table = 'ext__blog_posts';
|
|
||||||
|
|
||||||
public function create(array $data)
|
|
||||||
{
|
|
||||||
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 getPageForAdmin(string $search, int $page): array
|
|
||||||
{
|
|
||||||
return $this->getPostPage($search, $page, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getPageForListing(string $search, int $page): array
|
|
||||||
{
|
|
||||||
return $this->getPostPage($search, $page, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
private function getPostPage(string $search, int $page, bool $publishedOnly): array
|
|
||||||
{
|
|
||||||
$search = trim($search);
|
|
||||||
if ($publishedOnly && $search !== '' && mb_strlen($search) < self::MIN_PUBLIC_SEARCH_LENGTH) {
|
|
||||||
return ['posts' => [], 'total' => 0];
|
|
||||||
}
|
|
||||||
|
|
||||||
$categoriesTable = $_ENV['DATABASE_PREFIX'] . 'ext__blog_categories';
|
|
||||||
$uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads';
|
|
||||||
$from = $publishedOnly
|
|
||||||
? "FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id LEFT JOIN {$uploadsTable} featured_image ON featured_image.public_id = posts.featured_image_id AND LOWER(featured_image.mime_type) LIKE 'image/%'"
|
|
||||||
: "FROM {$this->table} posts";
|
|
||||||
$filters = [];
|
|
||||||
$parameters = [];
|
|
||||||
|
|
||||||
if ($publishedOnly) {
|
|
||||||
$filters[] = 'posts.status = ?';
|
|
||||||
$parameters[] = 'published';
|
|
||||||
}
|
|
||||||
if (trim($search) !== '') {
|
|
||||||
$filters[] = $publishedOnly
|
|
||||||
? '(posts.title LIKE ? ESCAPE \'!\' OR posts.slug LIKE ? ESCAPE \'!\' OR posts.excerpt LIKE ? ESCAPE \'!\')'
|
|
||||||
: '(posts.title LIKE ? ESCAPE \'!\' OR posts.slug LIKE ? ESCAPE \'!\' OR posts.excerpt LIKE ? ESCAPE \'!\' OR posts.body LIKE ? ESCAPE \'!\')';
|
|
||||||
$pattern = '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], trim($search)) . '%';
|
|
||||||
array_push($parameters, $pattern, $pattern, $pattern);
|
|
||||||
if (!$publishedOnly) {
|
|
||||||
$parameters[] = $pattern;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$where = $filters === [] ? '' : ' WHERE ' . implode(' AND ', $filters);
|
|
||||||
$total = $this->db->select("SELECT COUNT(*) AS total {$from}{$where}", $parameters)[0]['total'] ?? 0;
|
|
||||||
$page = min(max(1, $page), max(1, (int) ceil((int) $total / self::POSTS_PER_PAGE)));
|
|
||||||
$offset = ($page - 1) * self::POSTS_PER_PAGE;
|
|
||||||
$select = $publishedOnly
|
|
||||||
? 'SELECT posts.*, categories.name AS category_name, featured_image.public_id AS featured_image_public_id, featured_image.original_file AS featured_image_original_file, featured_image.alt_text AS featured_image_alt_text'
|
|
||||||
: 'SELECT posts.*';
|
|
||||||
$order = $publishedOnly ? 'posts.published_at DESC, posts.id DESC' : 'posts.updated_at DESC, posts.id DESC';
|
|
||||||
$posts = $this->db->select(
|
|
||||||
"{$select} {$from}{$where} ORDER BY {$order} LIMIT " . self::POSTS_PER_PAGE . " OFFSET {$offset}",
|
|
||||||
$parameters
|
|
||||||
);
|
|
||||||
if ($publishedOnly) {
|
|
||||||
$posts = array_map(fn(array $post): array => $this->resolveFeaturedImage($post), $posts);
|
|
||||||
}
|
|
||||||
|
|
||||||
return ['posts' => $posts, 'total' => (int) $total];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function findPublishedBySlug(string $slug): ?array
|
|
||||||
{
|
|
||||||
$categoriesTable = $_ENV['DATABASE_PREFIX'] . 'ext__blog_categories';
|
|
||||||
$uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads';
|
|
||||||
$posts = $this->db->select(
|
|
||||||
"SELECT posts.*, categories.name AS category_name, 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
|
|
||||||
{
|
|
||||||
$timezone = new DateTimeZone((string) (phpb_config('general.timezone') ?: 'UTC'));
|
|
||||||
if ($value === null || $value === '') {
|
|
||||||
return $status === 'published' ? (new DateTimeImmutable('now', $timezone))->format('Y-m-d H:i:s') : null;
|
|
||||||
}
|
|
||||||
if (!is_string($value)) {
|
|
||||||
throw new InvalidArgumentException('Enter a valid publication date.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$value = trim($value);
|
|
||||||
$format = str_contains($value, 'T') ? 'Y-m-d\\TH:i' : 'Y-m-d H:i:s';
|
|
||||||
$date = DateTimeImmutable::createFromFormat('!' . $format, $value, $timezone);
|
|
||||||
$errors = DateTimeImmutable::getLastErrors();
|
|
||||||
if ($date === false || ($errors !== false && ($errors['warning_count'] > 0 || $errors['error_count'] > 0)) || $date->format($format) !== $value) {
|
|
||||||
throw new InvalidArgumentException('Enter a valid publication date.');
|
|
||||||
}
|
|
||||||
if ($date > new DateTimeImmutable('now', $timezone)) {
|
|
||||||
throw new InvalidArgumentException('Publication dates cannot be in the future.');
|
|
||||||
}
|
|
||||||
|
|
||||||
return $date->format('Y-m-d H:i:s');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,193 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Plugi\Extensions\Blog\CategoriesRepository;
|
|
||||||
use Plugi\Extensions\Blog\PostsRepository;
|
|
||||||
use Plugi\Repositories\UploadRepository;
|
|
||||||
|
|
||||||
$postsRepository = new PostsRepository();
|
|
||||||
$timezone = new \DateTimeZone((string) (phpb_config('general.timezone') ?: 'UTC'));
|
|
||||||
$post = [
|
|
||||||
'title' => '',
|
|
||||||
'slug' => '',
|
|
||||||
'excerpt' => '',
|
|
||||||
'body' => '',
|
|
||||||
'featured_image_id' => null,
|
|
||||||
'category_id' => null,
|
|
||||||
'status' => 'draft',
|
|
||||||
'published_at' => null,
|
|
||||||
];
|
|
||||||
if (isset($_GET['id']) && ctype_digit((string) $_GET['id'])) {
|
|
||||||
$post = $postsRepository->findWithId($_GET['id']) ?? $post;
|
|
||||||
}
|
|
||||||
$isEditing = isset($post['id']);
|
|
||||||
$publishedAt = $post['published_at'] ? (new \DateTimeImmutable($post['published_at'], $timezone))->format('Y-m-d\TH:i') : '';
|
|
||||||
$categories = (new CategoriesRepository())->getAllForAdmin();
|
|
||||||
$imageUploads = array_values(array_filter((new UploadRepository())->getAll(), static fn($file): bool => is_string($file->mime_type ?? null) && str_starts_with(strtolower($file->mime_type), 'image/')));
|
|
||||||
?>
|
|
||||||
<header class="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
|
||||||
<div class="flex items-center gap-3">
|
|
||||||
<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">Times use the site timezone (<?= phpb_e($timezone->getName()) ?>). Leave blank to use the current time when publishing. Future dates are not supported.</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<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, '&').replace(/\[/g, '[').replace(/\]/g, ']');
|
|
||||||
const markdown = ``;
|
|
||||||
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>
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
<?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>
|
|
||||||
@@ -1,128 +0,0 @@
|
|||||||
<?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 "<?= phpb_e($search) ?>".
|
|
||||||
<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 (site time)</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>
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
.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
@@ -1,302 +0,0 @@
|
|||||||
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;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
});
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
<?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>
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
.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
@@ -1,33 +0,0 @@
|
|||||||
import hljs from 'highlight.js/lib/core';
|
|
||||||
import bash from 'highlight.js/lib/languages/bash';
|
|
||||||
import css from 'highlight.js/lib/languages/css';
|
|
||||||
import diff from 'highlight.js/lib/languages/diff';
|
|
||||||
import javascript from 'highlight.js/lib/languages/javascript';
|
|
||||||
import json from 'highlight.js/lib/languages/json';
|
|
||||||
import markdown from 'highlight.js/lib/languages/markdown';
|
|
||||||
import php from 'highlight.js/lib/languages/php';
|
|
||||||
import python from 'highlight.js/lib/languages/python';
|
|
||||||
import sql from 'highlight.js/lib/languages/sql';
|
|
||||||
import typescript from 'highlight.js/lib/languages/typescript';
|
|
||||||
import xml from 'highlight.js/lib/languages/xml';
|
|
||||||
import yaml from 'highlight.js/lib/languages/yaml';
|
|
||||||
|
|
||||||
Object.entries({ bash, css, diff, javascript, json, markdown, php, python, sql, typescript, xml, yaml })
|
|
||||||
.forEach(([name, language]) => hljs.registerLanguage(name, language));
|
|
||||||
|
|
||||||
window.blogCodeHighlighter = {
|
|
||||||
highlight(root = document) {
|
|
||||||
root.querySelectorAll('pre code:not(.hljs)').forEach((code) => {
|
|
||||||
const language = code.className.match(/(?:^|\s)language-([^\s]+)/)?.[1];
|
|
||||||
if (language && !hljs.getLanguage(language)) return;
|
|
||||||
hljs.highlightElement(code);
|
|
||||||
});
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
const highlightPage = () => window.blogCodeHighlighter.highlight(document);
|
|
||||||
if (document.readyState === 'loading') {
|
|
||||||
document.addEventListener('DOMContentLoaded', highlightPage, { once: true });
|
|
||||||
} else {
|
|
||||||
highlightPage();
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
return [
|
|
||||||
'title' => 'Blog Post',
|
|
||||||
'category' => 'Blog',
|
|
||||||
'icon' => 'ph ph-article',
|
|
||||||
'cache' => false,
|
|
||||||
];
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
$slug = phpb_route_parameter('slug');
|
|
||||||
$timezone = new \DateTimeZone((string) (phpb_config('general.timezone') ?: 'UTC'));
|
|
||||||
$post = is_string($slug) && $slug !== ''
|
|
||||||
? (new \Plugi\Extensions\Blog\PostsRepository())->findPublishedBySlug($slug)
|
|
||||||
: null;
|
|
||||||
?>
|
|
||||||
<?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 $publishedDate = date_create($post['published_at'], $timezone); ?>
|
|
||||||
<?php if ($publishedDate !== false): ?>
|
|
||||||
<time datetime="<?= phpb_e($publishedDate->format('c')) ?>"><?= phpb_e($publishedDate->format('F j, Y')) ?></time>
|
|
||||||
<?php endif; ?>
|
|
||||||
<?php endif; ?>
|
|
||||||
</div>
|
|
||||||
<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; ?>
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
return [
|
|
||||||
'title' => 'Published Posts',
|
|
||||||
'category' => 'Blog',
|
|
||||||
'icon' => 'ph ph-article',
|
|
||||||
'cache' => false,
|
|
||||||
];
|
|
||||||
@@ -1,91 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
$postsRepository = new \Plugi\Extensions\Blog\PostsRepository();
|
|
||||||
$timezone = new \DateTimeZone((string) (phpb_config('general.timezone') ?: 'UTC'));
|
|
||||||
$search = is_string($_GET['q'] ?? null) ? trim($_GET['q']) : '';
|
|
||||||
$pageValue = $_GET['page'] ?? null;
|
|
||||||
$page = is_string($pageValue) ? filter_var($pageValue, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) : false;
|
|
||||||
$page = $page === false ? 1 : $page;
|
|
||||||
$listingPath = isset($_SERVER['SERVER_NAME'], $_SERVER['REQUEST_URI']) ? phpb_full_url(phpb_current_relative_url(true)) : '/';
|
|
||||||
$pageResult = $postsRepository->getPageForListing($search, $page);
|
|
||||||
$searchTooShort = $search !== '' && mb_strlen($search) < \Plugi\Extensions\Blog\PostsRepository::MIN_PUBLIC_SEARCH_LENGTH;
|
|
||||||
$totalPages = max(1, (int) ceil($pageResult['total'] / \Plugi\Extensions\Blog\PostsRepository::POSTS_PER_PAGE));
|
|
||||||
if ($page > $totalPages) {
|
|
||||||
$page = $totalPages;
|
|
||||||
}
|
|
||||||
$posts = $pageResult['posts'];
|
|
||||||
$searchParameters = $search === '' ? [] : ['q' => $search];
|
|
||||||
?>
|
|
||||||
<section class="space-y-6" aria-label="Blog posts">
|
|
||||||
<form class="flex flex-col gap-3 sm:flex-row sm:items-end" method="get" action="<?= phpb_e($listingPath) ?>">
|
|
||||||
<label class="flex w-full max-w-md flex-col gap-2">
|
|
||||||
<span class="text-sm font-medium">Search titles, slugs, and excerpts (3+ characters)</span>
|
|
||||||
<input class="input w-full" type="search" name="q" value="<?= phpb_e($search) ?>" />
|
|
||||||
</label>
|
|
||||||
<button class="btn" type="submit">Search</button>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<?php if ($searchTooShort): ?>
|
|
||||||
<div class="alert alert-info" role="status">Enter at least <?= \Plugi\Extensions\Blog\PostsRepository::MIN_PUBLIC_SEARCH_LENGTH ?> characters to search.</div>
|
|
||||||
<?php elseif ($pageResult['total'] === 0): ?>
|
|
||||||
<div class="alert alert-info" role="status">
|
|
||||||
<?= $search === '' ? 'No published posts yet.' : 'No published posts match "' . phpb_e($search) . '".' ?>
|
|
||||||
</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 $publishedDate = date_create($post['published_at'], $timezone); ?>
|
|
||||||
<?php if ($publishedDate !== false): ?>
|
|
||||||
<time datetime="<?= phpb_e($publishedDate->format('c')) ?>"><?= phpb_e($publishedDate->format('F j, Y')) ?></time>
|
|
||||||
<?php endif; ?>
|
|
||||||
<?php endif; ?>
|
|
||||||
</div>
|
|
||||||
<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>
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
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,
|
|
||||||
});
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
<?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'],
|
|
||||||
],
|
|
||||||
],
|
|
||||||
],
|
|
||||||
];
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
<?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
@@ -1,582 +0,0 @@
|
|||||||
{
|
|
||||||
"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"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
{
|
|
||||||
"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"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
<?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.',
|
|
||||||
]);
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
<?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.',
|
|
||||||
]);
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
<?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.']);
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
<?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);
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
<?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);
|
|
||||||
@@ -1,118 +0,0 @@
|
|||||||
<?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"><code>safe</code></code>') && str_contains($payload['html'], '<code><script>alert(1)</script></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");
|
|
||||||
}
|
|
||||||
@@ -1,452 +0,0 @@
|
|||||||
<?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_';
|
|
||||||
$siteTimezone = 'Pacific/Kiritimati';
|
|
||||||
date_default_timezone_set('Pacific/Pago_Pago');
|
|
||||||
$phpb_config = ['website_manager' => ['url' => '/website-manager'], 'general' => ['uploads_url' => '/uploads', 'timezone' => $siteTimezone]];
|
|
||||||
$phpb_db = new BlogTestDatabase();
|
|
||||||
$phpb_db->createSchema();
|
|
||||||
assertBlog(isset($phpb_db->getDBDefinition()['ext__blog_posts'], $phpb_db->getDBDefinition()['ext__blog_categories']), 'The blog tables should be included in the core database definition.');
|
|
||||||
assertBlog(isset(\Plugi\Extensions::getBackends()['ext--blog']), 'The blog admin backend should be registered.');
|
|
||||||
assertBlog(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.');
|
|
||||||
$storedPublication = \DateTimeImmutable::createFromFormat('!Y-m-d H:i:s', $post['published_at'], new \DateTimeZone($siteTimezone));
|
|
||||||
assertBlog($storedPublication !== false && abs($storedPublication->getTimestamp() - time()) < 60, 'The automatic publication timestamp should use the configured site timezone.');
|
|
||||||
assertBlog($post['featured_image_id'] === 'blog-cover-1', 'A valid image upload reference should be persisted on the post.');
|
|
||||||
expectBlogValidation(fn() => $posts->create([
|
|
||||||
'title' => 'Missing featured image', 'slug' => 'missing-featured-image', 'excerpt' => '', 'body' => 'Body', 'featured_image_id' => 'missing-upload', 'category_id' => '', 'status' => 'draft', 'published_at' => '',
|
|
||||||
]), 'Missing upload references should be rejected.');
|
|
||||||
expectBlogValidation(fn() => $posts->create([
|
|
||||||
'title' => 'Non-image featured image', 'slug' => 'non-image-featured-image', 'excerpt' => '', 'body' => 'Body', 'featured_image_id' => 'blog-document-1', 'category_id' => '', 'status' => 'draft', 'published_at' => '',
|
|
||||||
]), 'Non-image upload references should be rejected.');
|
|
||||||
|
|
||||||
$olderPost = $posts->create([
|
|
||||||
'title' => 'Older published post',
|
|
||||||
'slug' => 'older-published-post',
|
|
||||||
'excerpt' => 'Older excerpt',
|
|
||||||
'body' => "## Markdown heading\n\nA **bold** and *emphasized* phrase with `inline code`, a [safe link](https://example.com), an [unsafe link](javascript:alert), and an [encoded unsafe link](javascript:alert).\n\n- first item\n- second item\n\n1. first numbered item\n2. second numbered item\n\n![Inline & ]](https://images.example/photo.jpg)\n\n\n\n\n<script>alert(\"x\")</script>&safe\n\n---\n\n> Quoted **text**.\n\n```php\n<script>alert(\"code\")</script>\n```\n\n~~~php\" onmouseover=\"alert(1)\n<script>alert(1)</script>\n~~~",
|
|
||||||
'category_id' => '',
|
|
||||||
'status' => 'published',
|
|
||||||
'published_at' => '2020-01-01T00:00',
|
|
||||||
]);
|
|
||||||
$pastPublication = (new \DateTimeImmutable('now', new \DateTimeZone($siteTimezone)))->modify('-1 hour')->format('Y-m-d\\TH:i');
|
|
||||||
$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';
|
|
||||||
|
|
||||||
$editorHtml = renderBlogEditor((int) $post['id']);
|
|
||||||
assertBlog(str_contains($editorHtml, 'site timezone (Pacific/Kiritimati)'), 'The editor should identify the timezone used for publication dates.');
|
|
||||||
assertBlog(str_contains($editorHtml, '<textarea id="post-body" name="body"') && str_contains($editorHtml, 'Post body'), 'The visible fallback textarea should retain and submit the stored body value.');
|
|
||||||
assertBlog(str_contains($editorHtml, 'id="post-body-toolbar"') && str_contains($editorHtml, 'data-format="bold"') && str_contains($editorHtml, 'data-format="heading"'), 'The editor should provide accessible Markdown formatting controls.');
|
|
||||||
assertBlog(str_contains($editorHtml, 'data-format="list"') && str_contains($editorHtml, 'data-format="ordered-list"') && str_contains($editorHtml, 'data-format="quote"') && str_contains($editorHtml, 'data-format="horizontal-rule"') && str_contains($editorHtml, 'data-format="code-block"'), 'The editor toolbar should offer unordered and ordered lists, quotes, horizontal rules, and code blocks.');
|
|
||||||
assertBlog(str_contains($editorHtml, 'id="post-body-editor"') && str_contains($editorHtml, 'id="post-body-preview"') && str_contains($editorHtml, 'id="post-body-view-tabs"'), 'The editor should include a CodeMirror mount and a preview toggle in the editor workspace.');
|
|
||||||
assertBlog(str_contains($editorHtml, 'data-view="write"') && str_contains($editorHtml, 'data-view="preview"') && str_contains($editorHtml, 'role="tabpanel"') && str_contains($editorHtml, 'aria-live="polite"'), 'The editor and preview tabs should expose accessible panels and status.');
|
|
||||||
assertBlog(str_contains($editorHtml, 'name="featured_image_id"') && str_contains($editorHtml, 'value="blog-cover-1" selected'), 'The editor should select a post featured image.');
|
|
||||||
assertBlog(!str_contains($editorHtml, 'notes.pdf'), 'The featured-image selector should omit non-image uploads.');
|
|
||||||
assertBlog(str_contains($editorHtml, 'id="post-inline-image"') && str_contains($editorHtml, 'id="insert-post-inline-image"'), 'The editor should offer a control for inserting inline images.');
|
|
||||||
assertBlog(str_contains($editorHtml, 'data-url="https://blog.example/uploads/blog-cover-1/cover.jpg"') && str_contains($editorHtml, 'data-alt="A "featured" & <cover>"'), 'The inline picker should expose escaped media URL and alt metadata.');
|
|
||||||
assertBlog(str_contains($editorHtml, 'selectionStart') && str_contains($editorHtml, 'setRangeText'), 'The inline picker should insert Markdown at the textarea cursor.');
|
|
||||||
assertBlog(str_contains($editorHtml, 'window.blogMarkdownEditor.insertAtCursor(markdown)'), 'The inline picker should insert at the CodeMirror cursor when the editor is initialized.');
|
|
||||||
$listingHtml = renderBlogListing();
|
|
||||||
assertBlog(str_contains($listingHtml, 'href="https://blog.example/blog/first-post"'), 'The listing should link to the configured post detail URL.');
|
|
||||||
assertBlog(str_contains($listingHtml, 'datetime="2020-01-01T00:00:00+14:00"'), 'Public listing dates should use the configured site timezone.');
|
|
||||||
assertBlog(str_contains($listingHtml, 'src="https://blog.example/uploads/blog-cover-1/cover.jpg" alt="A "featured" & <cover>"'), 'The public listing should display a featured image with escaped alt text.');
|
|
||||||
assertBlog(strpos($listingHtml, 'first-post') < strpos($listingHtml, 'older-published-post'), 'The rendered listing should preserve newest-first order.');
|
|
||||||
assertBlog(!str_contains($listingHtml, 'dated-draft') && !str_contains($listingHtml, 'second-post'), 'Draft posts should not appear in the rendered listing.');
|
|
||||||
$detailHtml = renderBlogDetail('older-published-post');
|
|
||||||
assertBlog(str_contains($detailHtml, 'datetime="2020-01-01T00:00:00+14:00"'), 'Public detail dates should use the configured site timezone.');
|
|
||||||
assertBlog(str_contains($detailHtml, '<h1 class="text-3xl font-bold tracking-tight text-base-content sm:text-4xl">Older published post</h1>'), 'The detail block should resolve a published post from the named slug route parameter.');
|
|
||||||
assertBlog(str_contains($detailHtml, '<h2 class="text-2xl font-bold tracking-tight">Markdown heading</h2>') && str_contains($detailHtml, '<strong>bold</strong>') && str_contains($detailHtml, '<em>emphasized</em>'), 'The detail block should render Markdown headings and emphasis.');
|
|
||||||
assertBlog(str_contains($detailHtml, '<a class="link link-hover" href="https://example.com">safe link</a>') && !str_contains($detailHtml, 'href="javascript:') && !str_contains($detailHtml, 'href="java'), 'The detail block should render safe links and reject unsafe protocols.');
|
|
||||||
assertBlog(str_contains($detailHtml, '<ul class="list-disc') && str_contains($detailHtml, '<li>first item</li>') && str_contains($detailHtml, '<li>second item</li>'), 'The detail block should render Markdown lists.');
|
|
||||||
assertBlog(str_contains($detailHtml, '<ol class="list-decimal') && str_contains($detailHtml, '<li>first numbered item</li>'), 'The detail block should render ordered Markdown lists.');
|
|
||||||
assertBlog(str_contains($detailHtml, '<code>inline code</code>'), 'The detail block should render inline code.');
|
|
||||||
assertBlog(str_contains($detailHtml, '<hr class="my-6 border-base-300">'), 'The detail block should render Markdown horizontal rules.');
|
|
||||||
assertBlog(str_contains($detailHtml, '<blockquote class="border-l-4 border-base-300 pl-4 text-base-content/80"><p>Quoted <strong>text</strong>.</p></blockquote>'), 'The detail block should render Markdown blockquotes with inline formatting.');
|
|
||||||
assertBlog(str_contains($detailHtml, '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code class="language-php"><script>alert("code")</script></code></pre>'), 'The detail block should add a language class and escape fenced code.');
|
|
||||||
assertBlog(str_contains($detailHtml, '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code><script>alert(1)</script></code></pre>') && !str_contains($detailHtml, 'onmouseover='), 'Malformed fence info should not create attributes, and its code should remain escaped.');
|
|
||||||
assertBlog(str_contains($detailHtml, '<img src="https://images.example/photo.jpg" alt="Inline & ]" class="max-w-full rounded-box">'), 'The detail block should render inline Markdown images with escaped alt text.');
|
|
||||||
assertBlog(!str_contains($detailHtml, 'src="javascript:') && !str_contains($detailHtml, 'src="java') && !str_contains($detailHtml, 'src="data:'), 'The detail block should reject unsafe image URL protocols.');
|
|
||||||
assertBlog(str_contains($detailHtml, '<script>alert("x")</script>&safe') && !str_contains($detailHtml, '<script>alert'), 'The detail block should escape raw HTML in post bodies.');
|
|
||||||
assertBlog(!str_contains($detailHtml, 'src="https://blog.example/uploads/blog-cover-1/cover.jpg"'), 'Posts without featured images should omit the featured-image URL.');
|
|
||||||
$plainTextHtml = renderBlogDetail('first-post');
|
|
||||||
assertBlog(str_contains($plainTextHtml, '<p>Post body</p>'), 'Existing plain-text post bodies should remain readable.');
|
|
||||||
assertBlog(str_contains($plainTextHtml, 'src="https://blog.example/uploads/blog-cover-1/cover.jpg" alt="A "featured" & <cover>"'), 'The public detail block should display a featured image with escaped alt text.');
|
|
||||||
$phpb_db->query('INSERT INTO test_uploads (public_id, original_file, mime_type, server_file, alt_text) VALUES (?, ?, ?, ?, ?)', [
|
|
||||||
'blog-cover-deleted', 'deleted.jpg', 'image/jpeg', 'deleted.jpg', 'Deleted cover',
|
|
||||||
]);
|
|
||||||
$deletedCoverPost = $posts->create([
|
|
||||||
'title' => 'Deleted featured image', 'slug' => 'deleted-featured-image', 'excerpt' => '', 'body' => 'Body', 'featured_image_id' => 'blog-cover-deleted', 'category_id' => '', 'status' => 'published', 'published_at' => '2019-01-01T00:00',
|
|
||||||
]);
|
|
||||||
$phpb_db->query('DELETE FROM test_uploads WHERE public_id = ?', ['blog-cover-deleted']);
|
|
||||||
assertBlog(!str_contains(renderBlogDetail('deleted-featured-image'), '<img'), 'Deleted featured-image uploads should be omitted from public detail pages.');
|
|
||||||
assertBlog(!str_contains(renderBlogListing(), 'deleted.jpg'), 'Deleted featured-image uploads should be omitted from public post cards.');
|
|
||||||
$posts->destroy($deletedCoverPost['id']);
|
|
||||||
assertBlog(str_contains(renderBlogDetail(null), 'Article not found'), 'A missing route slug should render a not-found state.');
|
|
||||||
assertBlog(str_contains(renderBlogDetail('unknown-post'), 'Article not found'), 'An unknown route slug should render a not-found state.');
|
|
||||||
assertBlog(str_contains(renderBlogDetail('dated-draft'), 'Article not found'), 'An unpublished post should render a not-found state.');
|
|
||||||
assertBlog(str_contains(renderBlogDetail('second-post'), 'Article not found'), 'A draft post should render a not-found state.');
|
|
||||||
|
|
||||||
assertBlog($datedPost['published_at'] === str_replace('T', ' ', $pastPublication) . ':00', 'A valid local publication date should be normalized for storage.');
|
|
||||||
assertBlog($datedPost['body'] === " Draft body\n", 'Post body whitespace should be preserved.');
|
|
||||||
|
|
||||||
expectBlogValidation(fn() => $posts->create([
|
|
||||||
'title' => 'Invalid date', 'slug' => 'invalid-date', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => 'not-a-date',
|
|
||||||
]), 'Invalid publication dates should be rejected.');
|
|
||||||
expectBlogValidation(fn() => $posts->create([
|
|
||||||
'title' => 'Future date', 'slug' => 'future-date', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => (new \DateTimeImmutable('now', new \DateTimeZone($siteTimezone)))->modify('+1 day')->format('Y-m-d\\TH:i'),
|
|
||||||
]), 'Future publication dates should be rejected.');
|
|
||||||
|
|
||||||
$updated = $posts->update(['id' => $post['id']], [
|
|
||||||
'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'], 'general' => ['uploads_url' => '/uploads', 'timezone' => $siteTimezone]];
|
|
||||||
$_GET = [];
|
|
||||||
assertBlog(str_contains(renderBlogAdminList(), 'No posts yet'), 'The admin list should show its empty-list state when no posts exist.');
|
|
||||||
|
|
||||||
for ($index = 1; $index <= 12; $index++) {
|
|
||||||
$number = str_pad((string) $index, 2, '0', STR_PAD_LEFT);
|
|
||||||
$batchPost = $posts->create([
|
|
||||||
'title' => 'Pagination batch ' . $number,
|
|
||||||
'slug' => 'pagination-batch-' . $number,
|
|
||||||
'excerpt' => 'Batch excerpt',
|
|
||||||
'body' => 'Batch body',
|
|
||||||
'category_id' => '',
|
|
||||||
'status' => $index === 12 ? 'draft' : 'published',
|
|
||||||
'published_at' => '2025-01-' . $number . 'T00:00',
|
|
||||||
]);
|
|
||||||
$phpb_db->query('UPDATE test_ext__blog_posts SET updated_at = ? WHERE id = ?', ['2025-02-' . $number . ' 00:00:00', $batchPost['id']]);
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach ([
|
|
||||||
'title' => 'TitleSearchMarker',
|
|
||||||
'slug' => 'slugsearchmarker',
|
|
||||||
'excerpt' => 'ExcerptSearchMarker',
|
|
||||||
'body' => 'BodySearchMarker',
|
|
||||||
] as $field => $term) {
|
|
||||||
$fieldPost = [
|
|
||||||
'title' => 'Field-only test post',
|
|
||||||
'slug' => 'field-only-test-post',
|
|
||||||
'excerpt' => 'Field-only excerpt',
|
|
||||||
'body' => 'Field-only body',
|
|
||||||
'category_id' => '',
|
|
||||||
'status' => 'published',
|
|
||||||
'published_at' => '2025-03-01T00:00',
|
|
||||||
];
|
|
||||||
$fieldPost[$field] = $term;
|
|
||||||
$fieldPost['slug'] = $field === 'slug' ? $term : 'field-only-' . $field;
|
|
||||||
$fieldPost = $posts->create($fieldPost);
|
|
||||||
$adminMatch = $posts->getPageForAdmin($term, 1);
|
|
||||||
$publicMatch = $posts->getPageForListing($term, 1);
|
|
||||||
assertBlog($adminMatch['total'] === 1 && $adminMatch['posts'][0]['slug'] === $fieldPost['slug'], 'Admin search should match the ' . $field . ' field.');
|
|
||||||
assertBlog($field === 'body' ? $publicMatch['total'] === 0 : $publicMatch['total'] === 1 && $publicMatch['posts'][0]['slug'] === $fieldPost['slug'], 'Public search should match only title, slug, and excerpt fields.');
|
|
||||||
}
|
|
||||||
$shortPublicSearch = $posts->getPageForListing('po', 1);
|
|
||||||
assertBlog($shortPublicSearch['total'] === 0 && $shortPublicSearch['posts'] === [], 'Public search should ignore queries shorter than three characters.');
|
|
||||||
$_GET = ['q' => 'po'];
|
|
||||||
assertBlog(str_contains(renderBlogListing(), 'Enter at least 3 characters to search.'), 'The public listing should explain the minimum search length.');
|
|
||||||
$_GET = [];
|
|
||||||
|
|
||||||
foreach ([
|
|
||||||
['term' => '100%', 'match' => 'literal-percent', 'title' => 'Price 100% complete', 'decoy' => 'wildcard-percent-decoy', 'decoyTitle' => 'Price 100X complete'],
|
|
||||||
['term' => 'under_score', 'match' => 'literal-underscore', 'title' => 'under_score example', 'decoy' => 'wildcard-underscore-decoy', 'decoyTitle' => 'underXscore example'],
|
|
||||||
['term' => 'bang!mark', 'match' => 'literal-escape-character', 'title' => 'bang!mark example', 'decoy' => 'escape-character-decoy', 'decoyTitle' => 'bangXmark example'],
|
|
||||||
] as $literalSearch) {
|
|
||||||
foreach ([[$literalSearch['match'], $literalSearch['title']], [$literalSearch['decoy'], $literalSearch['decoyTitle']]] as [$slug, $title]) {
|
|
||||||
$posts->create([
|
|
||||||
'title' => $title,
|
|
||||||
'slug' => $slug,
|
|
||||||
'excerpt' => '',
|
|
||||||
'body' => 'Search wildcard regression test',
|
|
||||||
'category_id' => '',
|
|
||||||
'status' => 'published',
|
|
||||||
'published_at' => '2025-03-01T00:00',
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
$adminMatch = $posts->getPageForAdmin($literalSearch['term'], 1);
|
|
||||||
$publicMatch = $posts->getPageForListing($literalSearch['term'], 1);
|
|
||||||
assertBlog($adminMatch['total'] === 1 && $adminMatch['posts'][0]['slug'] === $literalSearch['match'], 'Admin search should treat LIKE metacharacters literally.');
|
|
||||||
assertBlog($publicMatch['total'] === 1 && $publicMatch['posts'][0]['slug'] === $literalSearch['match'], 'Public search should treat LIKE metacharacters literally.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$adminFirstPage = $posts->getPageForAdmin('pagination', 1);
|
|
||||||
$adminLastPage = $posts->getPageForAdmin('pagination', 2);
|
|
||||||
assertBlog($adminFirstPage['total'] === 12 && count($adminFirstPage['posts']) === 10, 'Admin pagination should report all matching posts and cap each page at ten.');
|
|
||||||
assertBlog($adminFirstPage['posts'][0]['slug'] === 'pagination-batch-12' && $adminFirstPage['posts'][9]['slug'] === 'pagination-batch-03', 'Admin pages should preserve the newest-updated-first order.');
|
|
||||||
assertBlog(count($adminLastPage['posts']) === 2 && $adminLastPage['posts'][0]['slug'] === 'pagination-batch-02', 'The admin final page should contain the remaining posts in order.');
|
|
||||||
assertBlog($posts->getPageForAdmin('pagination', 0)['posts'][0]['slug'] === 'pagination-batch-12', 'Invalid low page numbers should normalize to the first page.');
|
|
||||||
assertBlog($posts->getPageForAdmin('pagination', PHP_INT_MAX)['posts'][0]['slug'] === 'pagination-batch-02', 'Oversized page numbers should safely resolve to the last matching page.');
|
|
||||||
|
|
||||||
$publicFirstPage = $posts->getPageForListing('pagination', 1);
|
|
||||||
$publicLastPage = $posts->getPageForListing('pagination', 2);
|
|
||||||
assertBlog($publicFirstPage['total'] === 11 && count($publicFirstPage['posts']) === 10, 'Public pagination should exclude the matching draft and report published totals.');
|
|
||||||
assertBlog($publicFirstPage['posts'][0]['slug'] === 'pagination-batch-11', 'Public pages should preserve newest-published-first order.');
|
|
||||||
assertBlog(count($publicLastPage['posts']) === 1 && $publicLastPage['posts'][0]['slug'] === 'pagination-batch-01', 'The public final page should contain its remaining published post.');
|
|
||||||
$noMatches = $posts->getPageForAdmin("pagination' OR '1'='1", 1);
|
|
||||||
assertBlog($noMatches['total'] === 0 && $noMatches['posts'] === [], 'Search input should be treated as a value rather than SQL.');
|
|
||||||
|
|
||||||
$_SERVER['HTTPS'] = 'on';
|
|
||||||
$_SERVER['SERVER_NAME'] = 'blog.example';
|
|
||||||
$_SERVER['SERVER_PORT'] = 443;
|
|
||||||
$_ENV['BASE_URL'] = 'https://blog.example/app';
|
|
||||||
$_SERVER['REQUEST_URI'] = '/app/news?keep=old';
|
|
||||||
$_GET = ['q' => 'pagination', 'page' => '2'];
|
|
||||||
$publicSearchPage = renderBlogListing();
|
|
||||||
assertBlog(str_contains($publicSearchPage, 'Pagination batch 01') && !str_contains($publicSearchPage, 'Pagination batch 11'), 'The public block should render only the requested search page.');
|
|
||||||
assertBlog(str_contains($publicSearchPage, 'action="https://blog.example/app/news"') && str_contains($publicSearchPage, 'name="q" value="pagination"'), 'The public search form should submit to the current path and retain its search value.');
|
|
||||||
assertBlog(str_contains($publicSearchPage, 'href="https://blog.example/app/news?q=pagination&page=1"') && str_contains($publicSearchPage, 'Page 2 of 2'), 'Public pagination should retain the search term and current page position.');
|
|
||||||
$_GET = ['q' => 'pagination', 'page' => '0'];
|
|
||||||
assertBlog(str_contains(renderBlogListing(), 'Pagination batch 11'), 'Invalid public page values should safely show the first page.');
|
|
||||||
$_GET = ['q' => 'no-such-post'];
|
|
||||||
$publicNoMatches = renderBlogListing();
|
|
||||||
assertBlog(str_contains($publicNoMatches, 'No published posts match "no-such-post"') && !str_contains($publicNoMatches, 'No published posts yet.'), 'The public block should distinguish no matches from an empty blog.');
|
|
||||||
|
|
||||||
$_GET = ['q' => 'pagination', 'page' => '99', 'posts_page' => '2'];
|
|
||||||
$adminSearchPage = renderBlogAdminList();
|
|
||||||
assertBlog(str_contains($adminSearchPage, 'Pagination batch 02') && str_contains($adminSearchPage, 'Pagination batch 01') && !str_contains($adminSearchPage, 'Pagination batch 12'), 'The admin list should render only the requested page.');
|
|
||||||
assertBlog(str_contains($adminSearchPage, 'name="tab" value="ext--blog"') && str_contains($adminSearchPage, 'name="q" value="pagination"'), 'The admin search form should retain the extension route and search term.');
|
|
||||||
assertBlog(str_contains($adminSearchPage, 'href="https://blog.example/app/website-manager?tab=ext--blog&action=posts&q=pagination&posts_page=1"') && str_contains($adminSearchPage, 'Page 2 of 2'), 'Admin pagination should preserve the extension route, search term, and posts_page parameter.');
|
|
||||||
$_GET = ['q' => 'pagination', 'page' => '2', 'posts_page' => '1'];
|
|
||||||
$adminFirstPageHtml = renderBlogAdminList();
|
|
||||||
assertBlog(str_contains($adminFirstPageHtml, 'Pagination batch 12') && str_contains($adminFirstPageHtml, '>Draft</span>'), 'The admin list should include matching drafts.');
|
|
||||||
$_GET = ['q' => 'pagination', 'page' => '2', 'posts_page' => '0'];
|
|
||||||
assertBlog(str_contains(renderBlogAdminList(), 'Pagination batch 12'), 'Invalid admin page values should safely show the first page.');
|
|
||||||
$_GET = ['q' => 'no-such-post'];
|
|
||||||
$adminNoMatches = renderBlogAdminList();
|
|
||||||
assertBlog(str_contains($adminNoMatches, 'No posts found for "no-such-post"') && !str_contains($adminNoMatches, 'No posts yet'), 'The admin list should distinguish no matches from an empty post list.');
|
|
||||||
|
|
||||||
fwrite(STDOUT, "Blog repository tests passed.\n");
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
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,10 +17,6 @@ if(isset($_GET['id']))
|
|||||||
$form = $formsRepository->findWithId($_GET['id']);
|
$form = $formsRepository->findWithId($_GET['id']);
|
||||||
|
|
||||||
$isEditing = isset($form['id']) && $form['id'] > 0;
|
$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">
|
<header class="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||||
@@ -38,8 +34,8 @@ $finishersJson = $finishersJson === false ? '[]' : $finishersJson;
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
const fields = <?= $fieldsJson ?>;
|
const fields = <?= $form["fields"] ?>;
|
||||||
const finishers = <?= $finishersJson ?>;
|
const finishers = <?= $form["finishers"] ?>;
|
||||||
const finisherDefinitions = <?= json_encode($finisherDefinitions, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;
|
const finisherDefinitions = <?= json_encode($finisherDefinitions, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -106,7 +102,6 @@ $finishersJson = $finishersJson === false ? '[]' : $finishersJson;
|
|||||||
this.fields.splice(toIndex, 0, field);
|
this.fields.splice(toIndex, 0, field);
|
||||||
}
|
}
|
||||||
}">
|
}">
|
||||||
<?php phpb_csrf_field(); ?>
|
|
||||||
<?php
|
<?php
|
||||||
if(isset($form['id'])) echo '<input type="hidden" name="id" value="'.$form['id'].'">';
|
if(isset($form['id'])) echo '<input type="hidden" name="id" value="'.$form['id'].'">';
|
||||||
?>
|
?>
|
||||||
|
|||||||
@@ -75,14 +75,9 @@ $entries = $entriesRepository->findWhere('formId', $id);
|
|||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
<td>
|
<td>
|
||||||
<div class="flex justify-end">
|
<div class="flex justify-end">
|
||||||
<form action="/ext--form/delete-entry" method="post">
|
<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']) ?>">
|
||||||
<?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>
|
<i class="ph-duotone ph-trash text-lg" aria-hidden="true"></i>
|
||||||
</button>
|
</a>
|
||||||
</form>
|
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
@@ -58,13 +58,9 @@ $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']) ?>">
|
<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>
|
<i class="ph-duotone ph-pencil-line text-lg" aria-hidden="true"></i>
|
||||||
</a>
|
</a>
|
||||||
<form action="/ext--form/delete-form" method="post">
|
<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']) ?>">
|
||||||
<?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>
|
<i class="ph-duotone ph-trash text-lg" aria-hidden="true"></i>
|
||||||
</button>
|
</a>
|
||||||
</form>
|
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
@@ -1,20 +1,11 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
phpb_requires_authenticated();
|
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();
|
$entriesRepository = new \Plugi\Extensions\Form\EntriesRepository();
|
||||||
|
|
||||||
if(
|
if(
|
||||||
isset($_POST['id'])
|
isset($_GET['id'])
|
||||||
) {
|
) {
|
||||||
$entriesRepository->destroy($_POST['id']);
|
$entriesRepository->destroy($_GET['id']);
|
||||||
}
|
}
|
||||||
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'listEntries', 'id' => $_POST['formId'] ?? '']));
|
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'listEntries', 'id' => $_GET['formId']]));
|
||||||
|
|||||||
@@ -1,22 +1,13 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
phpb_requires_authenticated();
|
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();
|
$formsRepository = new \Plugi\Extensions\Form\DefinitionsRepository();
|
||||||
$entriesRepository = new \Plugi\Extensions\Form\EntriesRepository();
|
$entriesRepository = new \Plugi\Extensions\Form\EntriesRepository();
|
||||||
|
|
||||||
if(
|
if(
|
||||||
isset($_POST['id'])
|
isset($_GET['id'])
|
||||||
) {
|
) {
|
||||||
$formsRepository->destroy($_POST['id']);
|
$formsRepository->destroy($_GET['id']);
|
||||||
$entriesRepository->destroyWhere('formId', $_POST['id']);
|
$entriesRepository->destroyWhere('formId', $_GET['id']);
|
||||||
}
|
}
|
||||||
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'listForms']));
|
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'listForms']));
|
||||||
|
|||||||
@@ -1,15 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
phpb_requires_authenticated();
|
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();
|
$formsRepository = new \Plugi\Extensions\Form\DefinitionsRepository();
|
||||||
|
|
||||||
if(
|
if(
|
||||||
|
|||||||
@@ -1,209 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Plugi\Extensions\Form {
|
|
||||||
class DefinitionsRepository
|
|
||||||
{
|
|
||||||
public static array $form = [];
|
|
||||||
public static array $created = [];
|
|
||||||
public static array $destroyed = [];
|
|
||||||
|
|
||||||
public function findWithId($id)
|
|
||||||
{
|
|
||||||
return self::$form;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function create(array $data): null|object|array
|
|
||||||
{
|
|
||||||
self::$created[] = $data;
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function update($instance, array $data): void
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
public function destroy($id): void
|
|
||||||
{
|
|
||||||
self::$destroyed[] = $id;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class EntriesRepository
|
|
||||||
{
|
|
||||||
public static array $destroyed = [];
|
|
||||||
public static array $deleted = [];
|
|
||||||
|
|
||||||
public function destroy($id): void
|
|
||||||
{
|
|
||||||
self::$deleted[] = $id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function destroyWhere($column, $value): void
|
|
||||||
{
|
|
||||||
self::$destroyed[] = [$column, $value];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace Plugi\Extensions\Form\Finishers {
|
|
||||||
class FinishersRepository
|
|
||||||
{
|
|
||||||
public function getEditorConfig(): array
|
|
||||||
{
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace {
|
|
||||||
use Plugi\Extensions\Form\DefinitionsRepository;
|
|
||||||
use Plugi\Extensions\Form\EntriesRepository;
|
|
||||||
|
|
||||||
class FormAdminSecurityRedirect extends RuntimeException
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertFormAdminSecurity(bool $condition, string $message): void
|
|
||||||
{
|
|
||||||
if (!$condition) {
|
|
||||||
throw new RuntimeException($message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function phpb_requires_authenticated(): void
|
|
||||||
{
|
|
||||||
if (!($GLOBALS['formAdminSecurityAuthenticated'] ?? false)) {
|
|
||||||
throw new RuntimeException('The form admin route did not require authentication.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function phpb_validate_csrf(): bool
|
|
||||||
{
|
|
||||||
return $GLOBALS['formAdminSecurityCsrfValid'] ?? false;
|
|
||||||
}
|
|
||||||
|
|
||||||
function phpb_csrf_field(): void
|
|
||||||
{
|
|
||||||
echo '<input type="hidden" name="_csrf_token" value="test-token">';
|
|
||||||
}
|
|
||||||
|
|
||||||
function phpb_e(string $value): string
|
|
||||||
{
|
|
||||||
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
|
|
||||||
}
|
|
||||||
|
|
||||||
function phpb_url(string $module, array $parameters = []): string
|
|
||||||
{
|
|
||||||
return $module . '?' . http_build_query($parameters);
|
|
||||||
}
|
|
||||||
|
|
||||||
function phpb_redirect(string $url, array $flashData = [], int $statusCode = 302): void
|
|
||||||
{
|
|
||||||
throw new FormAdminSecurityRedirect();
|
|
||||||
}
|
|
||||||
|
|
||||||
function includeFormSecurityRoute(string $route): void
|
|
||||||
{
|
|
||||||
try {
|
|
||||||
require $route;
|
|
||||||
} catch (FormAdminSecurityRedirect) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$projectRoot = dirname(__DIR__, 3);
|
|
||||||
$apacheRules = file_get_contents($projectRoot . '/.htaccess');
|
|
||||||
assertFormAdminSecurity(
|
|
||||||
is_string($apacheRules) && str_contains($apacheRules, 'Require all denied'),
|
|
||||||
'Apache must deny requests for hidden files such as the root .env file.'
|
|
||||||
);
|
|
||||||
|
|
||||||
$attack = '</script><script>window.pwned=1</script>';
|
|
||||||
DefinitionsRepository::$form = [
|
|
||||||
'id' => 7,
|
|
||||||
'name' => 'Test form',
|
|
||||||
'fields' => json_encode([['name' => $attack]]),
|
|
||||||
'finishers' => '[]',
|
|
||||||
];
|
|
||||||
$_GET = ['id' => '7'];
|
|
||||||
ob_start();
|
|
||||||
require dirname(__DIR__) . '/admin/Views/EditForm.php';
|
|
||||||
$editor = ob_get_clean();
|
|
||||||
assertFormAdminSecurity(
|
|
||||||
!str_contains($editor, $attack) && str_contains($editor, '\\u003C'),
|
|
||||||
'Stored form JSON must be escaped before it is emitted inside a script element.'
|
|
||||||
);
|
|
||||||
assertFormAdminSecurity(
|
|
||||||
str_contains($editor, 'name="_csrf_token"'),
|
|
||||||
'Form saves must submit a CSRF token.'
|
|
||||||
);
|
|
||||||
|
|
||||||
$GLOBALS['formAdminSecurityAuthenticated'] = true;
|
|
||||||
$GLOBALS['formAdminSecurityCsrfValid'] = false;
|
|
||||||
$saveRoute = dirname(__DIR__) . '/routes/saveForm.php';
|
|
||||||
$_SERVER['REQUEST_METHOD'] = 'GET';
|
|
||||||
$_POST = [];
|
|
||||||
http_response_code(200);
|
|
||||||
includeFormSecurityRoute($saveRoute);
|
|
||||||
assertFormAdminSecurity(http_response_code() === 405, 'Form saves must reject non-POST requests.');
|
|
||||||
assertFormAdminSecurity(DefinitionsRepository::$created === [], 'A GET request must not save a form.');
|
|
||||||
|
|
||||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
|
||||||
$_POST = ['name' => 'Rejected form', 'fields' => '[]', 'finishers' => '[]'];
|
|
||||||
http_response_code(200);
|
|
||||||
includeFormSecurityRoute($saveRoute);
|
|
||||||
assertFormAdminSecurity(http_response_code() === 403, 'Form saves must reject invalid CSRF tokens.');
|
|
||||||
assertFormAdminSecurity(DefinitionsRepository::$created === [], 'An invalid CSRF token must not save a form.');
|
|
||||||
|
|
||||||
$GLOBALS['formAdminSecurityCsrfValid'] = true;
|
|
||||||
$_POST['_csrf_token'] = 'test-token';
|
|
||||||
includeFormSecurityRoute($saveRoute);
|
|
||||||
assertFormAdminSecurity(count(DefinitionsRepository::$created) === 1, 'A valid POST should save a form.');
|
|
||||||
|
|
||||||
$deleteRoute = dirname(__DIR__) . '/routes/deleteForm.php';
|
|
||||||
$_SERVER['REQUEST_METHOD'] = 'GET';
|
|
||||||
$_GET = ['id' => '7'];
|
|
||||||
$_POST = [];
|
|
||||||
http_response_code(200);
|
|
||||||
includeFormSecurityRoute($deleteRoute);
|
|
||||||
assertFormAdminSecurity(http_response_code() === 405, 'Form deletion must reject non-POST requests.');
|
|
||||||
assertFormAdminSecurity(DefinitionsRepository::$destroyed === [], 'A GET request must not delete a form.');
|
|
||||||
|
|
||||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
|
||||||
$_POST = ['id' => '7'];
|
|
||||||
$GLOBALS['formAdminSecurityCsrfValid'] = false;
|
|
||||||
http_response_code(200);
|
|
||||||
includeFormSecurityRoute($deleteRoute);
|
|
||||||
assertFormAdminSecurity(http_response_code() === 403, 'Form deletion must reject invalid CSRF tokens.');
|
|
||||||
assertFormAdminSecurity(DefinitionsRepository::$destroyed === [], 'An invalid CSRF token must not delete a form.');
|
|
||||||
|
|
||||||
$_POST = ['id' => '7', '_csrf_token' => 'test-token'];
|
|
||||||
$GLOBALS['formAdminSecurityCsrfValid'] = true;
|
|
||||||
includeFormSecurityRoute($deleteRoute);
|
|
||||||
assertFormAdminSecurity(DefinitionsRepository::$destroyed === ['7'], 'A valid POST should delete the form.');
|
|
||||||
assertFormAdminSecurity(EntriesRepository::$destroyed === [['formId', '7']], 'Deleting a form should still delete its entries.');
|
|
||||||
|
|
||||||
$deleteEntryRoute = dirname(__DIR__) . '/routes/deleteEntry.php';
|
|
||||||
$_SERVER['REQUEST_METHOD'] = 'GET';
|
|
||||||
$_GET = ['id' => '12', 'formId' => '7'];
|
|
||||||
$_POST = [];
|
|
||||||
http_response_code(200);
|
|
||||||
includeFormSecurityRoute($deleteEntryRoute);
|
|
||||||
assertFormAdminSecurity(http_response_code() === 405, 'Entry deletion must reject non-POST requests.');
|
|
||||||
assertFormAdminSecurity(EntriesRepository::$deleted === [], 'A GET request must not delete an entry.');
|
|
||||||
|
|
||||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
|
||||||
$_POST = ['id' => '12', 'formId' => '7'];
|
|
||||||
$GLOBALS['formAdminSecurityCsrfValid'] = false;
|
|
||||||
http_response_code(200);
|
|
||||||
includeFormSecurityRoute($deleteEntryRoute);
|
|
||||||
assertFormAdminSecurity(http_response_code() === 403, 'Entry deletion must reject invalid CSRF tokens.');
|
|
||||||
assertFormAdminSecurity(EntriesRepository::$deleted === [], 'An invalid CSRF token must not delete an entry.');
|
|
||||||
|
|
||||||
$_POST['_csrf_token'] = 'test-token';
|
|
||||||
$GLOBALS['formAdminSecurityCsrfValid'] = true;
|
|
||||||
includeFormSecurityRoute($deleteEntryRoute);
|
|
||||||
assertFormAdminSecurity(EntriesRepository::$deleted === ['12'], 'A valid POST should delete an entry.');
|
|
||||||
|
|
||||||
fwrite(STDOUT, "PASS: form admin actions require POST and CSRF, and stored JSON is script-safe.\n");
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
<?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>
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
return [
|
|
||||||
'title' => 'Tracking',
|
|
||||||
'author' => 'Paul Spenke',
|
|
||||||
'identifier' => 'tracking',
|
|
||||||
'licence' => 'MIT',
|
|
||||||
'version' => '1.0.0',
|
|
||||||
];
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
<?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');
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
<?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.',
|
|
||||||
]);
|
|
||||||
@@ -1,185 +0,0 @@
|
|||||||
<?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");
|
|
||||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+2
-2
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+1
-1
File diff suppressed because one or more lines are too long
+1
-1
@@ -1 +1 @@
|
|||||||
{"version":3,"sourceRoot":"","sources":["file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/pagebuilder.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/fields.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/style-manager.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/asset-manager.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/mobile-mode.scss"],"names":[],"mappings":"AAKA,eAGI,uBACA,SACA,gBAGJ,EACI,mCACA,gCACA,2BAGJ,kCAEI,cAGJ,gBACI,eAGJ,YACI,gBAGJ,OACI,qBACA,YACA,WACA,gBAEA,qBACI,mBAIR,cACI,kBACA,YACA,WACA,sBACA,cACA,WACI,2BAGJ,qBACI,kBACA,UAGJ,sBACI,kBACA,QACA,SACA,gCACA,YACA,aAEA,4BACI,eACA,eACA,gBACA,kBACA,cAGR,sBACI,uBACA,wBACA,yBACA,6BACA,kBACA,oCAEJ,kBACI,KACI,0BAKZ,sBAEI,gBAGJ,eACI,YACA,MACA,yBAEJ,aACI,uBAGJ,cACI,UAEA,8BACI,uBAGR,mDAGI,aAEJ,eACI,UAEJ,YACI,yBACA,mBACA,cAEJ,eACI,cAEJ,gBACI,cAEJ,wBACI,cAEJ,iBACI,WACA,wBACA,qBACA,gBAEJ,oBACI,UACA,WAEJ,0BACI,8BAEJ,0BACI,oCACA,kBAEA,gCACI,oCAMR,cACI,SAEA,0BACI,aACA,eACA,4BACA,wBACA,qBACA,gBACA,mBACA,cACA,gCACA,eAEA,wCACI,aACA,yBACA,gCACA,iCACA,wBACA,qBACA,gBACA,WACA,gCAIZ,gBACI,QAEJ,sCAEI,OACA,wBACA,qBACA,gBACA,MAjMY,MAkMZ,iBACA,gBACA,cACA,eACA,eACA,gBAEJ,wBACI,iBACA,mBACA,0BACA,gBAEA,0CACI,gBAGJ,4BACI,YACA,gBAGJ,gCACI,mBACA,YAGR,iCAEI,KA/NY,MAkOZ,4BACI,2BAEJ,6BACI,4BAEJ,8BACI,4BAMR,cACI,yBAGA,6DAEI,WAGR,WACI,yBACA,gBACA,YAEA,uDAGI,YAGJ,0BACI,6BAMR,gBACI,kBACA,gBACA,MA7QY,MA8QZ,YACA,mBACA,YAEA,sEAEI,iBAEA,oFACI,mBACA,cACA,yBACA,kBACA,gBACA,eACA,aACA,eAEA,gGACI,qBAKhB,gBACI,kBACA,OACA,MACA,YACA,cACA,mBACA,gBACA,YACA,eACA,YACA,WACA,aACA,mBACA,uBAKJ,cACI,eACA,mBACA,qBACA,gBACA,YACA,iBAEA,0BACI,kBACA,SACA,SACA,eACA,cAGJ,oBACI,mBACA,4BACA,gBACA,YAEA,iCACI,cAKZ,WACI,YACA,gBACA,mBACA,WACA,uBAEA,cACI,YAGJ,iBACI,yBAGJ,wBACI,YACA,gBACA,kBACA,WAEA,4BACI,WAIZ,cACI,mBACA,YAEJ,sBACI,mBACA,oBAEJ,iBACI,gBACA,YACA,aAEA,mBACI,iBACA,gBAGR,oBACI,mBAEJ,6BACI,8BACA,mBAEJ,eACI,8BAKJ,4BACI,8BAEJ,yCACI,oCAEJ,wCACI,wDAEJ,6HAKI,8BACA,2CACA,iBACA,eACA,mBAEJ,sHAGI,8BAEJ,gBACI,gBACA,oBAEJ,iBACI,aAEJ,eACI,iBAKJ,2BACI,uCAKJ,eACI,cAEJ,gBACI,mBAEJ,oDAEI,WAEJ,oBACI,uBACA,sBAEJ,kBACI,mBACA,eACA,mBAEJ,yDAEI,kBAEJ,+BACI,WAEJ,8BACI,iBACA,oBAEJ,kCACI,gBAEJ,iCACI,mBAEJ,eACI,oBAEJ,gCACI,gBACA,UAEA,0DACI,kBAEA,gFACI,kBACA,QACA,MACA,gBACA,yBACA,qBACA,cACA,gBAGJ,8DACI,eACA,iBAOZ,wBACI,kBACA,OACA,SACA,MAhgBY,MAigBZ,SACA,YACA,mBACA,gBACA,sBAEA,uCACI,mBACA,sBAEA,iDACI,aAIR,uCACI,mBAEJ,yCACI,mBCphBR,WACE,yBAGA,yBACE,sBACA,WAGJ,gBACE,cAEF,kBACE,cAEF,oCACE,cAEA,2CACE,yBACA,WAGJ,mBACE,6BAEF,mBACE,gCAGF,iBACE,qBAEF,sCACE,iBACA,gBACA,oBACA,WAEF,oDACE,yBCxCF,+BACE,mBACA,cAGF,cACE,WACA,cACA,iBAEA,gEAEE,aAEF,2BACE,cAEF,+BACE,yBACA,YACA,gDACA,WAEA,qCACE,yBAMJ,gEAEE,cAGF,+CACE,uCACA,uCAGF,+BACE,yBAEA,2CACE,gBACA,WACA,iBAGF,0CACE,UACA,yBAEA,iDACE,WACA,mBAKN,0CACE,WAEA,gDACE,WChEN,sBACE,aAEF,oBACE,gBACA,cAEF,eACE,aAEF,cACE,2BACA,yBACA,sBACA,qBACA,iBAGF,cACE,qBACA,gBACA,uBACA,gBACA,kBACA,sBACA,yBACA,sBACA,qBACA,iBACA,eACA,gBACA,qBACA,8HACA,WACA,yBACA,yBAIA,yBACE,WACA,WAEF,oCACE,WAKF,2BACE,uCACA,0BAEF,oCACE,cACA,iBHqeJ,qBACI,cACA,eAEA,gCACI,yBACA,yBACA,WACA,iBACA,kBACA,aACA,eAEA,sCACI,qBAIR,sCACI,gBACA,wRACA,4BACA,sCACA,qBACA,mBAGJ,0BACI,iBACA,kBACA,eACA,eACA,YACA,6CI5jBN,kCACE,uBAGF,kCACE,aAEF,uEACE,OAGF,mCACE,kBACA,eACA,qDACA,kDACA,2CACA"}
|
{"version":3,"sourceRoot":"","sources":["file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/pagebuilder.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/fields.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/style-manager.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/asset-manager.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/mobile-mode.scss"],"names":[],"mappings":"AAKA,eAGI,uBACA,SACA,gBAGJ,EACI,mCACA,gCACA,2BAGJ,kCAEI,cAGJ,gBACI,eAGJ,YACI,gBAGJ,OACI,qBACA,YACA,WACA,gBAEA,qBACI,mBAIR,cACI,kBACA,YACA,WACA,sBACA,cACA,WACI,2BAGJ,qBACI,kBACA,UAGJ,sBACI,kBACA,QACA,SACA,gCACA,YACA,aAEA,4BACI,eACA,eACA,gBACA,kBACA,cAGR,sBACI,uBACA,wBACA,yBACA,6BACA,kBACA,oCAEJ,kBACI,KACI,0BAKZ,sBAEI,gBAGJ,eACI,YACA,MACA,yBAEJ,aACI,uBAGJ,cACI,UAEA,8BACI,uBAGR,mDAGI,aAEJ,eACI,UAEJ,YACI,yBACA,mBACA,cAEJ,eACI,cAEJ,gBACI,cAEJ,wBACI,cAEJ,iBACI,WACA,wBACA,qBACA,gBAEJ,oBACI,UACA,WAEJ,0BACI,8BAEJ,0BACI,oCACA,kBAEA,gCACI,oCAMR,cACI,SAEA,0BACI,aACA,eACA,4BACA,wBACA,qBACA,gBACA,mBACA,cACA,gCACA,eAEA,wCACI,aACA,yBACA,gCACA,iCACA,wBACA,qBACA,gBACA,WACA,gCAIZ,gBACI,QAEJ,sCAEI,OACA,wBACA,qBACA,gBACA,MAjMY,MAkMZ,iBACA,gBACA,cACA,eACA,eACA,gBAEJ,wBACI,iBACA,mBACA,0BACA,gBAEA,0CACI,gBAGJ,4BACI,YACA,gBAGJ,gCACI,mBACA,YAGR,iCAEI,KA/NY,MAkOZ,4BACI,2BAEJ,6BACI,4BAEJ,8BACI,4BAMR,cACI,yBAGA,6DAEI,WAGR,WACI,yBACA,gBACA,YAEA,uDAGI,YAGJ,0BACI,6BAMR,gBACI,kBACA,gBACA,MA7QY,MA8QZ,eACA,mBACA,YACA,YACA,aACA,mBAEA,sEAEI,iBAEA,oFACI,mBACA,cACA,yBACA,kBACA,gBACA,eACA,aACA,eAEA,gGACI,qBAKhB,gBACI,kBACA,OACA,MACA,YACA,cACA,mBACA,gBACA,YACA,eACA,YACA,WACA,aACA,mBACA,uBAKJ,cACI,eACA,mBACA,qBACA,gBACA,YACA,iBAEA,0BACI,kBACA,SACA,SACA,eACA,cAGJ,oBACI,mBACA,4BACA,gBACA,YAEA,iCACI,cAKZ,WACI,YACA,gBACA,mBACA,WACA,uBAEA,cACI,YAGJ,iBACI,yBAGJ,wBACI,YACA,gBACA,kBACA,WAEA,4BACI,WAIZ,cACI,mBACA,YAEJ,sBACI,mBACA,oBAEJ,iBACI,gBACA,YACA,aAEA,mBACI,iBACA,gBAGR,oBACI,mBAEJ,6BACI,8BACA,mBAEJ,eACI,8BAKJ,4BACI,8BAEJ,yCACI,oCAEJ,wCACI,wDAEJ,6HAKI,8BACA,2CACA,iBACA,eACA,mBAEJ,sHAGI,8BAEJ,gBACI,gBACA,oBAEJ,iBACI,aAEJ,eACI,iBAKJ,2BACI,uCAKJ,eACI,cAEJ,gBACI,mBAEJ,oDAEI,WAEJ,oBACI,uBACA,sBAEJ,kBACI,mBACA,eACA,mBAEJ,yDAEI,kBAEJ,+BACI,WAEJ,8BACI,iBACA,oBAEJ,kCACI,gBAEJ,iCACI,mBAEJ,eACI,oBAEJ,gCACI,gBACA,UAEA,0DACI,kBAEA,gFACI,kBACA,QACA,MACA,gBACA,yBACA,qBACA,cACA,gBAGJ,8DACI,eACA,iBAOZ,wBACI,kBACA,OACA,SACA,MAngBY,MAogBZ,SACA,YACA,mBACA,gBACA,sBAEA,uCACI,mBACA,sBAEA,iDACI,aAIR,uCACI,mBAEJ,yCACI,mBCvhBR,WACE,yBAGA,yBACE,sBACA,WAGJ,gBACE,cAEF,kBACE,cAEF,oCACE,cAEA,2CACE,yBACA,WAGJ,mBACE,6BAEF,mBACE,gCAGF,iBACE,qBAEF,sCACE,iBACA,gBACA,oBACA,WAEF,oDACE,yBCxCF,+BACE,mBACA,cAGF,cACE,WACA,cACA,iBAEA,gEAEE,aAEF,2BACE,cAEF,+BACE,yBACA,YACA,gDACA,WAEA,qCACE,yBAMJ,gEAEE,cAGF,+CACE,uCACA,uCAGF,+BACE,yBAEA,2CACE,gBACA,WACA,iBAGF,0CACE,UACA,yBAEA,iDACE,WACA,mBAKN,0CACE,WAEA,gDACE,WChEN,sBACE,aAEF,oBACE,gBACA,cAEF,eACE,aAEF,cACE,2BACA,yBACA,sBACA,qBACA,iBAGF,cACE,qBACA,gBACA,uBACA,gBACA,kBACA,sBACA,yBACA,sBACA,qBACA,iBACA,eACA,gBACA,qBACA,8HACA,WACA,yBACA,yBAIA,yBACE,WACA,WAEF,oCACE,WAKF,2BACE,uCACA,0BAEF,oCACE,cACA,iBHweJ,qBACI,cACA,eAEA,gCACI,yBACA,yBACA,WACA,iBACA,kBACA,aACA,eAEA,sCACI,qBAIR,sCACI,gBACA,wRACA,4BACA,sCACA,qBACA,mBAGJ,0BACI,iBACA,kBACA,eACA,eACA,YACA,6CI/jBN,kCACE,uBAGF,kCACE,aAEF,uEACE,OAGF,mCACE,kBACA,eACA,qDACA,kDACA,2CACA"}
|
||||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
@@ -67,9 +67,7 @@ return [
|
|||||||
'required' => 'Pflichtfeld',
|
'required' => 'Pflichtfeld',
|
||||||
'website-languages' => 'Website Sprachen',
|
'website-languages' => 'Website Sprachen',
|
||||||
'languages-selector-placeholder' => 'Wähle eine oder mehr Sprachen aus',
|
'languages-selector-placeholder' => 'Wähle eine oder mehr Sprachen aus',
|
||||||
'default-language' => 'Standardsprache der Website',
|
'admin-language' => 'Admin Sprache',
|
||||||
'default-language-requires-enabled' => 'Die Standardsprache muss oben ebenfalls aktiviert sein.',
|
|
||||||
'invalid-default-language' => 'Die Standardsprache muss in der Liste der Website-Sprachen aktiviert sein.',
|
|
||||||
'selected-theme' => 'Ausgewähltes Template',
|
'selected-theme' => 'Ausgewähltes Template',
|
||||||
'save-settings' => 'Einstellungen speichern',
|
'save-settings' => 'Einstellungen speichern',
|
||||||
'settings-updated' => 'Einstellungen aktualisiert',
|
'settings-updated' => 'Einstellungen aktualisiert',
|
||||||
@@ -85,7 +83,6 @@ return [
|
|||||||
'pagebuilder' => [
|
'pagebuilder' => [
|
||||||
'filter-placeholder' => 'Filter',
|
'filter-placeholder' => 'Filter',
|
||||||
'loading-text' => 'Seiteneditor wird geladen...',
|
'loading-text' => 'Seiteneditor wird geladen...',
|
||||||
'page-selector' => 'Seite auswählen',
|
|
||||||
'style-no-element-selected' => 'Wähle ein Element aus um das Aussehen anzupassen.',
|
'style-no-element-selected' => 'Wähle ein Element aus um das Aussehen anzupassen.',
|
||||||
'trait-no-element-selected' => 'Wähle ein Element aus um die Attribute anzupassen',
|
'trait-no-element-selected' => 'Wähle ein Element aus um die Attribute anzupassen',
|
||||||
'trait-settings' => 'Einstellungen',
|
'trait-settings' => 'Einstellungen',
|
||||||
|
|||||||
@@ -67,9 +67,7 @@ return [
|
|||||||
'required' => 'Required',
|
'required' => 'Required',
|
||||||
'website-languages' => 'Website languages',
|
'website-languages' => 'Website languages',
|
||||||
'languages-selector-placeholder' => 'Select one or more languages',
|
'languages-selector-placeholder' => 'Select one or more languages',
|
||||||
'default-language' => 'Default site language',
|
'admin-language' => 'Admin Language',
|
||||||
'default-language-requires-enabled' => 'The default language must also be enabled above.',
|
|
||||||
'invalid-default-language' => 'The default language must be enabled in the website languages list.',
|
|
||||||
'selected-theme' => 'Selected theme',
|
'selected-theme' => 'Selected theme',
|
||||||
'save-settings' => 'Save settings',
|
'save-settings' => 'Save settings',
|
||||||
'settings-updated' => 'Settings successfully updated',
|
'settings-updated' => 'Settings successfully updated',
|
||||||
@@ -85,7 +83,6 @@ return [
|
|||||||
'pagebuilder' => [
|
'pagebuilder' => [
|
||||||
'filter-placeholder' => 'Filter',
|
'filter-placeholder' => 'Filter',
|
||||||
'loading-text' => 'Loading pagebuilder..',
|
'loading-text' => 'Loading pagebuilder..',
|
||||||
'page-selector' => 'Select page',
|
|
||||||
'style-no-element-selected' => 'Select an element to modify the style.',
|
'style-no-element-selected' => 'Select an element to modify the style.',
|
||||||
'trait-no-element-selected' => 'Select an element to modify any attributes.',
|
'trait-no-element-selected' => 'Select an element to modify any attributes.',
|
||||||
'trait-settings' => 'Settings',
|
'trait-settings' => 'Settings',
|
||||||
|
|||||||
@@ -66,9 +66,7 @@ return [
|
|||||||
'required' => 'Obligatoriskt',
|
'required' => 'Obligatoriskt',
|
||||||
'website-languages' => 'Webbplatsspråk',
|
'website-languages' => 'Webbplatsspråk',
|
||||||
'languages-selector-placeholder' => 'Välj ett eller flera språk',
|
'languages-selector-placeholder' => 'Välj ett eller flera språk',
|
||||||
'default-language' => 'Webbplatsens standardspråk',
|
'admin-language' => 'Administratörsspråk',
|
||||||
'default-language-requires-enabled' => 'Standardspråket måste också vara aktiverat ovan.',
|
|
||||||
'invalid-default-language' => 'Standardspråket måste vara aktiverat i listan över webbplatsspråk.',
|
|
||||||
'selected-theme' => 'Valt tema',
|
'selected-theme' => 'Valt tema',
|
||||||
'save-settings' => 'Spara inställningar',
|
'save-settings' => 'Spara inställningar',
|
||||||
'settings-updated' => 'Inställningarna har uppdaterats',
|
'settings-updated' => 'Inställningarna har uppdaterats',
|
||||||
@@ -84,7 +82,6 @@ return [
|
|||||||
'pagebuilder' => [
|
'pagebuilder' => [
|
||||||
'filter-placeholder' => 'Filtrera',
|
'filter-placeholder' => 'Filtrera',
|
||||||
'loading-text' => 'Laddar sidbyggaren...',
|
'loading-text' => 'Laddar sidbyggaren...',
|
||||||
'page-selector' => 'Välj sida',
|
|
||||||
'style-no-element-selected' => 'Välj ett element för att ändra stilen.',
|
'style-no-element-selected' => 'Välj ett element för att ändra stilen.',
|
||||||
'trait-no-element-selected' => 'Välj ett element för att ändra dess attribut.',
|
'trait-no-element-selected' => 'Välj ett element för att ändra dess attribut.',
|
||||||
'trait-settings' => 'Inställningar',
|
'trait-settings' => 'Inställningar',
|
||||||
|
|||||||
Generated
+11
-13
@@ -1217,6 +1217,12 @@
|
|||||||
"fsevents": "~2.3.2"
|
"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": {
|
"node_modules/codemirror-formatting": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/codemirror-formatting/-/codemirror-formatting-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/codemirror-formatting/-/codemirror-formatting-1.0.0.tgz",
|
||||||
@@ -1332,12 +1338,6 @@
|
|||||||
"underscore": "1.13.8"
|
"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": {
|
"node_modules/has-flag": {
|
||||||
"version": "3.0.0",
|
"version": "3.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
|
||||||
@@ -2735,6 +2735,11 @@
|
|||||||
"readdirp": "~3.6.0"
|
"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": {
|
"codemirror-formatting": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/codemirror-formatting/-/codemirror-formatting-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/codemirror-formatting/-/codemirror-formatting-1.0.0.tgz",
|
||||||
@@ -2821,13 +2826,6 @@
|
|||||||
"html-entities": "~1.4.0",
|
"html-entities": "~1.4.0",
|
||||||
"promise-polyfill": "8.3.0",
|
"promise-polyfill": "8.3.0",
|
||||||
"underscore": "1.13.8"
|
"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": {
|
"has-flag": {
|
||||||
|
|||||||
@@ -281,15 +281,10 @@ if (! function_exists('phpb_current_relative_url')) {
|
|||||||
|
|
||||||
if (! function_exists('phpb_current_language')) {
|
if (! function_exists('phpb_current_language')) {
|
||||||
/**
|
/**
|
||||||
* Give the resolved request language or fall back to the current URL and site default.
|
* Give the current language based on the current URL.
|
||||||
*/
|
*/
|
||||||
function phpb_current_language(): string
|
function phpb_current_language(): string
|
||||||
{
|
{
|
||||||
global $phpb_request_language;
|
|
||||||
if (isset($phpb_request_language) && is_string($phpb_request_language)) {
|
|
||||||
return $phpb_request_language;
|
|
||||||
}
|
|
||||||
|
|
||||||
$urlComponents = explode('/', phpb_current_relative_url());
|
$urlComponents = explode('/', phpb_current_relative_url());
|
||||||
// remove empty values and reset array key numbering
|
// remove empty values and reset array key numbering
|
||||||
$urlComponents = array_values(array_filter($urlComponents));
|
$urlComponents = array_values(array_filter($urlComponents));
|
||||||
|
|||||||
@@ -68,10 +68,10 @@ class Extensions
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Register an HtmlBlock.
|
* Register an HtmlBlock.
|
||||||
* @param string|callable $html
|
* @param string $html
|
||||||
* @param string $location
|
* @param string $location
|
||||||
*/
|
*/
|
||||||
public static function registerHtmlBlock(string|callable $html, string $location = 'head') {
|
public static function registerHtmlBlock(string $html, string $location = 'head') {
|
||||||
self::$htmlBlocks[$location][] = $html;
|
self::$htmlBlocks[$location][] = $html;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -245,11 +245,7 @@ class Extensions
|
|||||||
*/
|
*/
|
||||||
public static function getHtmlBlocks(string $location = 'head'): string
|
public static function getHtmlBlocks(string $location = 'head'): string
|
||||||
{
|
{
|
||||||
$html = '';
|
return implode('', self::$htmlBlocks[$location]);
|
||||||
foreach (self::$htmlBlocks[$location] as $block) {
|
|
||||||
$html .= is_string($block) ? $block : $block();
|
|
||||||
}
|
|
||||||
return $html;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -307,12 +307,6 @@ class PageBuilder implements PageBuilderContract
|
|||||||
phpb_set_in_editmode();
|
phpb_set_in_editmode();
|
||||||
|
|
||||||
$pageRepository = new PageRepository();
|
$pageRepository = new PageRepository();
|
||||||
$editablePages = array_values(array_filter(
|
|
||||||
$pageRepository->getAll(),
|
|
||||||
static function ($availablePage) {
|
|
||||||
return $availablePage->get("type") !== "redirect";
|
|
||||||
},
|
|
||||||
));
|
|
||||||
|
|
||||||
$draftData = $pageRepository->getPageDraftData($page);
|
$draftData = $pageRepository->getPageDraftData($page);
|
||||||
$hasDraft = $draftData !== null;
|
$hasDraft = $draftData !== null;
|
||||||
|
|||||||
@@ -1,18 +0,0 @@
|
|||||||
export function bindLanguageSelector(document, window) {
|
|
||||||
document.addEventListener("change", function(e) {
|
|
||||||
const radio = e.target.closest("#language-selector input[type='radio']");
|
|
||||||
if (!radio) return;
|
|
||||||
let selectedLanguage = radio.value;
|
|
||||||
|
|
||||||
window.switchLanguage(selectedLanguage, function(success) {
|
|
||||||
if (success) {
|
|
||||||
window.activateLanguage(selectedLanguage);
|
|
||||||
} else {
|
|
||||||
const languageSelector = radio.closest("#language-selector");
|
|
||||||
languageSelector.querySelectorAll('input[type="radio"]').forEach(languageRadio => {
|
|
||||||
languageRadio.checked = languageRadio.value === window.currentLanguage;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import { bindLanguageSelector } from './language-selection.js';
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -74,7 +73,19 @@ import { bindLanguageSelector } from './language-selection.js';
|
|||||||
/**
|
/**
|
||||||
* Switch pagebuilder to another language variant on changing the language selector.
|
* Switch pagebuilder to another language variant on changing the language selector.
|
||||||
*/
|
*/
|
||||||
bindLanguageSelector(document, window);
|
document.addEventListener("change", function(e) {
|
||||||
|
const select = e.target.closest("#language-selector select");
|
||||||
|
if (!select) return;
|
||||||
|
let selectedLanguage = select.value;
|
||||||
|
|
||||||
|
window.switchLanguage(selectedLanguage, function(success) {
|
||||||
|
if (success) {
|
||||||
|
activateLanguage(selectedLanguage);
|
||||||
|
} else {
|
||||||
|
select.value = window.currentLanguage;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Activate the given language variant in the pagebuilder.
|
* Activate the given language variant in the pagebuilder.
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ const sidebarHeader = document.getElementById('sidebar-header');
|
|||||||
const sidebarBottomButtons = document.getElementById('sidebar-bottom-buttons');
|
const sidebarBottomButtons = document.getElementById('sidebar-bottom-buttons');
|
||||||
const panelsEl = document.querySelector('.gjs-pn-panels');
|
const panelsEl = document.querySelector('.gjs-pn-panels');
|
||||||
const gjsEl = document.getElementById('gjs');
|
const gjsEl = document.getElementById('gjs');
|
||||||
const viewportSelector = document.getElementById('viewport-selector');
|
const viewportSelector = document.getElementById('viewport-select');
|
||||||
|
|
||||||
if (window.editor) {
|
if (window.editor) {
|
||||||
bindViewportSelector(window.editor, viewportSelector);
|
bindViewportSelector(window.editor, viewportSelector);
|
||||||
|
|||||||
@@ -4,9 +4,8 @@ export function bindViewportSelector(editor, selector) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
selector.addEventListener('change', function() {
|
selector.addEventListener('change', function() {
|
||||||
const checkedRadio = selector.querySelector('input[type="radio"]:checked');
|
if (selector.value) {
|
||||||
if (checkedRadio && checkedRadio.value) {
|
editor.setDevice(selector.value);
|
||||||
editor.setDevice(checkedRadio.value);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -155,7 +155,7 @@ body,
|
|||||||
/* SIDEBAR */
|
/* SIDEBAR */
|
||||||
|
|
||||||
.gjs-pn-views {
|
.gjs-pn-views {
|
||||||
top: 80px;
|
top: 40px;
|
||||||
|
|
||||||
.gjs-pn-btn {
|
.gjs-pn-btn {
|
||||||
width: 33.33%;
|
width: 33.33%;
|
||||||
@@ -268,9 +268,12 @@ body,
|
|||||||
position: absolute;
|
position: absolute;
|
||||||
box-shadow: none;
|
box-shadow: none;
|
||||||
width: $sidebar-width;
|
width: $sidebar-width;
|
||||||
height: 80px;
|
padding: 0 10px;
|
||||||
background: #22272e;
|
background: #22272e;
|
||||||
|
height: 40px;
|
||||||
z-index: 100;
|
z-index: 100;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
|
||||||
#language-selector,
|
#language-selector,
|
||||||
#viewport-selector {
|
#viewport-selector {
|
||||||
@@ -302,7 +305,7 @@ body,
|
|||||||
border-radius: 0;
|
border-radius: 0;
|
||||||
border: none;
|
border: none;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
height: 36px;
|
height: 40px;
|
||||||
width: 40px;
|
width: 40px;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
@@ -129,69 +129,42 @@ require __DIR__ . "/grapesjs/trait-manager.php";
|
|||||||
<button id="toggle-sidebar" class="btn btn-sm btn-ghost">
|
<button id="toggle-sidebar" class="btn btn-sm btn-ghost">
|
||||||
<i class="fa fa-bars"></i>
|
<i class="fa fa-bars"></i>
|
||||||
</button>
|
</button>
|
||||||
<div id="sidebar-header" class="flex flex-wrap items-center justify-between gap-1 p-2">
|
<div id="sidebar-header" class="flex flex-wrap items-center justify-between gap-1 px-2">
|
||||||
<?php if (sizeof(phpb_active_languages()) > 1): ?>
|
<?php if (sizeof(phpb_active_languages()) > 1): ?>
|
||||||
<div class="flex-grow"></div>
|
|
||||||
<div id="language-selector">
|
<div id="language-selector">
|
||||||
<fieldset>
|
<select class="select select-xs w-24 text-xs">
|
||||||
<legend class="sr-only"><?= phpb_e(
|
|
||||||
phpb_trans("website-manager.website-languages"),
|
|
||||||
) ?></legend>
|
|
||||||
<div class="join">
|
|
||||||
<?php foreach (
|
<?php foreach (
|
||||||
array_keys(phpb_active_languages())
|
phpb_active_languages()
|
||||||
as $languageCode
|
as $languageCode => $languageTranslation
|
||||||
): ?>
|
): ?>
|
||||||
<label class="btn btn-xs font-mono join-item cursor-pointer has-[:checked]:bg-primary has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary">
|
<option value="<?= phpb_e($languageCode) ?>" <?= $languageCode ===
|
||||||
<input type="radio" name="pagebuilder-language" value="<?= phpb_e(
|
$currentLanguage
|
||||||
$languageCode,
|
? "selected"
|
||||||
) ?>" class="sr-only" <?= $languageCode === $currentLanguage
|
|
||||||
? "checked"
|
|
||||||
: "" ?>>
|
: "" ?>>
|
||||||
<span><?= phpb_e(strtoupper($languageCode)) ?></span>
|
<?= phpb_e(strtoupper($languageCode)) ?> - <?= phpb_e(
|
||||||
</label>
|
$languageTranslation,
|
||||||
|
) ?>
|
||||||
|
</option>
|
||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
</div>
|
</select>
|
||||||
</fieldset>
|
|
||||||
</div>
|
</div>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
<fieldset id="viewport-selector" class="ml-auto">
|
<div id="viewport-selector" class="ml-auto">
|
||||||
<legend class="sr-only"><?= phpb_e(
|
<label class="sr-only" for="viewport-select"><?= phpb_trans(
|
||||||
phpb_trans("pagebuilder.viewport-selector"),
|
"pagebuilder.viewport-selector",
|
||||||
) ?></legend>
|
|
||||||
<div class="join">
|
|
||||||
<label class="btn btn-xs join-item cursor-pointer has-[:checked]:bg-primary has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary">
|
|
||||||
<input type="radio" name="pagebuilder-viewport" value="Desktop" class="sr-only" aria-label="<?= phpb_e(
|
|
||||||
phpb_trans("pagebuilder.viewport-desktop"),
|
|
||||||
) ?>" checked>
|
|
||||||
<i class="ph ph-desktop" aria-hidden="true"></i>
|
|
||||||
</label>
|
|
||||||
<label class="btn btn-xs join-item cursor-pointer has-[:checked]:bg-primary has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary">
|
|
||||||
<input type="radio" name="pagebuilder-viewport" value="Tablet" class="sr-only" aria-label="<?= phpb_e(
|
|
||||||
phpb_trans("pagebuilder.viewport-tablet"),
|
|
||||||
) ?>">
|
|
||||||
<i class="ph ph-device-tablet" aria-hidden="true"></i>
|
|
||||||
</label>
|
|
||||||
<label class="btn btn-xs join-item cursor-pointer has-[:checked]:bg-primary has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary">
|
|
||||||
<input type="radio" name="pagebuilder-viewport" value="Mobile" class="sr-only" aria-label="<?= phpb_e(
|
|
||||||
phpb_trans("pagebuilder.viewport-mobile"),
|
|
||||||
) ?>">
|
|
||||||
<i class="ph ph-device-mobile" aria-hidden="true"></i>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
</fieldset>
|
|
||||||
<div class="w-full">
|
|
||||||
<label for="page-selector" class="sr-only"><?= phpb_e(
|
|
||||||
phpb_trans("pagebuilder.page-selector"),
|
|
||||||
) ?></label>
|
) ?></label>
|
||||||
<select id="page-selector" class="select select-sm w-full" onchange="const pageUrl = this.value; this.value = this.querySelector('option[selected]').value; window.location.href = pageUrl">
|
<select id="viewport-select" class="select select-xs w-28 text-xs" aria-label="<?= phpb_e(
|
||||||
<?php foreach ($editablePages as $editablePage): ?>
|
phpb_trans("pagebuilder.viewport-selector"),
|
||||||
<option value="<?= phpb_e(
|
) ?>">
|
||||||
phpb_url("pagebuilder", ["page" => $editablePage->getId()]),
|
<option value="Desktop"><?= phpb_trans(
|
||||||
) ?>" <?= $editablePage->getId() === $page->getId()
|
"pagebuilder.viewport-desktop",
|
||||||
? "selected"
|
) ?></option>
|
||||||
: "" ?>><?= phpb_e($editablePage->getName()) ?></option>
|
<option value="Tablet"><?= phpb_trans(
|
||||||
<?php endforeach; ?>
|
"pagebuilder.viewport-tablet",
|
||||||
|
) ?></option>
|
||||||
|
<option value="Mobile"><?= phpb_trans(
|
||||||
|
"pagebuilder.viewport-mobile",
|
||||||
|
) ?></option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ namespace Plugi\Modules\Router;
|
|||||||
use Plugi\Contracts\PageContract;
|
use Plugi\Contracts\PageContract;
|
||||||
use Plugi\Contracts\PageTranslationContract;
|
use Plugi\Contracts\PageTranslationContract;
|
||||||
use Plugi\Contracts\RouterContract;
|
use Plugi\Contracts\RouterContract;
|
||||||
use Plugi\PageTranslationService;
|
|
||||||
use Plugi\Repositories\PageRepository;
|
use Plugi\Repositories\PageRepository;
|
||||||
use Plugi\Repositories\PageTranslationRepository;
|
use Plugi\Repositories\PageTranslationRepository;
|
||||||
|
|
||||||
@@ -50,46 +49,23 @@ class DatabasePageRouter implements RouterContract
|
|||||||
*/
|
*/
|
||||||
public function resolve($url)
|
public function resolve($url)
|
||||||
{
|
{
|
||||||
$this->routeParameters = [];
|
// strip URL query parameters
|
||||||
$this->routeToPageTranslationIdMapping = [];
|
$url = explode('?', $url, 2)[0];
|
||||||
$translationService = new PageTranslationService();
|
// split URL into segments using / as separator
|
||||||
$url = preg_split('/[?#]/', $url, 2)[0] ?? '';
|
|
||||||
$url = preg_replace('#/+#', '/', '/' . trim($url, '/')) ?: '/';
|
|
||||||
$urlSegments = explode('/', $url);
|
$urlSegments = explode('/', $url);
|
||||||
|
|
||||||
$activeLanguages = phpb_active_languages();
|
// request all routes and convert each to its segments using / as separator
|
||||||
$pageTranslations = $this->pageTranslationRepository->getAll(['id', 'route', 'locale']);
|
$pageTranslations = $this->pageTranslationRepository->getAll(['id', 'route']);
|
||||||
$routes = [];
|
$routes = [];
|
||||||
foreach ($pageTranslations as $pageTranslation) {
|
foreach ($pageTranslations as $pageTranslation) {
|
||||||
if (! array_key_exists($pageTranslation->locale, $activeLanguages)) {
|
$route = $pageTranslation->route;
|
||||||
continue;
|
$this->routeToPageTranslationIdMapping[$route] = $pageTranslation->id;
|
||||||
}
|
$routeSegments = explode('/', $route);
|
||||||
if (! is_string($pageTranslation->route) || trim($pageTranslation->route) === '') {
|
$routes[] = $routeSegments;
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$route = $translationService->normalizeRoute($pageTranslation->route);
|
// sort routes into the order for evaluation
|
||||||
$routeKey = $translationService->getRouteKey($route);
|
$orderedRoutes = $this->getRoutesInOrder($routes);
|
||||||
if (isset($routes[$routeKey])) {
|
|
||||||
$routes[$routeKey] = false;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$routes[$routeKey] = [
|
|
||||||
'route' => $route,
|
|
||||||
'translationId' => $pageTranslation->id,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$routeSegments = [];
|
|
||||||
foreach ($routes as $route) {
|
|
||||||
if ($route === false) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
$this->routeToPageTranslationIdMapping[$route['route']] = $route['translationId'];
|
|
||||||
$routeSegments[] = explode('/', $route['route']);
|
|
||||||
}
|
|
||||||
$orderedRoutes = $this->getRoutesInOrder($routeSegments);
|
|
||||||
|
|
||||||
// match each route with current URL segments and return the corresponding page once we find a match
|
// match each route with current URL segments and return the corresponding page once we find a match
|
||||||
foreach ($orderedRoutes as $routeSegments) {
|
foreach ($orderedRoutes as $routeSegments) {
|
||||||
@@ -210,7 +186,7 @@ class DatabasePageRouter implements RouterContract
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
// the URL segment matches if equal to the route segment
|
// the URL segment matches if equal to the route segment
|
||||||
if (strtolower($urlSegment) === strtolower($routeSegment)) {
|
if ($urlSegment === $routeSegment) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -151,7 +151,6 @@ class WebsiteManager implements WebsiteManagerContract
|
|||||||
exit();
|
exit();
|
||||||
} elseif ($action === "destroy") {
|
} elseif ($action === "destroy") {
|
||||||
$this->handleDestroy($page);
|
$this->handleDestroy($page);
|
||||||
exit();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -298,15 +297,6 @@ class WebsiteManager implements WebsiteManagerContract
|
|||||||
*/
|
*/
|
||||||
public function handleDestroy(PageContract $page)
|
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();
|
$pageRepository = new PageRepository();
|
||||||
if (!$pageRepository->destroy($page->getId())) {
|
if (!$pageRepository->destroy($page->getId())) {
|
||||||
phpb_redirect(phpb_url("website_manager"), [
|
phpb_redirect(phpb_url("website_manager"), [
|
||||||
@@ -339,15 +329,6 @@ class WebsiteManager implements WebsiteManagerContract
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
phpb_redirect(
|
|
||||||
phpb_url("website_manager", ["tab" => "settings"]),
|
|
||||||
[
|
|
||||||
"message-type" => "error",
|
|
||||||
"message" => phpb_trans(
|
|
||||||
"website-manager.invalid-default-language",
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ if (isset($page)) {
|
|||||||
|
|
||||||
$pageTranslations = $page ? $page->getTranslations() : [];
|
$pageTranslations = $page ? $page->getTranslations() : [];
|
||||||
$activeLanguages = phpb_active_languages();
|
$activeLanguages = phpb_active_languages();
|
||||||
$routeService = new \Plugi\PageTranslationService();
|
|
||||||
$fieldValue = static function (string $field, ?string $languageCode = null) use ($page, $pageTranslations): string {
|
$fieldValue = static function (string $field, ?string $languageCode = null) use ($page, $pageTranslations): string {
|
||||||
if ($languageCode !== null) {
|
if ($languageCode !== null) {
|
||||||
$postedValues = $_POST[$field] ?? null;
|
$postedValues = $_POST[$field] ?? null;
|
||||||
@@ -113,7 +112,6 @@ $javascriptValue = static function (string $value): string {
|
|||||||
<?php
|
<?php
|
||||||
$firstLang = true;
|
$firstLang = true;
|
||||||
foreach ($activeLanguages as $languageCode => $languageTranslation):
|
foreach ($activeLanguages as $languageCode => $languageTranslation):
|
||||||
$routePrefix = $routeService->getGeneratedRoutePrefix($languageCode, $firstLang);
|
|
||||||
$savedTranslation = $pageTranslations[$languageCode] ?? null;
|
$savedTranslation = $pageTranslations[$languageCode] ?? null;
|
||||||
$hasSavedTranslation = is_array($savedTranslation);
|
$hasSavedTranslation = is_array($savedTranslation);
|
||||||
$translationType = $fieldValue('type') !== '' ? $fieldValue('type') : ($page?->get('type') ?? 'static');
|
$translationType = $fieldValue('type') !== '' ? $fieldValue('type') : ($page?->get('type') ?? 'static');
|
||||||
@@ -149,7 +147,7 @@ $javascriptValue = static function (string $value): string {
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
<div class="space-y-3" x-data="{route: <?= $javascriptValue($fieldValue('route', $languageCode)) ?>, empty: true, locale: <?= $javascriptValue($routePrefix) ?>}" x-init="empty = route.length === 0">
|
<div class="space-y-3" x-data="{route: <?= $javascriptValue($fieldValue('route', $languageCode)) ?>, empty: true, locale: <?= $javascriptValue($firstLang ? '' : '/' . $languageCode) ?>}" x-init="empty = route.length === 0">
|
||||||
<div class="form-control w-full">
|
<div class="form-control w-full">
|
||||||
<label class="label" for="<?= phpb_e($languageCode) ?>-page-title">
|
<label class="label" for="<?= phpb_e($languageCode) ?>-page-title">
|
||||||
<span class="label-text"><?= phpb_trans('website-manager.page-title') ?></span>
|
<span class="label-text"><?= phpb_trans('website-manager.page-title') ?></span>
|
||||||
|
|||||||
@@ -161,20 +161,17 @@
|
|||||||
) ?>" class="btn btn-ghost btn-square btn-sm">
|
) ?>" class="btn btn-ghost btn-square btn-sm">
|
||||||
<i class="text-xl ph-duotone ph-gear" aria-hidden="true"></i>
|
<i class="text-xl ph-duotone ph-gear" aria-hidden="true"></i>
|
||||||
</a>
|
</a>
|
||||||
<form method="post" action="<?= phpb_url("website_manager", [
|
<a href="<?= phpb_url("website_manager", [
|
||||||
"route" => "page_settings",
|
"route" => "page_settings",
|
||||||
"action" => "destroy",
|
"action" => "destroy",
|
||||||
"page" => $page->getId(),
|
"page" => $page->getId(),
|
||||||
]) ?>">
|
]) ?>" title="<?= phpb_trans(
|
||||||
<?php phpb_csrf_field(); ?>
|
|
||||||
<button type="submit" title="<?= phpb_trans(
|
|
||||||
"website-manager.remove",
|
"website-manager.remove",
|
||||||
) ?>" aria-label="<?= phpb_e(
|
) ?>" aria-label="<?= phpb_e(
|
||||||
phpb_trans("website-manager.remove"),
|
phpb_trans("website-manager.remove"),
|
||||||
) ?>" class="btn btn-error btn-square btn-sm">
|
) ?>" class="btn btn-error btn-square btn-sm">
|
||||||
<i class="text-xl ph-duotone ph-trash" aria-hidden="true"></i>
|
<i class="text-xl ph-duotone ph-trash" aria-hidden="true"></i>
|
||||||
</button>
|
</a>
|
||||||
</form>
|
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
@@ -1,22 +1,13 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use Plugi\Extensions;
|
use Plugi\Extensions;
|
||||||
use Plugi\Setting;
|
|
||||||
|
|
||||||
$activeLanguages = phpb_active_languages();
|
$settingIns = phpb_instance('setting');
|
||||||
?>
|
?>
|
||||||
|
|
||||||
<form method="post" action="<?= phpb_url("website_manager", [
|
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'settings', 'action' => 'update', 'tab' => 'settings']) ?>">
|
||||||
"route" => "settings",
|
|
||||||
"action" => "update",
|
|
||||||
"tab" => "settings",
|
|
||||||
]) ?>">
|
|
||||||
<?php phpb_csrf_field(); ?>
|
<?php phpb_csrf_field(); ?>
|
||||||
<div class="space-y-6" x-data="{activeTab: 0, tabs: ['Website','Language','Theme','Extensions'], enabledLanguages: <?= str_replace(
|
<div class="space-y-6" x-data="{activeTab: 0, tabs: ['Website','Language','Theme','Extensions']}">
|
||||||
'"',
|
|
||||||
"'",
|
|
||||||
json_encode(array_keys($activeLanguages)),
|
|
||||||
) ?>}">
|
|
||||||
<header class="space-y-1">
|
<header class="space-y-1">
|
||||||
<h2 class="text-xl font-bold tracking-tight text-base-content">Site settings</h2>
|
<h2 class="text-xl font-bold tracking-tight text-base-content">Site settings</h2>
|
||||||
<p class="text-sm text-base-content/60">Configure language, appearance, and extension options for this site.</p>
|
<p class="text-sm text-base-content/60">Configure language, appearance, and extension options for this site.</p>
|
||||||
@@ -31,53 +22,37 @@ $activeLanguages = phpb_active_languages();
|
|||||||
</div>
|
</div>
|
||||||
<div id="settings-panel-1" class="space-y-6" role="tabpanel" aria-labelledby="settings-tab-1" tabindex="0" x-show="activeTab === 1">
|
<div id="settings-panel-1" class="space-y-6" role="tabpanel" aria-labelledby="settings-tab-1" tabindex="0" x-show="activeTab === 1">
|
||||||
<section class="space-y-4 rounded-box border border-base-300 bg-base-100 p-4 sm:p-6">
|
<section class="space-y-4 rounded-box border border-base-300 bg-base-100 p-4 sm:p-6">
|
||||||
<h2 class="text-lg font-semibold"><?= phpb_trans(
|
<h2 class="text-lg font-semibold"><?= phpb_trans('website-manager.website-languages') ?></h2>
|
||||||
"website-manager.website-languages",
|
|
||||||
) ?></h2>
|
|
||||||
<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
<?php foreach (
|
<?php
|
||||||
phpb_trans("languages")
|
foreach (phpb_trans('languages') as $locale => $localeText):
|
||||||
as $locale => $localeText
|
?>
|
||||||
): ?>
|
|
||||||
<div class="form-control">
|
<div class="form-control">
|
||||||
<label class="flex cursor-pointer items-center justify-between gap-4 rounded-box border border-base-300 bg-base-100 px-4 py-3 transition-colors hover:border-primary/40 hover:bg-base-200/50">
|
<label class="flex cursor-pointer items-center justify-between gap-4 rounded-box border border-base-300 bg-base-100 px-4 py-3 transition-colors hover:border-primary/40 hover:bg-base-200/50">
|
||||||
<span class="label-text"><?= phpb_e(
|
<span class="label-text"><?= phpb_e($localeText) ?></span>
|
||||||
$localeText,
|
<input type="checkbox" name="languages[]" value="<?= phpb_e($locale) ?>" <?= phpb_e($settingIns::has('languages', $locale)) ? 'checked' : '' ?> class="checkbox checkbox-sm" />
|
||||||
) ?></span>
|
|
||||||
<input type="checkbox" name="languages[]" value="<?= phpb_e(
|
|
||||||
$locale,
|
|
||||||
) ?>" <?= isset($activeLanguages[$locale])
|
|
||||||
? "checked"
|
|
||||||
: "" ?> @change="enabledLanguages = $event.target.checked ? [...enabledLanguages, $event.target.value] : enabledLanguages.filter(language => language !== $event.target.value)" class="checkbox checkbox-sm" />
|
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<?php endforeach; ?>
|
<?php
|
||||||
|
endforeach;
|
||||||
|
?>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<section class="max-w-2xl rounded-box border border-base-300 bg-base-100 p-4 sm:p-6">
|
<section class="max-w-2xl rounded-box border border-base-300 bg-base-100 p-4 sm:p-6">
|
||||||
<div class="form-control w-full">
|
<div class="form-control w-full">
|
||||||
<label for="default_language" class="label">
|
<label for="admin_language" class="label">
|
||||||
<span class="label-text"><?= phpb_trans(
|
<span class="label-text"><?= phpb_trans('website-manager.admin-language') ?> <strong><?= phpb_current_language() ?></strong></span>
|
||||||
"website-manager.default-language",
|
|
||||||
) ?></span>
|
|
||||||
</label>
|
</label>
|
||||||
<select class="select select-bordered w-full" id="default_language" name="default_language" title="<?= phpb_trans(
|
<select class="select select-bordered w-full" id="admin_language" name="admin_language" title="<?= phpb_trans('website-manager.languages-selector-placeholder') ?>" required>
|
||||||
"website-manager.languages-selector-placeholder",
|
<?php
|
||||||
) ?>" required>
|
$beLanguages = ['de', 'en', 'sv'];
|
||||||
<?php foreach (
|
foreach ($beLanguages as $locale):
|
||||||
phpb_trans("languages")
|
?>
|
||||||
as $locale => $localeText
|
<option value="<?= phpb_e($locale) ?>" <?= phpb_e(phpb_config('general.language') === $locale ? 'selected' : '') ?>><?= phpb_e(phpb_trans('languages.'.$locale)) ?></option>
|
||||||
): ?>
|
<?php
|
||||||
<option value="<?= phpb_e($locale) ?>" <?= phpb_e(
|
endforeach;
|
||||||
phpb_config("general.language") === $locale ? "selected" : "",
|
?>
|
||||||
) ?> :disabled="!enabledLanguages.includes('<?= phpb_e(
|
|
||||||
$locale,
|
|
||||||
) ?>')"><?= phpb_e($localeText) ?></option>
|
|
||||||
<?php endforeach; ?>
|
|
||||||
</select>
|
</select>
|
||||||
<p class="mt-2 text-sm text-base-content/60"><?= phpb_trans(
|
|
||||||
"website-manager.default-language-requires-enabled",
|
|
||||||
) ?></p>
|
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
@@ -85,84 +60,74 @@ $activeLanguages = phpb_active_languages();
|
|||||||
<section class="max-w-2xl rounded-box border border-base-300 bg-base-100 p-4 sm:p-6">
|
<section class="max-w-2xl rounded-box border border-base-300 bg-base-100 p-4 sm:p-6">
|
||||||
<div class="form-control w-full">
|
<div class="form-control w-full">
|
||||||
<label for="selected_theme" class="label">
|
<label for="selected_theme" class="label">
|
||||||
<span class="label-text"><?= phpb_trans(
|
<span class="label-text"><?= phpb_trans('website-manager.selected-theme') ?></span>
|
||||||
"website-manager.selected-theme",
|
|
||||||
) ?></span>
|
|
||||||
</label>
|
</label>
|
||||||
<select class="select select-bordered w-full" id="selected_theme" name="selected_theme" title="<?= phpb_trans(
|
<select class="select select-bordered w-full" id="selected_theme" name="selected_theme" title="<?= phpb_trans('website-manager.languages-selector-placeholder') ?>" required>
|
||||||
"website-manager.languages-selector-placeholder",
|
|
||||||
) ?>" required>
|
|
||||||
<?php
|
<?php
|
||||||
$themes = phpb_themes();
|
$themes = phpb_themes();
|
||||||
foreach ($themes as $theme => $themeConfig): ?>
|
foreach ($themes as $theme => $themeConfig):
|
||||||
<option value="<?= phpb_e($theme) ?>" <?= phpb_e(
|
?>
|
||||||
phpb_config("theme.active_theme") === $theme ? "selected" : "",
|
<option value="<?= phpb_e($theme) ?>" <?= phpb_e(phpb_config('theme.active_theme') === $theme ? 'selected' : '') ?>><?= phpb_e($themeConfig['title']) ?></option>
|
||||||
) ?>><?= phpb_e($themeConfig["title"]) ?></option>
|
<?php
|
||||||
<?php endforeach;
|
endforeach;
|
||||||
?>
|
?>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
<div id="settings-panel-3" class="space-y-6" role="tabpanel" aria-labelledby="settings-tab-3" tabindex="0" x-show="activeTab === 3">
|
<div id="settings-panel-3" class="space-y-6" role="tabpanel" aria-labelledby="settings-tab-3" tabindex="0" x-show="activeTab === 3">
|
||||||
<?php foreach (Extensions::getConfigs() as $extKey => $config):
|
<div class="flex flex-col gap-4">
|
||||||
$extensionSettings = Extensions::getSettings($extKey);
|
<?php
|
||||||
$activationKey = "extensions--{$extKey}--enabled";
|
foreach (Extensions::getConfigs() as $extKey => $config):
|
||||||
|
if(count(Extensions::getSettings($extKey)) === 0){
|
||||||
|
continue;
|
||||||
|
}
|
||||||
?>
|
?>
|
||||||
<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">
|
<details class="collapse collapse-arrow border border-base-300 bg-base-100">
|
||||||
<summary class="collapse-title text-base font-semibold">Extension settings</summary>
|
<summary class="collapse-title text-lg font-semibold"><?= phpb_e($config['title']) ?></summary>
|
||||||
<div class="collapse-content">
|
<div class="collapse-content">
|
||||||
<div class="space-y-4">
|
<div class="space-y-4">
|
||||||
<?php foreach ($extensionSettings as $setting): ?>
|
<?php
|
||||||
<?php if ($setting["type"] === "text"): ?>
|
foreach (Extensions::getSettings($extKey) as $setting):
|
||||||
|
?>
|
||||||
|
<?php
|
||||||
|
if ($setting['type'] === 'text'):
|
||||||
|
?>
|
||||||
<label class="form-control w-full gap-2">
|
<label class="form-control w-full gap-2">
|
||||||
<span class="label-text"><?= phpb_e(
|
<span class="label-text"><?= phpb_e($setting['label'] ?: $setting['name']) ?></span>
|
||||||
$setting["label"] ?: $setting["name"],
|
<input type="text" name="<?= phpb_e($setting['key']) ?>" value="<?= phpb_e($setting['value']) ?>" class="input input-bordered w-full" />
|
||||||
) ?></span>
|
|
||||||
<input type="text" name="<?= phpb_e(
|
|
||||||
$setting["key"],
|
|
||||||
) ?>" value="<?= phpb_e(
|
|
||||||
$setting["value"],
|
|
||||||
) ?>" class="input input-bordered w-full" />
|
|
||||||
</label>
|
</label>
|
||||||
<?php endif; ?>
|
<?php
|
||||||
<?php if ($setting["type"] === "toggle"): ?>
|
endif;
|
||||||
<div class="form-control" x-data="{state: <?= phpb_e(
|
?>
|
||||||
$setting["value"],
|
<?php
|
||||||
) ?>}">
|
if ($setting['type'] === 'toggle'):
|
||||||
|
?>
|
||||||
|
<div class="form-control" x-data="{state: <?= phpb_e($setting['value']) ?>}">
|
||||||
<label class="label cursor-pointer">
|
<label class="label cursor-pointer">
|
||||||
<span class="label-text"><?= phpb_e(
|
<span class="label-text"><?= phpb_e($setting['label'] ?: $setting['name']) ?></span>
|
||||||
$setting["label"] ?: $setting["name"],
|
<input type='hidden' :value="state" name="<?= phpb_e($setting['key']) ?>">
|
||||||
) ?></span>
|
|
||||||
<input type='hidden' :value="state" name="<?= phpb_e(
|
|
||||||
$setting["key"],
|
|
||||||
) ?>">
|
|
||||||
<input type="checkbox" class="toggle" x-model="state" />
|
<input type="checkbox" class="toggle" x-model="state" />
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<?php endif; ?>
|
<?php
|
||||||
<?php endforeach; ?>
|
endif;
|
||||||
|
?>
|
||||||
|
<?php
|
||||||
|
endforeach;
|
||||||
|
?>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</details>
|
</details>
|
||||||
<?php endif; ?>
|
<?php
|
||||||
</section>
|
endforeach;
|
||||||
<?php endforeach; ?>
|
?>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex justify-end border-t border-base-300 pt-6">
|
<div class="flex justify-end border-t border-base-300 pt-6">
|
||||||
<button type="submit" class="btn btn-primary">
|
<button type="submit" class="btn btn-primary">
|
||||||
<i class="ph-bold ph-floppy-disk" aria-hidden="true"></i>
|
<i class="ph-bold ph-floppy-disk" aria-hidden="true"></i>
|
||||||
<?= phpb_trans("website-manager.save-settings") ?>
|
<?= phpb_trans('website-manager.save-settings'); ?>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -173,16 +138,10 @@ $activeLanguages = phpb_active_languages();
|
|||||||
|
|
||||||
|
|
||||||
<!-- <div class="mt-8">-->
|
<!-- <div class="mt-8">-->
|
||||||
<!-- --><?php
|
<!-- --><?php //= phpb_trans('website-manager.pagebuilder-block-images') ?>
|
||||||
//= phpb_trans('website-manager.pagebuilder-block-images')
|
|
||||||
?>
|
|
||||||
<!-- </div>-->
|
<!-- </div>-->
|
||||||
<!-- <a href="--><?php
|
<!-- <a href="--><?php //= phpb_url('website_manager', ['route' => 'settings', 'action' => 'renderBlockThumbs']) ?><!--" class="btn btn-secondary btn-sm mr-1">-->
|
||||||
//= phpb_url('website_manager', ['route' => 'settings', 'action' => 'renderBlockThumbs'])
|
<!-- --><?php //= phpb_trans('website-manager.render-thumbs') ?>
|
||||||
?><!--" class="btn btn-secondary btn-sm mr-1">-->
|
|
||||||
<!-- --><?php
|
|
||||||
//= phpb_trans('website-manager.render-thumbs')
|
|
||||||
?>
|
|
||||||
<!-- </a>-->
|
<!-- </a>-->
|
||||||
|
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -6,30 +6,6 @@ use Plugi\Repositories\PageTranslationRepository;
|
|||||||
|
|
||||||
class PageTranslationService
|
class PageTranslationService
|
||||||
{
|
{
|
||||||
public function normalizeRoute(string $route): string
|
|
||||||
{
|
|
||||||
$route = preg_split('/[?#]/', trim($route), 2)[0] ?? '';
|
|
||||||
$segments = preg_split('#/+#', trim($route, '/'), -1, PREG_SPLIT_NO_EMPTY) ?: [];
|
|
||||||
foreach ($segments as &$segment) {
|
|
||||||
if ($segment !== '*' && ! preg_match('/^\{[^{}]+\}$/', $segment)) {
|
|
||||||
$segment = strtolower($segment);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
unset($segment);
|
|
||||||
|
|
||||||
return $segments === [] ? '/' : '/' . implode('/', $segments);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getRouteKey(string $route): string
|
|
||||||
{
|
|
||||||
return strtolower($this->normalizeRoute($route));
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getGeneratedRoutePrefix(string $locale, bool $isDefaultLocale): string
|
|
||||||
{
|
|
||||||
return $isDefaultLocale ? '' : '/' . $locale;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Return the requested locale, configured default, or first available locale, in that order.
|
* Return the requested locale, configured default, or first available locale, in that order.
|
||||||
*
|
*
|
||||||
|
|||||||
+18
-32
@@ -82,7 +82,6 @@ class Plugi
|
|||||||
$this->setDatabaseConnection();
|
$this->setDatabaseConnection();
|
||||||
$this->checkDatabaseDefinition();
|
$this->checkDatabaseDefinition();
|
||||||
$this->hydrateConfig();
|
$this->hydrateConfig();
|
||||||
$this->loadEnabledExtensions();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// init the default authentication, if enabled
|
// init the default authentication, if enabled
|
||||||
@@ -161,10 +160,20 @@ class Plugi
|
|||||||
$extensionFile = 'extensions/' . $extFolder . '/extension.php';
|
$extensionFile = 'extensions/' . $extFolder . '/extension.php';
|
||||||
$configFile = 'extensions/' . $extFolder . '/config.php';
|
$configFile = 'extensions/' . $extFolder . '/config.php';
|
||||||
if ($entry->isDir() && ! $entry->isDot() && file_exists($extensionFile) && file_exists($configFile)) {
|
if ($entry->isDir() && ! $entry->isDot() && file_exists($extensionFile) && file_exists($configFile)) {
|
||||||
|
require $extensionFile;
|
||||||
$extConfig = include($configFile);
|
$extConfig = include($configFile);
|
||||||
$extConfig['dir'] = 'extensions/' . $extFolder;
|
$extConfig['dir'] = 'extensions/' . $extFolder;
|
||||||
$extKey = $extConfig['identifier'];
|
$extKey = $extConfig['identifier'];
|
||||||
Extensions::registerConfig($extKey, $extConfig);
|
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'])){
|
if(array_key_exists('settings', $extConfig) && is_array($extConfig['settings'])){
|
||||||
Extensions::addSettings(array_map(function ($setting) use($extKey){
|
Extensions::addSettings(array_map(function ($setting) use($extKey){
|
||||||
$setting['key'] = 'ext--' . $extKey . '--' . $setting['name'];
|
$setting['key'] = 'ext--' . $extKey . '--' . $setting['name'];
|
||||||
@@ -177,26 +186,6 @@ 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.
|
* Set the Plugi configuration to the given array.
|
||||||
*
|
*
|
||||||
@@ -220,7 +209,7 @@ class Plugi
|
|||||||
$phpb_db = new DB();
|
$phpb_db = new DB();
|
||||||
$theme = Setting::get('selected_theme');
|
$theme = Setting::get('selected_theme');
|
||||||
if ($theme) $phpb_config['theme']['active_theme'] = $theme;
|
if ($theme) $phpb_config['theme']['active_theme'] = $theme;
|
||||||
$language = Setting::get('default_language') ?? Setting::get('admin_language');
|
$language = Setting::get('admin_language');
|
||||||
if ($language) $phpb_config['general']['language'] = $language;
|
if ($language) $phpb_config['general']['language'] = $language;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -234,7 +223,7 @@ class Plugi
|
|||||||
global $phpb_config;
|
global $phpb_config;
|
||||||
$theme = Setting::get('selected_theme');
|
$theme = Setting::get('selected_theme');
|
||||||
if ($theme) $phpb_config['theme']['active_theme'] = $theme;
|
if ($theme) $phpb_config['theme']['active_theme'] = $theme;
|
||||||
$language = Setting::get('default_language') ?? Setting::get('admin_language');
|
$language = Setting::get('admin_language');
|
||||||
if ($language) $phpb_config['general']['language'] = $language;
|
if ($language) $phpb_config['general']['language'] = $language;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -484,16 +473,9 @@ class Plugi
|
|||||||
$previewToken = $_GET['previewToken'] ?? null;
|
$previewToken = $_GET['previewToken'] ?? null;
|
||||||
$isAuthenticatedPreview = $this->isAuthenticatedPreviewRequest($previewToken);
|
$isAuthenticatedPreview = $this->isAuthenticatedPreviewRequest($previewToken);
|
||||||
|
|
||||||
$pageTranslation = $this->resolvePageLanguageVariantFromUrl(phpb_current_relative_url());
|
|
||||||
if ($pageTranslation) {
|
|
||||||
global $phpb_request_language;
|
|
||||||
$phpb_request_language = $pageTranslation->locale;
|
|
||||||
$this->loadTranslations($pageTranslation->locale);
|
|
||||||
}
|
|
||||||
|
|
||||||
// try to find page in cache
|
// try to find page in cache
|
||||||
$cache = phpb_instance('cache');
|
$cache = phpb_instance('cache');
|
||||||
if ($pageTranslation && ! $hasPreviewToken &&
|
if (! $hasPreviewToken &&
|
||||||
phpb_config('cache.enabled') &&
|
phpb_config('cache.enabled') &&
|
||||||
! isset($_GET['ignore_cache']) &&
|
! isset($_GET['ignore_cache']) &&
|
||||||
! isset($_GET['refresh_cache']) &&
|
! isset($_GET['refresh_cache']) &&
|
||||||
@@ -508,7 +490,11 @@ class Plugi
|
|||||||
}
|
}
|
||||||
|
|
||||||
// let the page router resolve the current URL
|
// let the page router resolve the current URL
|
||||||
$page = $pageTranslation?->getPage();
|
$page = null;
|
||||||
|
$pageTranslation = $this->resolvePageLanguageVariantFromUrl(phpb_current_relative_url());
|
||||||
|
if ($pageTranslation) {
|
||||||
|
$page = $pageTranslation->getPage();
|
||||||
|
}
|
||||||
// if the URL cannot be resolved, but the lowercase version of the URL can be resolved, redirect to the lowercase URL
|
// if the URL cannot be resolved, but the lowercase version of the URL can be resolved, redirect to the lowercase URL
|
||||||
if (($page->logic ?? '') === 'page-not-found' && phpb_current_relative_url() !== strtolower(phpb_current_relative_url())) {
|
if (($page->logic ?? '') === 'page-not-found' && phpb_current_relative_url() !== strtolower(phpb_current_relative_url())) {
|
||||||
$pageLowerCaseUrlTranslation = $this->resolvePageLanguageVariantFromUrl(strtolower(phpb_current_relative_url()));
|
$pageLowerCaseUrlTranslation = $this->resolvePageLanguageVariantFromUrl(strtolower(phpb_current_relative_url()));
|
||||||
|
|||||||
@@ -121,12 +121,8 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
if ($updateResult) {
|
if ($updateResult) {
|
||||||
$newRoutes = [];
|
|
||||||
foreach ($activeLanguages as $languageCode => $languageTranslation) {
|
|
||||||
$newRoutes[] = $translationService->normalizeRoute($data['route'][$languageCode]);
|
|
||||||
}
|
|
||||||
$translationService->invalidateRoutes(
|
$translationService->invalidateRoutes(
|
||||||
array_merge($oldRoutes, $newRoutes),
|
array_merge($oldRoutes, array_values($data["route"])),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return $updateResult;
|
return $updateResult;
|
||||||
@@ -150,36 +146,27 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
|
|||||||
}
|
}
|
||||||
|
|
||||||
$pageTranslationRepository = new PageTranslationRepository();
|
$pageTranslationRepository = new PageTranslationRepository();
|
||||||
$translationService = new PageTranslationService();
|
if (
|
||||||
$existingTranslations = [];
|
!$pageTranslationRepository->destroyWhere(
|
||||||
foreach ($pageTranslationRepository->getForPages([$page->getId()]) as $existingTranslation) {
|
phpb_config("page.translation.foreign_key"),
|
||||||
$existingTranslations[$existingTranslation->locale] = $existingTranslation;
|
$page->getId(),
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
foreach ($activeLanguages as $languageCode => $languageTranslation) {
|
foreach ($activeLanguages as $languageCode => $languageTranslation) {
|
||||||
$existingTranslation = $existingTranslations[$languageCode] ?? null;
|
$translation = $pageTranslationRepository->create([
|
||||||
$route = $data['route'][$languageCode];
|
|
||||||
if (! $existingTranslation || $route !== $existingTranslation->route) {
|
|
||||||
$route = $translationService->normalizeRoute($route);
|
|
||||||
}
|
|
||||||
$translationData = [
|
|
||||||
phpb_config("page.translation.foreign_key") => $page->getId(),
|
phpb_config("page.translation.foreign_key") => $page->getId(),
|
||||||
"locale" => $languageCode,
|
"locale" => $languageCode,
|
||||||
"title" => $data["title"][$languageCode],
|
"title" => $data["title"][$languageCode],
|
||||||
"meta_title" => $data["meta_title"][$languageCode],
|
"meta_title" => $data["meta_title"][$languageCode],
|
||||||
"meta_description" => $data["meta_description"][$languageCode],
|
"meta_description" => $data["meta_description"][$languageCode],
|
||||||
"route" => $route,
|
"route" => $data["route"][$languageCode],
|
||||||
"target" => $data["target"][$languageCode],
|
"target" => $data["target"][$languageCode],
|
||||||
];
|
]);
|
||||||
if ($existingTranslation) {
|
if (!($translation instanceof PageTranslationContract)) {
|
||||||
if (! $pageTranslationRepository->update($existingTranslation, $translationData)) {
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
$translation = $pageTranslationRepository->create($translationData);
|
|
||||||
if (! ($translation instanceof PageTranslationContract)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
@@ -246,49 +233,17 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
|
|||||||
array $activeLanguages,
|
array $activeLanguages,
|
||||||
$pageId = null,
|
$pageId = null,
|
||||||
): bool {
|
): bool {
|
||||||
$translationService = new PageTranslationService();
|
|
||||||
$existingTranslations = [];
|
|
||||||
if ($pageId !== null) {
|
|
||||||
foreach ((new PageTranslationRepository())->getForPages([$pageId]) as $translation) {
|
|
||||||
$existingTranslations[$translation->locale] = $translation;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$routes = [];
|
$routes = [];
|
||||||
foreach ($activeLanguages as $languageCode => $languageTranslation) {
|
foreach ($activeLanguages as $languageCode => $languageTranslation) {
|
||||||
$route = $data["route"][$languageCode];
|
$route = $data["route"][$languageCode];
|
||||||
$routeKey = $translationService->getRouteKey($route);
|
if (array_key_exists($route, $routes)) {
|
||||||
if (array_key_exists($routeKey, $routes)) {
|
|
||||||
$unchangedRoutes = $pageId !== null;
|
|
||||||
foreach (array_keys($routes[$routeKey]) as $existingLocale) {
|
|
||||||
if (($existingTranslations[$existingLocale]->route ?? null) !== $data['route'][$existingLocale]) {
|
|
||||||
$unchangedRoutes = false;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (! $unchangedRoutes || ($existingTranslations[$languageCode]->route ?? null) !== $route) {
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
$routes[$route] = true;
|
||||||
$routes[$routeKey][$languageCode] = $route;
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach ($routes as $routeKey => $localizedRoutes) {
|
|
||||||
foreach ($existingTranslations as $existingLocale => $translation) {
|
|
||||||
if (isset($activeLanguages[$existingLocale]) || $translationService->getRouteKey((string) $translation->route) !== $routeKey) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
foreach ($localizedRoutes as $languageCode => $route) {
|
|
||||||
if (($existingTranslations[$languageCode]->route ?? null) !== $route) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$pageTranslationRepository = new PageTranslationRepository();
|
$pageTranslationRepository = new PageTranslationRepository();
|
||||||
foreach ($routes as $localizedRoutes) {
|
foreach (array_keys($routes) as $route) {
|
||||||
$route = reset($localizedRoutes);
|
|
||||||
if ($pageTranslationRepository->routeExists($route, $pageId)) {
|
if ($pageTranslationRepository->routeExists($route, $pageId)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
namespace Plugi\Repositories;
|
namespace Plugi\Repositories;
|
||||||
|
|
||||||
use Plugi\Contracts\PageTranslationRepositoryContract;
|
use Plugi\Contracts\PageTranslationRepositoryContract;
|
||||||
use Plugi\PageTranslationService;
|
|
||||||
|
|
||||||
class PageTranslationRepository extends BaseRepository implements PageTranslationRepositoryContract
|
class PageTranslationRepository extends BaseRepository implements PageTranslationRepositoryContract
|
||||||
{
|
{
|
||||||
@@ -40,23 +39,16 @@ class PageTranslationRepository extends BaseRepository implements PageTranslatio
|
|||||||
*/
|
*/
|
||||||
public function routeExists(string $route, $excludedPageId = null): bool
|
public function routeExists(string $route, $excludedPageId = null): bool
|
||||||
{
|
{
|
||||||
|
$query = "SELECT 1 FROM {$this->table} WHERE route = ?";
|
||||||
|
$parameters = [$route];
|
||||||
|
if ($excludedPageId !== null) {
|
||||||
$foreignKey = $this->removeNonAlphaNumeric(phpb_config('page.translation.foreign_key'));
|
$foreignKey = $this->removeNonAlphaNumeric(phpb_config('page.translation.foreign_key'));
|
||||||
$routes = $this->db->select("SELECT route, {$foreignKey} FROM {$this->table}", []);
|
$query .= " AND {$foreignKey} != ?";
|
||||||
$translationService = new PageTranslationService();
|
$parameters[] = $excludedPageId;
|
||||||
$routeKey = $translationService->getRouteKey($route);
|
|
||||||
foreach ($routes as $translation) {
|
|
||||||
if ($excludedPageId !== null && (string) $translation[$foreignKey] === (string) $excludedPageId) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (! is_string($translation['route']) || trim($translation['route']) === '') {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if ($translationService->getRouteKey((string) $translation['route']) === $routeKey) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
$query .= ' LIMIT 1';
|
||||||
|
|
||||||
return false;
|
return ! empty($this->db->select($query, $parameters));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -21,60 +21,27 @@ class SettingRepository extends BaseRepository implements SettingRepositoryContr
|
|||||||
*/
|
*/
|
||||||
public function updateSettings(array $data)
|
public function updateSettings(array $data)
|
||||||
{
|
{
|
||||||
if (! $this->hasValidLanguageSettings($data)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->db->transaction(function () use ($data) {
|
|
||||||
foreach ($data as $key => $value) {
|
foreach ($data as $key => $value) {
|
||||||
$isArray = is_array($value) ? 1 : 0;
|
$isArray = is_array($value) ? 1 : 0;
|
||||||
if ($isArray) {
|
if ($isArray) {
|
||||||
$value = implode(',', $value);
|
$value = implode(',', $value);
|
||||||
}
|
}
|
||||||
$setting = [
|
$ins = $this->findWhere('setting', $key);
|
||||||
|
if (empty($ins)) {
|
||||||
|
$this->create([
|
||||||
'setting' => $key,
|
'setting' => $key,
|
||||||
'value' => $value,
|
'value' => $value,
|
||||||
'is_array' => $isArray,
|
'is_array' => $isArray,
|
||||||
];
|
]);
|
||||||
$ins = $this->findWhere('setting', $key);
|
} else {
|
||||||
if (empty($ins)) {
|
$this->update($ins[0], [
|
||||||
if (! $this->create($setting)) {
|
'setting' => $key,
|
||||||
return false;
|
'value' => $value,
|
||||||
}
|
'is_array' => $isArray,
|
||||||
} elseif (! $this->update($ins[0], $setting)) {
|
]);
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private function hasValidLanguageSettings(array $data): bool
|
|
||||||
{
|
|
||||||
if (! array_intersect(['languages', 'default_language', 'admin_language'], array_keys($data))) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
$languages = array_key_exists('languages', $data)
|
|
||||||
? $data['languages']
|
|
||||||
: array_keys(phpb_active_languages());
|
|
||||||
$defaultLanguage = $data['default_language']
|
|
||||||
?? phpb_instance('setting')::get('default_language')
|
|
||||||
?? $data['admin_language']
|
|
||||||
?? phpb_config('general.language');
|
|
||||||
$availableLanguages = phpb_trans('languages');
|
|
||||||
|
|
||||||
if (! is_array($languages) || $languages === [] || ! is_string($defaultLanguage)
|
|
||||||
|| ! is_array($availableLanguages) || ! isset($availableLanguages[$defaultLanguage])
|
|
||||||
|| ! in_array($defaultLanguage, $languages, true)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach ($languages as $language) {
|
|
||||||
if (! is_string($language) || ! isset($availableLanguages[$language])) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -1,148 +0,0 @@
|
|||||||
<?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");
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
<?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");
|
|
||||||
@@ -1,136 +0,0 @@
|
|||||||
<?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");
|
|
||||||
@@ -54,14 +54,11 @@ class PageCreationTestDatabase extends DB
|
|||||||
public int $pageTranslationAllCallCount = 0;
|
public int $pageTranslationAllCallCount = 0;
|
||||||
public int $pageTranslationBatchSelectCount = 0;
|
public int $pageTranslationBatchSelectCount = 0;
|
||||||
public ?int $failOnTranslationInsert = null;
|
public ?int $failOnTranslationInsert = null;
|
||||||
public bool $failOnTranslationUpdate = false;
|
|
||||||
public bool $throwOnTranslationFailure = false;
|
public bool $throwOnTranslationFailure = false;
|
||||||
public ?string $failOnDeleteTable = null;
|
public ?string $failOnDeleteTable = null;
|
||||||
public bool $throwOnDeleteFailure = false;
|
public bool $throwOnDeleteFailure = false;
|
||||||
public bool $failOnPageUpdate = false;
|
public bool $failOnPageUpdate = false;
|
||||||
public ?int $failOnPageUpdateId = null;
|
public ?int $failOnPageUpdateId = null;
|
||||||
public ?int $failOnSettingWrite = null;
|
|
||||||
public int $settingWriteCount = 0;
|
|
||||||
public array $schemaDiffs = [];
|
public array $schemaDiffs = [];
|
||||||
|
|
||||||
public function __construct()
|
public function __construct()
|
||||||
@@ -73,12 +70,6 @@ class PageCreationTestDatabase extends DB
|
|||||||
|
|
||||||
public function query(string $query, array $parameters = [])
|
public function query(string $query, array $parameters = [])
|
||||||
{
|
{
|
||||||
if (str_starts_with($query, 'INSERT INTO settings') || str_starts_with($query, 'UPDATE settings SET')) {
|
|
||||||
$this->settingWriteCount++;
|
|
||||||
if ($this->settingWriteCount === $this->failOnSettingWrite) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($this->failOnDeleteTable !== null && str_starts_with($query, 'DELETE FROM ' . $this->failOnDeleteTable)) {
|
if ($this->failOnDeleteTable !== null && str_starts_with($query, 'DELETE FROM ' . $this->failOnDeleteTable)) {
|
||||||
if ($this->throwOnDeleteFailure) {
|
if ($this->throwOnDeleteFailure) {
|
||||||
throw new PDOException('Simulated page deletion failure.');
|
throw new PDOException('Simulated page deletion failure.');
|
||||||
@@ -101,9 +92,6 @@ class PageCreationTestDatabase extends DB
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if ($this->failOnTranslationUpdate && str_starts_with($query, 'UPDATE page_translations SET')) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return parent::query($query, $parameters);
|
return parent::query($query, $parameters);
|
||||||
}
|
}
|
||||||
@@ -140,12 +128,6 @@ class PageCreationTestDatabase extends DB
|
|||||||
|
|
||||||
public function createSchema(): void
|
public function createSchema(): void
|
||||||
{
|
{
|
||||||
$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
|
|
||||||
)');
|
|
||||||
$this->pdo->exec('CREATE TABLE pages (
|
$this->pdo->exec('CREATE TABLE pages (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
name TEXT,
|
name TEXT,
|
||||||
@@ -230,24 +212,14 @@ class PageCreationSchemaMigrationTestDatabase extends DB
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function transaction(callable $callback): mixed
|
|
||||||
{
|
|
||||||
return $callback();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function select(string $query, array $parameters): array
|
public function select(string $query, array $parameters): array
|
||||||
{
|
{
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
public function findWithId(string $table, $id): array
|
|
||||||
{
|
|
||||||
return [['id' => $id]];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function lastInsertId(): string
|
public function lastInsertId(): string
|
||||||
{
|
{
|
||||||
return '1';
|
return '0';
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getDBDefinitionHash(): string
|
public function getDBDefinitionHash(): string
|
||||||
@@ -296,11 +268,11 @@ class PageCreationTestCache
|
|||||||
|
|
||||||
class PageCreationTestPublicRouter
|
class PageCreationTestPublicRouter
|
||||||
{
|
{
|
||||||
public function __construct(private ?PageTranslationContract $translation)
|
public function __construct(private PageTranslationContract $translation)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
public function resolve(string $url): ?PageTranslationContract
|
public function resolve(string $url): PageTranslationContract
|
||||||
{
|
{
|
||||||
return $this->translation;
|
return $this->translation;
|
||||||
}
|
}
|
||||||
@@ -309,12 +281,10 @@ class PageCreationTestPublicRouter
|
|||||||
class PageCreationTestPublicPageBuilder
|
class PageCreationTestPublicPageBuilder
|
||||||
{
|
{
|
||||||
public array $renderedData = [];
|
public array $renderedData = [];
|
||||||
public ?string $renderedLanguage = null;
|
|
||||||
|
|
||||||
public function renderPage(PageContract $page, ?string $language = null): string
|
public function renderPage(PageContract $page, ?string $language = null): string
|
||||||
{
|
{
|
||||||
$this->renderedData = $page->getBuilderData();
|
$this->renderedData = $page->getBuilderData();
|
||||||
$this->renderedLanguage = $language;
|
|
||||||
return '<!doctype html><html><head><title>Page</title></head><body><main>Theme layout</main>'
|
return '<!doctype html><html><head><title>Page</title></head><body><main>Theme layout</main>'
|
||||||
. '<a href="/about?locale=de#intro">Internal</a>'
|
. '<a href="/about?locale=de#intro">Internal</a>'
|
||||||
. '<a href="https://example.test/contact?next=1">Absolute internal</a>'
|
. '<a href="https://example.test/contact?next=1">Absolute internal</a>'
|
||||||
@@ -329,7 +299,7 @@ class PageCreationTestPublicPageBuilder
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function runPageCreationPublicRequest(?PageTranslationContract $translation, array $query, bool $authenticated, string $sessionToken, ?string $cachedContent = null): array
|
function runPageCreationPublicRequest(PageTranslationContract $translation, array $query, bool $authenticated, string $sessionToken): array
|
||||||
{
|
{
|
||||||
global $pageCreationCurrentUrl;
|
global $pageCreationCurrentUrl;
|
||||||
|
|
||||||
@@ -342,7 +312,7 @@ function runPageCreationPublicRequest(?PageTranslationContract $translation, arr
|
|||||||
$pageCreationCurrentUrl = '/new-page' . ($query === [] ? '' : '?' . http_build_query($query));
|
$pageCreationCurrentUrl = '/new-page' . ($query === [] ? '' : '?' . http_build_query($query));
|
||||||
PageCreationTestCache::$cacheReads = [];
|
PageCreationTestCache::$cacheReads = [];
|
||||||
PageCreationTestCache::$cacheWrites = [];
|
PageCreationTestCache::$cacheWrites = [];
|
||||||
PageCreationTestCache::$cachedContent = $cachedContent;
|
PageCreationTestCache::$cachedContent = null;
|
||||||
\Plugi\Modules\GrapesJS\PageRenderer::$canBeCached = true;
|
\Plugi\Modules\GrapesJS\PageRenderer::$canBeCached = true;
|
||||||
|
|
||||||
$pageBuilder = new PageCreationTestPublicPageBuilder();
|
$pageBuilder = new PageCreationTestPublicPageBuilder();
|
||||||
@@ -768,7 +738,7 @@ $cases = [
|
|||||||
assertPageCreation($page === true, 'The submitted homepage payload did not create a page.');
|
assertPageCreation($page === true, 'The submitted homepage payload did not create a page.');
|
||||||
assertPageCreation(count($translations) === 2, 'The homepage did not persist both localized translations.');
|
assertPageCreation(count($translations) === 2, 'The homepage did not persist both localized translations.');
|
||||||
assertPageCreation($translations[0]['route'] === '/', 'The English homepage route was not preserved.');
|
assertPageCreation($translations[0]['route'] === '/', 'The English homepage route was not preserved.');
|
||||||
assertPageCreation($translations[1]['route'] === '/de', 'The German homepage route was not stored without a trailing slash.');
|
assertPageCreation($translations[1]['route'] === '/de/', 'The German homepage route was not preserved.');
|
||||||
},
|
},
|
||||||
'generated routes persist for every active locale' => function (): void {
|
'generated routes persist for every active locale' => function (): void {
|
||||||
resetPageCreationDatabase();
|
resetPageCreationDatabase();
|
||||||
@@ -871,107 +841,6 @@ $cases = [
|
|||||||
);
|
);
|
||||||
assertPageCreation($phpb_db->pageTranslationAllCallCount === 0, 'Route validation loaded every translation instead of querying for a collision.');
|
assertPageCreation($phpb_db->pageTranslationAllCallCount === 0, 'Route validation loaded every translation instead of querying for a collision.');
|
||||||
},
|
},
|
||||||
'page route writes canonicalize slash and case variants' => function (): void {
|
|
||||||
resetPageCreationDatabase();
|
|
||||||
$repository = new PageRepository();
|
|
||||||
assertPageCreation($repository->create(pageCreationPayload([
|
|
||||||
'route' => ['en' => '/About//Us/', 'de' => '/DE/Neue-Seite/'],
|
|
||||||
])) === true, 'A route with redundant slashes and uppercase characters was rejected.');
|
|
||||||
|
|
||||||
global $phpb_db;
|
|
||||||
$translations = $phpb_db->rows('page_translations');
|
|
||||||
assertPageCreation($translations[0]['route'] === '/about/us', 'The English route was not stored canonically.');
|
|
||||||
assertPageCreation($translations[1]['route'] === '/de/neue-seite', 'The German route was not stored canonically.');
|
|
||||||
},
|
|
||||||
'route collision checks reject canonical slash and case variants' => function (): void {
|
|
||||||
resetPageCreationDatabase();
|
|
||||||
$repository = new PageRepository();
|
|
||||||
$repository->create(pageCreationPayload([
|
|
||||||
'route' => ['en' => '/About/Us/', 'de' => '/de/uns'],
|
|
||||||
]));
|
|
||||||
|
|
||||||
assertPageCreation($repository->create(pageCreationPayload([
|
|
||||||
'name' => 'Canonical collision',
|
|
||||||
'route' => ['en' => '/ABOUT//US', 'de' => '/de/another'],
|
|
||||||
])) === false, 'A case or slash variant of a stored route was not rejected.');
|
|
||||||
},
|
|
||||||
'unchanged legacy routes remain stored until edited' => function (): void {
|
|
||||||
resetPageCreationDatabase();
|
|
||||||
$repository = new PageRepository();
|
|
||||||
$repository->create(pageCreationPayload());
|
|
||||||
global $phpb_db;
|
|
||||||
$pageId = $phpb_db->rows('pages')[0]['id'];
|
|
||||||
$phpb_db->query('UPDATE page_translations SET route = ? WHERE page_id = ? AND locale = ?', ['/Legacy-Path/', $pageId, 'en']);
|
|
||||||
$page = $repository->findWithId($pageId);
|
|
||||||
|
|
||||||
assertPageCreation($repository->update($page, pageCreationPayload([
|
|
||||||
'name' => 'Updated title only',
|
|
||||||
'route' => ['en' => '/Legacy-Path/'],
|
|
||||||
])) === true, 'An unrelated page edit failed for a legacy route.');
|
|
||||||
assertPageCreation($phpb_db->rows('page_translations')[0]['route'] === '/Legacy-Path/', 'An unchanged legacy route was rewritten during an unrelated edit.');
|
|
||||||
},
|
|
||||||
'ambiguous legacy routes do not resolve to an arbitrary translation' => function (): void {
|
|
||||||
resetPageCreationDatabase();
|
|
||||||
$repository = new PageRepository();
|
|
||||||
$repository->create(pageCreationPayload(['route' => ['en' => '/legacy-path', 'de' => '/de/first']]));
|
|
||||||
$repository->create(pageCreationPayload(['name' => 'Second page', 'route' => ['en' => '/other-path', 'de' => '/de/second']]));
|
|
||||||
global $phpb_db;
|
|
||||||
$pageIds = array_column($phpb_db->rows('pages'), 'id');
|
|
||||||
$phpb_db->query('UPDATE page_translations SET route = ? WHERE page_id = ? AND locale = ?', ['/LEGACY-PATH/', $pageIds[1], 'en']);
|
|
||||||
|
|
||||||
assertPageCreation((new DatabasePageRouter())->resolve('/legacy-path') === null, 'A normalized legacy route collision resolved to an arbitrary page.');
|
|
||||||
},
|
|
||||||
'router normalizes request paths and keeps route parameters and wildcards' => function (): void {
|
|
||||||
resetPageCreationDatabase();
|
|
||||||
$repository = new PageRepository();
|
|
||||||
assertPageCreation($repository->create(pageCreationPayload([
|
|
||||||
'route' => ['en' => '/Catalog/{ProductID}/', 'de' => '/DE/Files/*'],
|
|
||||||
])) === true, 'Routes for parameter and wildcard matching were not created.');
|
|
||||||
|
|
||||||
$router = new DatabasePageRouter();
|
|
||||||
$parameterRoute = $router->resolve('//CATALOG/AbC/?preview=1');
|
|
||||||
assertPageCreation($parameterRoute instanceof PageTranslationContract, 'Case/slash variants did not match a parameterized route.');
|
|
||||||
assertPageCreation($parameterRoute->route === '/catalog/{ProductID}', 'The resolved parameter route was not canonicalized.');
|
|
||||||
assertPageCreation(($GLOBALS['phpb_route_parameters']['ProductID'] ?? null) === 'AbC', 'The route parameter name or value was changed.');
|
|
||||||
|
|
||||||
$wildcardRoute = $router->resolve('/DE/FILES/a/b/');
|
|
||||||
assertPageCreation($wildcardRoute instanceof PageTranslationContract && $wildcardRoute->locale === 'de', 'A case/slash variant did not match the wildcard route.');
|
|
||||||
},
|
|
||||||
'disabled-language routes are hidden and translation rows survive edits' => function (): void {
|
|
||||||
resetPageCreationDatabase();
|
|
||||||
$repository = new PageRepository();
|
|
||||||
assertPageCreation($repository->create(pageCreationPayload()) === true, 'The multilingual page was not created.');
|
|
||||||
global $phpb_db, $pageCreationLanguages;
|
|
||||||
$pageId = $phpb_db->rows('pages')[0]['id'];
|
|
||||||
$pageCreationLanguages = ['en' => []];
|
|
||||||
$page = $repository->findWithId($pageId);
|
|
||||||
assertPageCreation($repository->update($page, pageCreationPayload([
|
|
||||||
'name' => 'Edited with German disabled',
|
|
||||||
'title' => ['en' => 'Changed English', 'de' => 'Must remain untouched'],
|
|
||||||
'route' => ['en' => '/changed-english'],
|
|
||||||
])) === true, 'Editing with a language disabled failed.');
|
|
||||||
|
|
||||||
$translations = $phpb_db->rows('page_translations');
|
|
||||||
assertPageCreation(count($translations) === 2, 'Editing deleted an inactive translation.');
|
|
||||||
$germanTranslation = array_values(array_filter($translations, static fn(array $translation): bool => $translation['locale'] === 'de'))[0] ?? null;
|
|
||||||
assertPageCreation($germanTranslation !== null && $germanTranslation['title'] === 'Neue Seite' && $germanTranslation['route'] === '/de/new-page', 'Editing changed the inactive translation data.');
|
|
||||||
assertPageCreation((new DatabasePageRouter())->resolve('/de/new-page') === null, 'A disabled locale remained publicly routable.');
|
|
||||||
|
|
||||||
$pageCreationLanguages = ['en' => [], 'de' => []];
|
|
||||||
assertPageCreation((new DatabasePageRouter())->resolve('/DE/NEW-PAGE') instanceof PageTranslationContract, 'Re-enabling a locale did not restore its stored route.');
|
|
||||||
},
|
|
||||||
'active route edits cannot collide with a stored inactive translation' => function (): void {
|
|
||||||
resetPageCreationDatabase();
|
|
||||||
$repository = new PageRepository();
|
|
||||||
$repository->create(pageCreationPayload());
|
|
||||||
global $phpb_db, $pageCreationLanguages;
|
|
||||||
$pageCreationLanguages = ['en' => []];
|
|
||||||
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
|
|
||||||
|
|
||||||
assertPageCreation($repository->update($page, pageCreationPayload([
|
|
||||||
'route' => ['en' => '/de/new-page'],
|
|
||||||
])) === false, 'An active route was allowed to collide with an inactive translation on the same page.');
|
|
||||||
},
|
|
||||||
'page locale coverage summarizes complete partial and absent translations in one batch' => function (): void {
|
'page locale coverage summarizes complete partial and absent translations in one batch' => function (): void {
|
||||||
resetPageCreationDatabase();
|
resetPageCreationDatabase();
|
||||||
$repository = new PageRepository();
|
$repository = new PageRepository();
|
||||||
@@ -1058,38 +927,6 @@ $cases = [
|
|||||||
'Successful deletion did not invalidate every stored localized route: ' . json_encode(PageCreationTestCache::$invalidatedRoutes)
|
'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 {
|
'failed page deletion rolls back translation cleanup without invalidating caches' => function (): void {
|
||||||
resetPageCreationDatabase();
|
resetPageCreationDatabase();
|
||||||
$repository = new PageRepository();
|
$repository = new PageRepository();
|
||||||
@@ -1291,52 +1128,6 @@ $cases = [
|
|||||||
assertPageCreation($phpb_db->rows('pages')[0]['draft_data'] !== null, 'Rejected CSRF requests changed the saved draft.');
|
assertPageCreation($phpb_db->rows('pages')[0]['draft_data'] !== null, 'Rejected CSRF requests changed the saved draft.');
|
||||||
http_response_code(200);
|
http_response_code(200);
|
||||||
},
|
},
|
||||||
'settings writes roll back when a create or update fails' => function (): void {
|
|
||||||
resetPageCreationDatabase();
|
|
||||||
global $phpb_db;
|
|
||||||
$settingRepository = new \Plugi\Repositories\SettingRepository();
|
|
||||||
$phpb_db->failOnSettingWrite = 2;
|
|
||||||
|
|
||||||
assertPageCreation(
|
|
||||||
! $settingRepository->updateSettings(['first' => 'one', 'second' => 'two'])
|
|
||||||
&& $phpb_db->rows('settings') === [],
|
|
||||||
'A failed settings create reported success or retained earlier writes.'
|
|
||||||
);
|
|
||||||
|
|
||||||
resetPageCreationDatabase();
|
|
||||||
$phpb_db->query('INSERT INTO settings (setting, value, is_array) VALUES (?, ?, ?)', ['existing', 'old', 0]);
|
|
||||||
$phpb_db->settingWriteCount = 0;
|
|
||||||
$phpb_db->failOnSettingWrite = 2;
|
|
||||||
$settingRepository = new \Plugi\Repositories\SettingRepository();
|
|
||||||
$updateSucceeded = $settingRepository->updateSettings(['first' => 'one', 'existing' => 'new']);
|
|
||||||
$savedSettings = array_column($phpb_db->rows('settings'), 'value', 'setting');
|
|
||||||
assertPageCreation(
|
|
||||||
! $updateSucceeded && $savedSettings === ['existing' => 'old'],
|
|
||||||
'A failed settings update reported success or retained earlier writes.'
|
|
||||||
);
|
|
||||||
|
|
||||||
resetPageCreationDatabase();
|
|
||||||
$settingRepository = new \Plugi\Repositories\SettingRepository();
|
|
||||||
assertPageCreation(
|
|
||||||
$settingRepository->updateSettings(['first' => 'one', 'second' => ['two', 'three']])
|
|
||||||
&& array_column($phpb_db->rows('settings'), 'value', 'setting') === ['first' => 'one', 'second' => 'two,three'],
|
|
||||||
'Successful settings writes were not committed.'
|
|
||||||
);
|
|
||||||
},
|
|
||||||
'cached public pages require a currently resolved route' => function (): void {
|
|
||||||
resetPageCreationDatabase();
|
|
||||||
$translation = new PageTranslation();
|
|
||||||
$translation->locale = 'en';
|
|
||||||
$translation->route = '/new-page';
|
|
||||||
|
|
||||||
[$handled, $html] = runPageCreationPublicRequest($translation, [], false, '', '<p>cached page</p>');
|
|
||||||
assertPageCreation($handled && $html === '<p>cached page</p>', 'An active route did not serve its cached response.');
|
|
||||||
assertPageCreation(count(PageCreationTestCache::$cacheReads) === 1, 'An active route did not check its cache.');
|
|
||||||
|
|
||||||
[$handled, $html] = runPageCreationPublicRequest(null, [], false, '', '<p>cached disabled route</p>');
|
|
||||||
assertPageCreation(! $handled && $html === '', 'A cached response was served after the router rejected the route.');
|
|
||||||
assertPageCreation(PageCreationTestCache::$cacheReads === [], 'A rejected route accessed the page cache.');
|
|
||||||
},
|
|
||||||
'public requests show drafts only for authenticated session-bound preview tokens' => function (): void {
|
'public requests show drafts only for authenticated session-bound preview tokens' => function (): void {
|
||||||
resetPageCreationDatabase();
|
resetPageCreationDatabase();
|
||||||
$repository = new PageRepository();
|
$repository = new PageRepository();
|
||||||
@@ -1352,14 +1143,13 @@ $cases = [
|
|||||||
$repository->updatePageDraftData($page, $draftData);
|
$repository->updatePageDraftData($page, $draftData);
|
||||||
$translation = new PageTranslation();
|
$translation = new PageTranslation();
|
||||||
$translation->page_id = $pageId;
|
$translation->page_id = $pageId;
|
||||||
$translation->locale = 'de';
|
$translation->locale = 'en';
|
||||||
$translation->route = '/new-page';
|
$translation->route = '/new-page';
|
||||||
$resolvedPreviewRoute = (new DatabasePageRouter())->resolve('/new-page?previewToken=valid-token');
|
$resolvedPreviewRoute = (new DatabasePageRouter())->resolve('/new-page?previewToken=valid-token');
|
||||||
assertPageCreation($resolvedPreviewRoute->route === '/new-page', 'The public router treated preview query parameters as part of the page route.');
|
assertPageCreation($resolvedPreviewRoute->route === '/new-page', 'The public router treated preview query parameters as part of the page route.');
|
||||||
|
|
||||||
[$handled, $html, $pageBuilder] = runPageCreationPublicRequest($translation, ['previewToken' => 'valid-token'], true, 'valid-token');
|
[$handled, $html, $pageBuilder] = runPageCreationPublicRequest($translation, ['previewToken' => 'valid-token'], true, 'valid-token');
|
||||||
assertPageCreation($handled === true, 'An authenticated preview request was not handled.');
|
assertPageCreation($handled === true, 'An authenticated preview request was not handled.');
|
||||||
assertPageCreation($pageBuilder->renderedLanguage === 'de' && $GLOBALS['phpb_request_language'] === 'de', 'A resolved translation locale did not control page rendering and request language state.');
|
|
||||||
assertPageCreation($pageBuilder->renderedData === $draftData, 'An authenticated session-bound preview did not render the saved draft.');
|
assertPageCreation($pageBuilder->renderedData === $draftData, 'An authenticated session-bound preview did not render the saved draft.');
|
||||||
assertPageCreation(str_contains(strtolower($html), '<!doctype html>'), 'Draft preview did not preserve the page doctype.');
|
assertPageCreation(str_contains(strtolower($html), '<!doctype html>'), 'Draft preview did not preserve the page doctype.');
|
||||||
assertPageCreation(str_contains($html, 'Theme layout'), 'Draft preview did not preserve the full themed page.');
|
assertPageCreation(str_contains($html, 'Theme layout'), 'Draft preview did not preserve the full themed page.');
|
||||||
@@ -1466,7 +1256,7 @@ $cases = [
|
|||||||
$repository->create(pageCreationPayload());
|
$repository->create(pageCreationPayload());
|
||||||
global $phpb_db;
|
global $phpb_db;
|
||||||
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
|
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
|
||||||
$phpb_db->failOnTranslationUpdate = true;
|
$phpb_db->failOnTranslationInsert = 4;
|
||||||
|
|
||||||
$result = $repository->update($page, pageCreationPayload([
|
$result = $repository->update($page, pageCreationPayload([
|
||||||
'name' => 'Changed page',
|
'name' => 'Changed page',
|
||||||
|
|||||||
@@ -7,17 +7,6 @@ $pageTranslationServiceConfig = [
|
|||||||
'language' => 'en',
|
'language' => 'en',
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
$pageTranslationServiceSettings = ['languages' => ['en', 'fr']];
|
|
||||||
$pageTranslationServiceUrl = '/page';
|
|
||||||
|
|
||||||
class PageTranslationTestSettings
|
|
||||||
{
|
|
||||||
public static function get(string $key): mixed
|
|
||||||
{
|
|
||||||
global $pageTranslationServiceSettings;
|
|
||||||
return $pageTranslationServiceSettings[$key] ?? null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function phpb_config(?string $key = null): mixed
|
function phpb_config(?string $key = null): mixed
|
||||||
{
|
{
|
||||||
@@ -33,66 +22,10 @@ function phpb_config(?string $key = null): mixed
|
|||||||
}
|
}
|
||||||
$value = $value[$segment];
|
$value = $value[$segment];
|
||||||
}
|
}
|
||||||
|
|
||||||
return $value;
|
return $value;
|
||||||
}
|
}
|
||||||
|
|
||||||
function phpb_trans(string $key): mixed
|
|
||||||
{
|
|
||||||
$languages = ['en' => 'English', 'fr' => 'French'];
|
|
||||||
return $key === 'languages' ? $languages : ($languages[substr($key, 10)] ?? '');
|
|
||||||
}
|
|
||||||
|
|
||||||
function phpb_instance(string $name, array $params = []): mixed
|
|
||||||
{
|
|
||||||
return PageTranslationTestSettings::class;
|
|
||||||
}
|
|
||||||
|
|
||||||
function phpb_current_relative_url(bool $removeParameters = false): string
|
|
||||||
{
|
|
||||||
global $pageTranslationServiceUrl;
|
|
||||||
return $pageTranslationServiceUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
require_once __DIR__ . '/../src/Core/helpers.php';
|
|
||||||
require_once __DIR__ . '/../src/Contracts/SettingRepositoryContract.php';
|
|
||||||
require_once __DIR__ . '/../src/Repositories/BaseRepository.php';
|
|
||||||
require_once __DIR__ . '/../src/Repositories/SettingRepository.php';
|
|
||||||
require_once __DIR__ . '/../src/Contracts/SettingContract.php';
|
|
||||||
require_once __DIR__ . '/../src/Setting.php';
|
|
||||||
require_once __DIR__ . '/../src/Plugi.php';
|
|
||||||
|
|
||||||
class PageTranslationTestSettingRepository extends Plugi\Repositories\SettingRepository
|
|
||||||
{
|
|
||||||
public array $saved = [];
|
|
||||||
|
|
||||||
public function __construct()
|
|
||||||
{
|
|
||||||
$this->db = new class {
|
|
||||||
public function transaction(callable $callback): mixed
|
|
||||||
{
|
|
||||||
return $callback();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
public function findWhere($column, $value): array
|
|
||||||
{
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function create(array $data): object
|
|
||||||
{
|
|
||||||
$this->saved[$data['setting']] = $data;
|
|
||||||
return new stdClass();
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function update($instance, array $data): bool
|
|
||||||
{
|
|
||||||
$this->saved[$data['setting']] = $data;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertPageTranslationService(bool $condition, string $message): void
|
function assertPageTranslationService(bool $condition, string $message): void
|
||||||
{
|
{
|
||||||
if (! $condition) {
|
if (! $condition) {
|
||||||
@@ -148,108 +81,6 @@ $cases = [
|
|||||||
'Locale validation should accept active languages only and must not apply fallback.'
|
'Locale validation should accept active languages only and must not apply fallback.'
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
'routes normalize slash variants and static-segment case' => function () use ($service): void {
|
|
||||||
assertPageTranslationService(
|
|
||||||
$service->normalizeRoute('/About//US/') === '/about/us'
|
|
||||||
&& $service->normalizeRoute('/About/{ProductID}/') === '/about/{ProductID}'
|
|
||||||
&& $service->getRouteKey('/ABOUT/{productid}') === $service->getRouteKey('/about/{ProductID}'),
|
|
||||||
'Route normalization should canonicalize slashes and case without changing parameter names.'
|
|
||||||
);
|
|
||||||
},
|
|
||||||
'generated route prefix follows the default-language convention' => function () use ($service): void {
|
|
||||||
assertPageTranslationService(
|
|
||||||
$service->getGeneratedRoutePrefix('en', true) === ''
|
|
||||||
&& $service->getGeneratedRoutePrefix('de', false) === '/de',
|
|
||||||
'Generated routes should leave the default locale unprefixed and prefix later locales.'
|
|
||||||
);
|
|
||||||
},
|
|
||||||
'matched page locale takes precedence over URL inference' => function (): void {
|
|
||||||
global $pageTranslationServiceUrl, $phpb_request_language;
|
|
||||||
$pageTranslationServiceUrl = '/page';
|
|
||||||
$phpb_request_language = 'fr';
|
|
||||||
|
|
||||||
assertPageTranslationService(
|
|
||||||
phpb_current_language() === 'fr',
|
|
||||||
'The matched translation locale should be authoritative on resolved page requests.'
|
|
||||||
);
|
|
||||||
unset($GLOBALS['phpb_request_language']);
|
|
||||||
},
|
|
||||||
'unresolved requests retain URL and configured-default fallback' => function (): void {
|
|
||||||
global $pageTranslationServiceUrl, $pageTranslationServiceConfig, $phpb_request_language;
|
|
||||||
unset($GLOBALS['phpb_request_language']);
|
|
||||||
$pageTranslationServiceConfig['general']['language'] = 'en';
|
|
||||||
$pageTranslationServiceUrl = '/fr/page';
|
|
||||||
assertPageTranslationService(
|
|
||||||
phpb_current_language() === 'fr',
|
|
||||||
'An unresolved locale-prefixed URL should retain URL-based language detection.'
|
|
||||||
);
|
|
||||||
|
|
||||||
$pageTranslationServiceUrl = '/page';
|
|
||||||
assertPageTranslationService(
|
|
||||||
phpb_current_language() === 'en',
|
|
||||||
'An unresolved URL without a locale prefix should fall back to the configured default.'
|
|
||||||
);
|
|
||||||
},
|
|
||||||
'default-language settings reject a disabled locale' => function (): void {
|
|
||||||
$settingRepository = new PageTranslationTestSettingRepository();
|
|
||||||
|
|
||||||
assertPageTranslationService(
|
|
||||||
! $settingRepository->updateSettings([
|
|
||||||
'languages' => ['en'],
|
|
||||||
'default_language' => 'fr',
|
|
||||||
]) && $settingRepository->saved === [],
|
|
||||||
'A default locale must be among enabled languages and invalid settings must not be persisted.'
|
|
||||||
);
|
|
||||||
},
|
|
||||||
'default-language settings accept an enabled locale' => function (): void {
|
|
||||||
$settingRepository = new PageTranslationTestSettingRepository();
|
|
||||||
|
|
||||||
assertPageTranslationService(
|
|
||||||
$settingRepository->updateSettings([
|
|
||||||
'languages' => ['en', 'fr'],
|
|
||||||
'default_language' => 'fr',
|
|
||||||
]) && ($settingRepository->saved['default_language']['value'] ?? null) === 'fr',
|
|
||||||
'A selected default locale should be saved when it is enabled.'
|
|
||||||
);
|
|
||||||
},
|
|
||||||
'legacy language input cannot disable an existing default' => function (): void {
|
|
||||||
global $pageTranslationServiceSettings;
|
|
||||||
$pageTranslationServiceSettings['default_language'] = 'en';
|
|
||||||
$settingRepository = new PageTranslationTestSettingRepository();
|
|
||||||
|
|
||||||
assertPageTranslationService(
|
|
||||||
! $settingRepository->updateSettings([
|
|
||||||
'languages' => ['fr'],
|
|
||||||
'admin_language' => 'fr',
|
|
||||||
]) && $settingRepository->saved === [],
|
|
||||||
'Legacy language input must not allow disabling the saved site default without replacement.'
|
|
||||||
);
|
|
||||||
unset($pageTranslationServiceSettings['default_language']);
|
|
||||||
},
|
|
||||||
'new default language takes precedence over the legacy setting' => function (): void {
|
|
||||||
$settings = new ReflectionProperty(Plugi\Setting::class, 'settings');
|
|
||||||
$settings->setValue(null, ['default_language' => 'fr', 'admin_language' => 'en']);
|
|
||||||
$GLOBALS['phpb_config'] = ['general' => ['language' => 'en'], 'theme' => []];
|
|
||||||
|
|
||||||
(new Plugi\Plugi([]))->hydrateConfig();
|
|
||||||
|
|
||||||
assertPageTranslationService(
|
|
||||||
$GLOBALS['phpb_config']['general']['language'] === 'fr',
|
|
||||||
'The distinct default-language setting should take precedence over the legacy setting.'
|
|
||||||
);
|
|
||||||
},
|
|
||||||
'legacy admin language remains a compatibility fallback' => function (): void {
|
|
||||||
$settings = new ReflectionProperty(Plugi\Setting::class, 'settings');
|
|
||||||
$settings->setValue(null, ['admin_language' => 'fr']);
|
|
||||||
$GLOBALS['phpb_config'] = ['general' => ['language' => 'en'], 'theme' => []];
|
|
||||||
|
|
||||||
(new Plugi\Plugi([]))->hydrateConfig();
|
|
||||||
|
|
||||||
assertPageTranslationService(
|
|
||||||
$GLOBALS['phpb_config']['general']['language'] === 'fr',
|
|
||||||
'Installations without a saved default-language setting should continue using admin_language.'
|
|
||||||
);
|
|
||||||
},
|
|
||||||
'translation values follow the same fallback order and preserve empty strings' => function () use ($service): void {
|
'translation values follow the same fallback order and preserve empty strings' => function () use ($service): void {
|
||||||
global $pageTranslationServiceConfig;
|
global $pageTranslationServiceConfig;
|
||||||
$pageTranslationServiceConfig['general']['language'] = 'fr';
|
$pageTranslationServiceConfig['general']['language'] = 'fr';
|
||||||
|
|||||||
@@ -1,64 +0,0 @@
|
|||||||
import assert from 'node:assert/strict';
|
|
||||||
import test from 'node:test';
|
|
||||||
import { bindLanguageSelector } from '../src/Modules/GrapesJS/resources/assets/js/language-selection.js';
|
|
||||||
|
|
||||||
function createHarness(switchSuccess) {
|
|
||||||
let changeHandler;
|
|
||||||
const radios = [
|
|
||||||
{ value: 'en', checked: false },
|
|
||||||
{ value: 'de', checked: true },
|
|
||||||
];
|
|
||||||
const selector = {
|
|
||||||
querySelectorAll(query) {
|
|
||||||
assert.equal(query, 'input[type="radio"]');
|
|
||||||
return radios;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
radios[1].closest = function(query) {
|
|
||||||
if (query === "#language-selector input[type='radio']") return this;
|
|
||||||
if (query === '#language-selector') return selector;
|
|
||||||
throw new Error(`Unexpected selector: ${query}`);
|
|
||||||
};
|
|
||||||
const document = {
|
|
||||||
addEventListener(eventName, handler) {
|
|
||||||
assert.equal(eventName, 'change');
|
|
||||||
changeHandler = handler;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const calls = { switched: [], activated: [] };
|
|
||||||
const window = {
|
|
||||||
currentLanguage: 'en',
|
|
||||||
switchLanguage(language, callback) {
|
|
||||||
calls.switched.push(language);
|
|
||||||
callback(switchSuccess);
|
|
||||||
},
|
|
||||||
activateLanguage(language) {
|
|
||||||
calls.activated.push(language);
|
|
||||||
this.currentLanguage = language;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
bindLanguageSelector(document, window);
|
|
||||||
changeHandler({ target: radios[1] });
|
|
||||||
|
|
||||||
return { calls, radios, window };
|
|
||||||
}
|
|
||||||
|
|
||||||
test('language changes activate the selected language when switching succeeds', () => {
|
|
||||||
const { calls, radios, window } = createHarness(true);
|
|
||||||
|
|
||||||
assert.deepEqual(calls.switched, ['de']);
|
|
||||||
assert.deepEqual(calls.activated, ['de']);
|
|
||||||
assert.equal(window.currentLanguage, 'de');
|
|
||||||
assert.equal(radios[1].checked, true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('language changes restore the current radio when switching fails', () => {
|
|
||||||
const { calls, radios, window } = createHarness(false);
|
|
||||||
|
|
||||||
assert.deepEqual(calls.switched, ['de']);
|
|
||||||
assert.deepEqual(calls.activated, []);
|
|
||||||
assert.equal(window.currentLanguage, 'en');
|
|
||||||
assert.equal(radios[0].checked, true);
|
|
||||||
assert.equal(radios[1].checked, false);
|
|
||||||
});
|
|
||||||
@@ -19,12 +19,8 @@ test('viewport changes select a device without changing project data or invoking
|
|||||||
saveCalls++;
|
saveCalls++;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
let checkedRadio;
|
|
||||||
const selector = {
|
const selector = {
|
||||||
querySelector(selector) {
|
value: 'Desktop',
|
||||||
assert.equal(selector, 'input[type="radio"]:checked');
|
|
||||||
return checkedRadio;
|
|
||||||
},
|
|
||||||
addEventListener(eventName, handler) {
|
addEventListener(eventName, handler) {
|
||||||
assert.equal(eventName, 'change');
|
assert.equal(eventName, 'change');
|
||||||
changeHandler = handler;
|
changeHandler = handler;
|
||||||
@@ -33,7 +29,7 @@ test('viewport changes select a device without changing project data or invoking
|
|||||||
|
|
||||||
bindViewportSelector(editor, selector);
|
bindViewportSelector(editor, selector);
|
||||||
for (const device of ['Desktop', 'Tablet', 'Mobile']) {
|
for (const device of ['Desktop', 'Tablet', 'Mobile']) {
|
||||||
checkedRadio = { value: device };
|
selector.value = device;
|
||||||
changeHandler();
|
changeHandler();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user