Compare commits

..
57 Commits
Author SHA1 Message Date
deepDiverPaul f01cad090c Merge pull request 'Feature/ext-blog' (#14) from feature/ext-blog into main
Reviewed-on: #14
2026-12-02 10:22:46 +00:00
deepDiverPaul 6f0e39b5f5 feat(ext-blog): Add syntax highlighting for code blocks
Added language-specific syntax highlighting support to the markdown editor and preview. New code-highlighter assets are registered for public pages and admin headers. The PostContentRenderer detects language identifiers in code fences to apply appropriate CSS classes for highlighting. Tests verify the highlighting works correctly and unsafe content is escaped properly.
2026-12-02 10:20:36 +00:00
deepDiverPaul 745f33f17d feat(ext-blog): Add markdown editor bundling and dependencies 2026-12-02 10:20:36 +00:00
deepDiverPaul 2d4b196b04 feat(ext-blog): Add rich Markdown editor for blog posts
Replace the plain textarea with a CodeMirror-based editor supporting syntax highlighting, formatting toolbar (bold, italic, lists, code blocks), and a live preview toggle. Update PostContentRenderer to handle new Markdown syntax (blockquotes, fenced code blocks). Add a preview endpoint for rendering content without saving.
2026-12-02 10:20:36 +00:00
deepDiverPaul e97d96c1f5 feat(ext-blog): Add Markdown support and featured images to Plugi Blog Extension
Updated README.md to document Markdown rendering and image authoring capabilities. Added PostContentRenderer class for safe Markdown parsing with XSS protection. Updated PostsRepository to fetch and resolve featured image data from the uploads table. Added UI controls in EditPost.php for selecting images and inserting inline Markdown. Updated views to display featured images on post cards and detail pages.
2026-12-02 10:20:36 +00:00
deepDiverPaul 32582e9279 feat(ext-blog): Add pagination and search to blog post listing
The PostsRepository now includes methods for fetching paginated and searched posts. The admin and public views include search forms, pagination controls, and display total counts instead of just post counts. Tests verify the new functionality including special character search handling and pagination limits.
2026-12-02 10:20:36 +00:00
deepDiverPaul f35645132e Add blog extension 2026-12-02 10:20:36 +00:00
deepDiverPaul 47214e0bbc Merge pull request 'fix(security): Add security hardening and CSRF protection.' (#13) from security into main
Reviewed-on: #13
2026-12-02 10:20:04 +00:00
deepDiverPaul b44b1bfc72 fix(security): Add security hardening and CSRF protection.
Added .htaccess rules to deny access to hidden files. Escaped JSON output in views to prevent XSS attacks. Converted delete links and forms to use POST with CSRF tokens. Enforced POST method on sensitive routes. Added tests to verify these security controls.
2026-12-02 11:07:41 +01:00
deepDiverPaul 6f02b0bc8d Merge pull request 'Extensions' (#12) from feat-extensions-add-extension-enable-dis into main
Reviewed-on: #12
2026-12-01 10:05:05 +00:00
deepDiverPaul 2e42cd00d2 feat(extensions): Add extension enable/disable toggle and loading logic
The settings view now renders a toggle switch for each extension to enable or disable it. The `Plugi` class includes a new method to load extensions based on their enabled state. Tests verify the activation logic and settings persistence.
2026-12-01 10:28:46 +01:00
deepDiverPaul 515e4cac1f feat(ext-tracking): Add tracking extension for HTML/JS snippets
Adds a new extension allowing injection of custom code into the page head. Includes an admin interface for saving snippets, secure save routes with CSRF protection, and tests verifying the functionality. Also updates core Extensions.php to support callable HTML blocks for lazy evaluation.
2026-11-30 22:51:03 +01:00
deepDiverPaul cc9c03e580 Merge pull request 'feat(multi-language): Add multi-language support and routing updates' (#11) from feature/multi-language into main
Reviewed-on: #11
2026-11-30 18:48:52 +00:00
deepDiverPaul 6a4f7cac5f feat(multi-language): Add multi-language support and routing updates
Add configuration for multiple languages in the Website Manager
2026-11-30 19:47:55 +01:00
deepDiverPaul 464a50748f Merge pull request 'Dev' (#10) from dev into main
Reviewed-on: #10
2026-11-30 15:52:01 +00:00
deepDiverPaul 68b8ff7fb3 page switching in editor 2026-11-30 16:51:16 +01:00
deepDiverPaul ba1007ff5d replace the PageBuilder language and viewport dropdowns with accessible
radio button groups
2026-11-30 16:51:15 +01:00
deepDiverPaul c80f28de1d improve publishing 2026-11-30 16:51:15 +01:00
deepDiverPaul 59924675fd update phosphor icons 2026-11-30 16:51:15 +01:00
deepDiverPaul c0e43106e1 add draft/publishing workflow 2026-11-30 16:51:15 +01:00
deepDiverPaul 25030638a4 Implemented: editor uploads are constrained to safe image files inside
the upload tree, and public form submissions are
size-bounded and rate-limited
2026-11-30 16:51:15 +01:00
deepDiverPaul e1767dcd2c media-library search, MIME-type and virtual-folder filters, persisted
folder and alt-text editing, and safe defaults for legacy uploads
2026-11-30 16:51:14 +01:00
deepDiverPaul 1ec2d9c8e1 add dashboard 2026-11-30 16:51:14 +01:00
deepDiverPaul 6308f5e733 Merge pull request 'Dev' (#9) from dev into main
Reviewed-on: #9
2026-11-27 16:25:00 +00:00
deepDiverPaul 2513a51fa4 update docs 2026-11-27 16:24:48 +00:00
deepDiverPaul 3dc7c25dc2 Update installation procedure 2026-11-27 16:24:48 +00:00
deepDiverPaul b8d9ff0b35 Update .gitignore 2026-11-27 16:24:48 +00:00
deepDiverPaul c27897dfa0 Merge pull request 'Dev' (#8) from dev into main
Reviewed-on: #8
2026-11-26 09:04:24 +00:00
deepDiverPaul 017f8f0434 add page builder viewport selection 2026-11-26 08:14:11 +01:00
deepDiverPaul fea53afc72 normalize generated page slugs to lowercase 2026-11-26 08:09:09 +01:00
deepDiverPaul 93fab6567d Merge branch 'dev' into feature/quality-checks 2026-11-26 08:07:20 +01:00
deepDiverPaul 21a33e53aa add primary key and auto-increment schema support
Configure the page translations table with an `id` primary key and auto-increment column, and detect and apply these constraints in database schema updates. Add persistence coverage for English and German homepage routes.
2026-11-26 07:59:07 +01:00
deepDiverPaul cb51db9048 add site quality audits and pagebuilder viewport selection
Add published-page accessibility and link checks with localized reports, and add responsive viewport controls to the page builder. Detect schema drift beyond matching hashes and apply lowercase definitions when creating or updating tables. Refresh generated admin, page-builder, and website-manager assets, and add coverage for quality checks, viewport selection, and schema migrations.
2026-11-25 21:48:45 +01:00
deepDiverPaul ed8ae3200b refresh theme-one starter blocks and layout
Redesign the master layout and content blocks with responsive styling, accessible navigation, and configurable CTA and quote sections. Add about-me, embedded-code, and FAQ blocks, and update the generated theme assets. Replace Alpine-based locale handling with vanilla JavaScript for locale flags and gallery lightboxes, and remove Alpine and DaisyUI dependencies.
2026-11-25 17:50:12 +01:00
deepDiverPaul 102fbc9464 improve form submission handling and frontend assets
Replace Alpine form bindings with accessible vanilla JavaScript submission states and unique field IDs. Add the bundled frontend script and Rolldown build configuration, update the generated stylesheet, and extend submission handler tests.
2026-11-25 15:56:26 +01:00
deepDiverPaul a07e3ad8d9 fix localized page management and builder synchronization
Validate locales and route uniqueness, report page deletion failures, and keep translation CRUD and route caches consistent. Show translation completeness in page settings and listings, and preserve locale-specific block data while synchronizing shared structure. Add translation service and page builder synchronization tests.
2026-11-25 14:53:35 +01:00
deepDiverPaul 9d192c2141 refresh admin interface layouts
Redesign authentication and website manager views with responsive layouts, clearer navigation, and accessibility improvements. Refresh page, menu, file, system information, settings, overview, welcome, page settings, and block thumbnail screens. Add the shared Admin stylesheet and Plugi theme, update the build configuration, and regenerate the admin CSS.
2026-11-25 12:02:54 +01:00
deepDiverPaul 151ac9df4c refresh form extension admin interface
Improve form editing, settings, submission lists, and navigation with responsive layouts and accessibility enhancements. Update the form wrapper block view and regenerate the extension stylesheet. Ignore .agents and skills-lock.json.
2026-11-25 09:59:51 +01:00
deepDiverPaul ca7ee32091 refresh admin interface layouts
Redesign authentication and website manager layouts and views for a responsive, accessible interface. Update page, menu, file, info, and settings screens, and refresh the generated WebsiteManager stylesheet.
2026-11-25 08:01:50 +01:00
deepDiverPaul 82086c725f Merge remote-tracking branch 'origin/dev' into dev 2026-11-24 22:45:38 +01:00
deepDiverPaul e21cc1bf4c Merge pull request 'update .gitignore and LICENSE' (#6) from feature/docs into main
Reviewed-on: #6
2026-11-24 21:43:41 +00:00
deepDiverPaul bea51b098a update .gitignore and LICENSE
Add docs directory to .gitignore and update copyright year to 2026 in LICENSE.
2026-11-24 21:43:29 +00:00
deepDiverPaul f78a63cf5b Merge remote-tracking branch 'origin/dev' into dev 2026-11-24 22:42:37 +01:00
deepDiverPaul cbce2b04f4 Merge pull request 'fix page creation validation and persistence' (#5) from dev into main
Reviewed-on: #5
2026-11-24 21:42:27 +00:00
deepDiverPaul 15cd385126 fix page creation validation and persistence
Validate required page fields and localized translations, detect route collisions, and save pages and translations atomically with rollback on failure. Report creation errors while preserving submitted form values, safely encode Alpine.js values, and add English and German error messages. Return null for failed inserts and add page persistence tests.
2026-11-24 21:42:14 +00:00
deepDiverPaul 8251f883e6 fix page creation validation and persistence
Validate required page fields and localized translations, detect route collisions, and save pages and translations atomically with rollback on failure. Report creation errors while preserving submitted form values, safely encode Alpine.js values, and add English and German error messages. Return null for failed inserts and add page persistence tests.
2026-11-24 22:40:52 +01:00
deepDiverPaul 956eca181f Merge pull request 'Feature/languages' (#4) from feature/languages into main
Reviewed-on: #4
2026-11-24 17:53:29 +00:00
deepDiverPaul d5597b045f add configurable form finishers and webhook delivery
Expose finisher settings through the editor registry and build the action editor dynamically. Add configurable admin email recipients and subjects, and introduce a webhook finisher with validated request options and JSON submission payloads.

Expand submission handler tests to cover editor configuration, email overrides, webhook validation, HTTP responses, and submission outcomes.
2026-11-24 18:51:20 +01:00
deepDiverPaul dfe1e40e58 add configurable SMTP mail delivery
Add a core SMTP mailer with configurable transport, authentication, and sender settings. Route form confirmation and admin notifications through the core mailer, and add tests for SMTP delivery, failure cases, and finisher integration.
2026-11-24 11:48:31 +01:00
deepDiverPaul c507618b90 add form submission handling and confirmation emails
Validate form submissions and action configuration, execute finishers with submission context, and return JSON success or error responses. Add configurable confirmation emails to submitters and report failed submissions in the form UI.

Harden database and admin email finishers, and add submission handler and confirmation email checks.
2026-11-24 11:26:37 +01:00
deepDiverPaul 80e60d6823 translate form extension UI to English
Replace German labels, prompts, validation messages, and submission text across the form admin and block views with English.
Remove redundant LICENSE files from the form and sitemap extensions.
2026-11-24 10:56:44 +01:00
deepDiverPaul ef692943f6 add Swedish language support
Add Swedish translations for the admin and page builder, and include Swedish in the language names and admin language selector.
2026-11-24 10:40:19 +01:00
deepDiverPaul 67c94b6a5d fix admin language options
Remove the Spanish and Dutch translation files and limit the admin language selector to German and English.
2026-11-24 10:34:41 +01:00
deepDiverPaul 3160f377d1 Merge pull request 'security: add CSRF protection and harden core handling' (#3) from security into main
Reviewed-on: #3
2026-11-24 09:26:35 +00:00
deepDiverPaul 2b73242d04 security: add CSRF protection and harden core handling
Add CSRF token validation and include tokens in authentication, website manager, and GrapesJS forms and requests. Harden login with password hash verification and session ID regeneration, validate database identifiers and charset, and secure upload MIME detection and filename generation.

Update nullable type declarations and PHP syntax across core contracts and modules, switch the Docker image to PHP 8.4, and move the theme script asset to the end of the page. Refresh the PageBuilderBody distribution assets.
2026-11-24 09:26:15 +00:00
deepDiverPaul d6c06b82d5 Merge pull request 'update README banner URL to Gitea mirror' (#2) from feature/docs into main
Reviewed-on: #2
2026-11-23 17:05:11 +00:00
deepDiverPaul 207bcdeaf3 update README banner URL to Gitea mirror
Replace the GitHub-hosted banner image URL with the Gitea instance URL.
2026-11-23 18:04:57 +01:00
238 changed files with 294969 additions and 37719 deletions
+24 -12
View File
@@ -1,12 +1,24 @@
STAGE = production
BASE_URL = http://localhost:63000
database_driver = mysql
database_host = mysql
database_database = plugi
database_username = plugi
database_password = plugi
database_charset = utf8
database_collation = utf8_unicode_ci
database_prefix =
USERNAME = admin
PASSWORD = admin
STAGE=production
BASE_URL=http://localhost:63000
DATABASE_DRIVER=mysql
DATABASE_HOST=mysql
DATABASE_DATABASE=plugi
DATABASE_USERNAME=plugi
DATABASE_PASSWORD=change-me
DATABASE_CHARSET=utf8mb4
DATABASE_PREFIX=
MYSQL_ROOT_PASSWORD=change-me-root
USERNAME=admin
PASSWORD=
PASSWORD_HASH=
MAIL_HOST=
MAIL_PORT=587
MAIL_ENCRYPTION=tls
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_FROM_ADDRESS=
MAIL_FROM_NAME=
MAIL_TIMEOUT=10
+8 -1
View File
@@ -12,10 +12,15 @@ dist-ssr
*.local
.env
/config.php
/docs
cache
uploads
uploads/*
!uploads/.htaccess
extensions/dev_*
.agents
skills-lock.json
# Editor directories and files
.vscode/*
@@ -28,3 +33,5 @@ extensions/dev_*
*.njsproj
*.sln
*.sw?
.DS_Store
+6
View File
@@ -1,5 +1,10 @@
<FilesMatch "^\.">
Require all denied
</FilesMatch>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule (^|/)\.(?!well-known/) - [F,L]
# Redirect non-www. to www. (except when on a subdomain)
# RewriteCond %{HTTP_HOST} !^www\.
@@ -27,6 +32,7 @@
RewriteRule ^themes/([^/]+)/public/(.*)$ themes/$1/public/$2 [L]
# Allow direct access to uploaded files with URL format: /uploads/{filepath;,}
RewriteRule ^uploads/.*\.(?:php[0-9]*|phtml|phar)(?:/|$) - [F,NC]
RewriteRule ^uploads/(.*)$ uploads/$1 [L]
# Rewrite all remaining requests to index.php
+2 -2
View File
@@ -2,9 +2,9 @@ FROM php:8.4-apache-bookworm
WORKDIR "/var/www/html"
RUN apt-get update; \
docker-php-ext-install pdo pdo_mysql; \
apt-get -y --no-install-recommends install \
git \
php8.4-mysql; \
libonig-dev; \
docker-php-ext-install mbstring pdo_mysql; \
apt-get clean; \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2023 Paul Spenke
Copyright (c) 2026 Paul Spenke
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+22 -15
View File
@@ -1,25 +1,32 @@
![Plugi](https://github.com/deepDiverPaul/plugi/blob/0357cc90d603ff3c33e68d5e5de160abce7315c0/plugi-core/dist/images/plugi-banner.png)
![Plugi](https://gitea.spenke-nordic.com/deepDiverPaul/plugi/raw/branch/main/plugi-core/dist/images/plugi-banner.png)
> A fork of [PHPagebuilder](https://github.com/HansSchouten/PHPagebuilder) by [Hans Schouten](https://github.com/HansSchouten).
> Still a work-in-progress
Plugi is a website boilerplate with a drag-and-drop page builder.
This boilerplate defines the project structure for quickly creating a website that can be managed with a drag and drop
pagebuilder.
## Quick installation
## Installation
1. Use PHP 8.4 with the PDO MySQL extension and a MySQL 8 database. The supplied Docker image is based on PHP 8.4.
2. Copy `.env.dist` to `.env` and `config.dist.php` to `config.php`; set the database connection, public `BASE_URL`, and a unique admin username and password hash in `.env`.
3. Create the database and a database user, deploy the project at the web root, and make `uploads/` writable by the web server.
4. Open the site, sign in at `/admin/auth`, and follow the Website Manager database update prompt to create/update the schema.
To setup your website download the latest version of Plugi and upload it to the webroot directory of your website.
See the [Plugi documentation](https://plugi.paulspenke.com/) for the full installation guide, including manual deployment, Docker development, security, and troubleshooting.
### Edit the config file
The file `config.php` holds all the basic configuration for your project. Edit as needed. Be sure to update the
login-credentials.
## Multilingual pages
### Login
Now you should be able to log in to the admin panel by going to the `/admin` URL of your website using `admin` and
`admin` (you can change these in the config file). If you are able to login you can start building your website.
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.
Note: make sure to disable error reporting in `index.php` once your website goes into production!
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.
## Docker
Simply run `docker-compose up -d` using the supplied `docker-compose.yml`. The image uses PHP 8.2
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
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:
```sh
docker compose up --build -d
```
The app is available at `http://localhost:63000`; Adminer is bound to localhost at `http://localhost:63001`.
+66 -45
View File
@@ -9,10 +9,10 @@ return [
| General settings for configuring the PageBuilder.
|
*/
'general' => [
'language' => 'en',
'assets_url' => '/plugi-core/dist',
'uploads_url' => '/uploads'
"general" => [
"language" => "en",
"assets_url" => "/plugi-core/dist",
"uploads_url" => "/uploads",
],
/*
@@ -20,12 +20,12 @@ return [
| Storage settings
|--------------------------------------------------------------------------
|
| Database and file storage settings.
| File storage settings.
|
*/
'storage' => [
'use_database' => true,
'uploads_folder' => __DIR__ . '/uploads'
"storage" => [
"use_database" => true,
"uploads_folder" => __DIR__ . "/uploads",
],
/*
@@ -37,10 +37,10 @@ return [
| credentials configured in this setting block.
|
*/
'auth' => [
'use_login' => true,
'class' => Plugi\Modules\Auth\Auth::class,
'url' => '/admin/auth',
"auth" => [
"use_login" => true,
"class" => Plugi\Modules\Auth\Auth::class,
"url" => "/admin/auth",
],
/*
@@ -51,10 +51,10 @@ return [
| By default a basic WebsiteManager is provided for creating/editing pages.
|
*/
'website_manager' => [
'use_website_manager' => true,
'class' => Plugi\Modules\WebsiteManager\WebsiteManager::class,
'url' => '/admin'
"website_manager" => [
"use_website_manager" => true,
"class" => Plugi\Modules\WebsiteManager\WebsiteManager::class,
"url" => "/admin",
],
/*
@@ -65,8 +65,8 @@ return [
| By default a setting class is provided for accessing website settings.
|
*/
'setting' => [
'class' => Plugi\Setting::class
"setting" => [
"class" => Plugi\Setting::class,
],
/*
@@ -77,12 +77,12 @@ return [
| By default a PageBuilder is provided based on GrapesJS.
|
*/
'pagebuilder' => [
'class' => Plugi\Modules\GrapesJS\PageBuilder::class,
'url' => '/admin/pagebuilder',
'actions' => [
'back' => '/admin'
]
"pagebuilder" => [
"class" => Plugi\Modules\GrapesJS\PageBuilder::class,
"url" => "/admin/pagebuilder",
"actions" => [
"back" => "/admin?tab=pages",
],
],
/*
@@ -93,14 +93,14 @@ return [
| By default a Page class is provided with knowledge about its layout and URL.
|
*/
'page' => [
'class' => Plugi\Page::class,
'table' => 'pages',
'translation' => [
'class' => Plugi\PageTranslation::class,
'table' => 'page_translations',
'foreign_key' => 'page_id',
]
"page" => [
"class" => Plugi\Page::class,
"table" => "pages",
"translation" => [
"class" => Plugi\PageTranslation::class,
"table" => "page_translations",
"foreign_key" => "page_id",
],
],
/*
@@ -114,10 +114,10 @@ return [
| The cached html is removed if the page is saved again in the page builder.
|
*/
'cache' => [
'enabled' => false,
'folder' => __DIR__ . '/cache',
'class' => Plugi\Cache::class
"cache" => [
"enabled" => false,
"folder" => __DIR__ . "/cache",
"class" => Plugi\Cache::class,
],
/*
@@ -130,11 +130,11 @@ return [
| containing a view, model (optional) and controller (optional).
|
*/
'theme' => [
'class' => Plugi\Theme::class,
'folder' => __DIR__ . '/themes',
'folder_url' => '/themes',
'active_theme' => 'theme-one'
"theme" => [
"class" => Plugi\Theme::class,
"folder" => __DIR__ . "/themes",
"folder_url" => "/themes",
"active_theme" => "theme-one",
],
/*
@@ -145,8 +145,30 @@ return [
| Settings for resolving pages based on the current URI.
|
*/
'router' => [
'class' => Plugi\Modules\Router\DatabasePageRouter::class
"router" => [
"class" => Plugi\Modules\Router\DatabasePageRouter::class,
],
/*
|--------------------------------------------------------------------------
| Mail settings
|--------------------------------------------------------------------------
|
| Configure the SMTP server used by Plugi mail actions. Leave credentials
| blank when the server does not require authentication.
|
*/
"mail" => [
"class" => Plugi\Core\Mailer::class,
"transport" => "smtp",
"host" => $_ENV["MAIL_HOST"] ?? "",
"port" => (int) ($_ENV["MAIL_PORT"] ?? 587),
"encryption" => $_ENV["MAIL_ENCRYPTION"] ?? "tls",
"username" => $_ENV["MAIL_USERNAME"] ?? "",
"password" => $_ENV["MAIL_PASSWORD"] ?? "",
"from_address" => $_ENV["MAIL_FROM_ADDRESS"] ?? "",
"from_name" => $_ENV["MAIL_FROM_NAME"] ?? "",
"timeout" => (int) ($_ENV["MAIL_TIMEOUT"] ?? 10),
],
/*
@@ -160,6 +182,5 @@ return [
| Important: when overriding a class always extend the original class.
|
*/
'class_replacements' => [
],
"class_replacements" => [],
];
+28 -7
View File
@@ -1,3 +1,4 @@
# Development only. Do not use this Compose stack for production deployments.
services:
web:
build: .
@@ -7,7 +8,28 @@ services:
depends_on:
- mysql
ports:
- '63000:80'
- '127.0.0.1:63000:80'
environment:
STAGE: ${STAGE:-production}
BASE_URL: ${BASE_URL:-http://localhost:63000}
DATABASE_DRIVER: ${DATABASE_DRIVER:-mysql}
DATABASE_HOST: ${DATABASE_HOST:-mysql}
DATABASE_DATABASE: ${DATABASE_DATABASE:-plugi}
DATABASE_USERNAME: ${DATABASE_USERNAME:-plugi}
DATABASE_PASSWORD: ${DATABASE_PASSWORD:-change-me}
DATABASE_CHARSET: ${DATABASE_CHARSET:-utf8mb4}
DATABASE_PREFIX: ${DATABASE_PREFIX:-}
USERNAME: ${USERNAME:-admin}
PASSWORD: ${PASSWORD:-}
PASSWORD_HASH: ${PASSWORD_HASH:-}
MAIL_HOST: ${MAIL_HOST:-}
MAIL_PORT: ${MAIL_PORT:-587}
MAIL_ENCRYPTION: ${MAIL_ENCRYPTION:-tls}
MAIL_USERNAME: ${MAIL_USERNAME:-}
MAIL_PASSWORD: ${MAIL_PASSWORD:-}
MAIL_FROM_ADDRESS: ${MAIL_FROM_ADDRESS:-}
MAIL_FROM_NAME: ${MAIL_FROM_NAME:-}
MAIL_TIMEOUT: ${MAIL_TIMEOUT:-10}
links:
- mysql
networks:
@@ -15,7 +37,7 @@ services:
adminer:
image: adminer
ports:
- 63001:8080
- '127.0.0.1:63001:8080'
links:
- mysql
networks:
@@ -24,13 +46,12 @@ services:
image: "mysql:8.0"
restart: 'always'
volumes:
- '.:/application'
- db:/var/lib/mysql:cached
environment:
- MYSQL_ROOT_PASSWORD=root
- MYSQL_DATABASE=plugi
- MYSQL_USER=plugi
- MYSQL_PASSWORD=plugi
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-change-me-root}
MYSQL_DATABASE: ${DATABASE_DATABASE:-plugi}
MYSQL_USER: ${DATABASE_USERNAME:-plugi}
MYSQL_PASSWORD: ${DATABASE_PASSWORD:-change-me}
# ports:
# - '63002:3306'
networks:
+25
View File
@@ -0,0 +1,25 @@
# Plugi Blog Extension
The blog extension provides Website Manager post and category management plus two page-builder blocks. Posts are single-language; post bodies are stored as Markdown and rendered safely on request.
## Install and update the database
1. Place this directory at `extensions/plugi-ext-blog`. Plugi automatically discovers extension folders containing both `extension.php` and `config.php`.
2. Open Website Manager and apply the pending database definition update. Existing installations need this update to create or update the extension-owned post and category tables, including the optional featured-image field.
3. Add categories if useful, then create posts as drafts or publish them from the Blog section.
## Create the public pages
1. Create a regular Plugi page with the route `/blog` and add the **Published Posts** block. It lists published posts newest first; drafts are never shown.
2. Create another regular page with the route `/blog/{slug}` and add the **Blog Post** block. The core router supplies the named `slug` parameter to the block.
3. Apply the site’s normal page layout and theme to both pages. Their presentation remains controlled by the page builder and theme.
The detail block displays a not-found state for a missing, unknown, or unpublished slug. The blog blocks are not page-cached so publishing or editing content is reflected on the next request. Authors, tags, scheduling, RSS, and translated posts are not included in this release.
Keep `/blog` and `/blog/{slug}` unique among the site’s page routes.
## Authoring content and images
Write post bodies in Markdown using the syntax-highlighted source editor. Its toolbar inserts bold, italic, headings, links, unordered and ordered lists, blockquotes, horizontal rules, inline code, and fenced code blocks; the live preview uses the same server-side renderer as the public detail page. If JavaScript is unavailable, the source textarea remains usable and can still save the post. The detail page supports headings, paragraphs and line breaks, bold and italic text, inline code, links, ordered and unordered lists, blockquotes, horizontal rules, and fenced code blocks. Add a language identifier after the opening fence (for example, `php`) to enable language-specific highlighting. Bash, CSS, diff, HTML/XML, JavaScript/TypeScript, JSON, Markdown, PHP, Python, SQL, and YAML are highlighted; unlabeled blocks are auto-detected from this set, and other language labels remain plain text. Code-block contents are rendered as escaped text before highlighting. Raw HTML is displayed as text; links only render with relative URLs or `http`, `https`, and `mailto` schemes.
Choose a featured image from the existing Website Manager media library to show it on post cards and detail pages. Use the editor’s inline-image selector to insert Markdown image syntax at the body cursor; image alt text comes from the selected media item. Inline images render only with relative, `http`, or `https` sources. Unsafe link and image protocols are not rendered.
@@ -0,0 +1,61 @@
<?php
namespace Plugi\Extensions\Blog;
use InvalidArgumentException;
use Plugi\Repositories\BaseRepository;
class CategoriesRepository extends BaseRepository
{
protected $table = 'ext__blog_categories';
public function create(array $data)
{
return parent::create($this->validatedData($data));
}
public function update($instance, array $data)
{
$id = is_array($instance) ? ($instance['id'] ?? null) : ($instance->id ?? null);
if (!is_numeric($id) || (int) $id < 1 || $this->findWithId($id) === null) {
return false;
}
return parent::update(['id' => (int) $id], $this->validatedData($data, (int) $id));
}
public function getAllForAdmin(): array
{
return $this->db->select("SELECT * FROM {$this->table} ORDER BY name ASC, id ASC", []);
}
public function destroy($id)
{
if (!is_numeric($id) || (int) $id < 1) {
return false;
}
return $this->db->transaction(function () use ($id) {
return (new PostsRepository())->clearCategory((int) $id) && parent::destroy((int) $id);
});
}
private function validatedData(array $data, ?int $categoryId = null): array
{
$name = is_string($data['name'] ?? null) ? trim($data['name']) : '';
$slug = is_string($data['slug'] ?? null) ? trim($data['slug']) : '';
if ($name === '' || mb_strlen($name) > 255) {
throw new InvalidArgumentException('A category name of 1–255 characters is required.');
}
if (strlen($slug) > 191 || !preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug)) {
throw new InvalidArgumentException('Use a lowercase slug with letters, numbers, and single hyphens.');
}
foreach ($this->findWhere('slug', $slug) as $category) {
if ((int) $category['id'] !== $categoryId) {
throw new InvalidArgumentException('That category slug is already in use.');
}
}
return ['name' => $name, 'slug' => $slug];
}
}
@@ -0,0 +1,186 @@
<?php
namespace Plugi\Extensions\Blog;
class PostContentRenderer
{
// shortcut: supports basic Markdown blocks and inline syntax; use a maintained parser if authors need advanced Markdown.
public function render(string $markdown): string
{
$blocks = [];
$paragraph = [];
$listType = null;
$listItems = [];
$quote = [];
$flush = function () use (&$blocks, &$paragraph, &$listType, &$listItems, &$quote): void {
if ($paragraph !== []) {
$blocks[] = '<p>' . nl2br($this->renderInline(implode("\n", $paragraph))) . '</p>';
$paragraph = [];
}
if ($listType !== null) {
$class = $listType === 'ul' ? 'list-disc' : 'list-decimal';
$items = array_map(fn(string $item): string => '<li>' . $this->renderInline($item) . '</li>', $listItems);
$blocks[] = '<' . $listType . ' class="' . $class . ' space-y-1 pl-6">' . implode('', $items) . '</' . $listType . '>';
$listType = null;
$listItems = [];
}
if ($quote !== []) {
$blocks[] = '<blockquote class="border-l-4 border-base-300 pl-4 text-base-content/80"><p>' . nl2br($this->renderInline(implode("\n", $quote))) . '</p></blockquote>';
$quote = [];
}
};
$fence = null;
$fenceLanguage = null;
$codeLines = [];
foreach (preg_split('/\R/', $markdown) ?: [] as $line) {
if ($fence !== null) {
if (preg_match('/^ {0,3}(`{3,}|~{3,})[ \t]*$/', $line, $matches)
&& $matches[1][0] === $fence[0]
&& strlen($matches[1]) >= strlen($fence)) {
$codeClass = $fenceLanguage === null ? '' : ' class="language-' . $fenceLanguage . '"';
$blocks[] = '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code' . $codeClass . '>' . $this->escape(implode("\n", $codeLines)) . '</code></pre>';
$fence = null;
$fenceLanguage = null;
$codeLines = [];
continue;
}
$codeLines[] = $line;
continue;
}
if (preg_match('/^ {0,3}(`{3,}|~{3,})(.*)$/', $line, $matches)) {
$flush();
$fence = $matches[1];
$info = trim($matches[2]);
$fenceLanguage = preg_match('/^([A-Za-z0-9][A-Za-z0-9_+-]*)(?:[ \t]+|$)/', $info, $languageMatches)
? $languageMatches[1]
: null;
$codeLines = [];
continue;
}
if (trim($line) === '') {
$flush();
continue;
}
if (preg_match('/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*#*[ \t]*$/', $line, $matches)) {
$flush();
$level = strlen($matches[1]);
$class = [
1 => 'text-3xl font-bold tracking-tight',
2 => 'text-2xl font-bold tracking-tight',
3 => 'text-xl font-semibold',
4 => 'text-lg font-semibold',
5 => 'text-base font-semibold',
6 => 'text-sm font-semibold',
][$level];
$blocks[] = '<h' . $level . ' class="' . $class . '">' . $this->renderInline($matches[2]) . '</h' . $level . '>';
continue;
}
if (preg_match('/^ {0,3}(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})$/', $line)) {
$flush();
$blocks[] = '<hr class="my-6 border-base-300">';
continue;
}
if (preg_match('/^ {0,3}> ?(.*)$/', $line, $matches)) {
if ($paragraph !== [] || $listType !== null) {
$flush();
}
$quote[] = $matches[1];
continue;
}
if ($quote !== []) {
$flush();
}
if (preg_match('/^ {0,3}[-*+]\s+(.+)$/', $line, $matches)) {
$type = 'ul';
} elseif (preg_match('/^ {0,3}\d+[.)]\s+(.+)$/', $line, $matches)) {
$type = 'ol';
} else {
if ($listType !== null) {
$flush();
}
$paragraph[] = $line;
continue;
}
if ($paragraph !== []) {
$flush();
} elseif ($listType !== null && $listType !== $type) {
$flush();
}
$listType = $type;
$listItems[] = $matches[1];
}
$flush();
if ($fence !== null) {
$codeClass = $fenceLanguage === null ? '' : ' class="language-' . $fenceLanguage . '"';
$blocks[] = '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code' . $codeClass . '>' . $this->escape(implode("\n", $codeLines)) . '</code></pre>';
}
return implode("\n", $blocks);
}
private function renderInline(string $text): string
{
$parts = preg_split('/(`[^`\r\n]+`|!\[[^\]\r\n]*\]\([^\s)\r\n]+\)|\[[^\]\r\n]+\]\([^\s)\r\n]+\)|\*\*[^*\r\n]+\*\*|__[^_\r\n]+__|\*[^*\r\n]+\*|_[^_\r\n]+_)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE) ?: [$text];
$html = '';
foreach ($parts as $part) {
if ($part === '') {
continue;
}
if ($part[0] === '`') {
$html .= '<code>' . $this->escape(substr($part, 1, -1)) . '</code>';
} elseif (preg_match('/^!\[([^\]]*)\]\(([^)]+)\)$/', $part, $matches)) {
$altText = html_entity_decode($matches[1], ENT_QUOTES | ENT_HTML5, 'UTF-8');
$html .= $this->isSafeImageUrl($matches[2])
? '<img src="' . $this->escape($matches[2]) . '" alt="' . $this->escape($altText) . '" class="max-w-full rounded-box">'
: $this->escape($altText);
} elseif (preg_match('/^\[([^\]]+)\]\(([^)]+)\)$/', $part, $matches)) {
$html .= $this->isSafeLink($matches[2])
? '<a class="link link-hover" href="' . $this->escape($matches[2]) . '">' . $this->renderInline($matches[1]) . '</a>'
: $this->renderInline($matches[1]);
} elseif (str_starts_with($part, '**') || str_starts_with($part, '__')) {
$html .= '<strong>' . $this->renderInline(substr($part, 2, -2)) . '</strong>';
} elseif ($part[0] === '*' || $part[0] === '_') {
$html .= '<em>' . $this->renderInline(substr($part, 1, -1)) . '</em>';
} else {
$html .= $this->escape($part);
}
}
return $html;
}
private function isSafeLink(string $url): bool
{
return $this->isSafeUrl($url, ['http', 'https', 'mailto']);
}
private function isSafeImageUrl(string $url): bool
{
return $this->isSafeUrl($url, ['http', 'https']);
}
private function isSafeUrl(string $url, array $allowedSchemes): bool
{
$decodedUrl = html_entity_decode($url, ENT_QUOTES | ENT_HTML5, 'UTF-8');
if ($decodedUrl === '' || preg_match('/[\x00-\x20\x7f]/', $decodedUrl)) {
return false;
}
if (preg_match('/^([a-z][a-z0-9+.-]*):/i', $decodedUrl, $matches)) {
return in_array(strtolower($matches[1]), $allowedSchemes, true);
}
return true;
}
private function escape(string $text): string
{
return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
}
@@ -0,0 +1,217 @@
<?php
namespace Plugi\Extensions\Blog;
use DateTimeImmutable;
use InvalidArgumentException;
use Plugi\Repositories\BaseRepository;
class PostsRepository extends BaseRepository
{
public const POSTS_PER_PAGE = 10;
protected $table = 'ext__blog_posts';
public function create(array $data)
{
return parent::create($this->validatedData($data));
}
public function update($instance, array $data)
{
$id = is_array($instance) ? ($instance['id'] ?? null) : ($instance->id ?? null);
if (!is_numeric($id) || (int) $id < 1 || $this->findWithId($id) === null) {
return false;
}
return parent::update(['id' => (int) $id], $this->validatedData($data, (int) $id));
}
public function getAllForAdmin(): array
{
return $this->db->select("SELECT * FROM {$this->table} ORDER BY updated_at DESC, id DESC", []);
}
public function getPublishedForListing(): array
{
$categoriesTable = $_ENV['DATABASE_PREFIX'] . 'ext__blog_categories';
$uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads';
$posts = $this->db->select(
"SELECT posts.*, categories.name AS category_name, featured_image.public_id AS featured_image_public_id, featured_image.original_file AS featured_image_original_file, featured_image.alt_text AS featured_image_alt_text FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id LEFT JOIN {$uploadsTable} featured_image ON featured_image.public_id = posts.featured_image_id AND LOWER(featured_image.mime_type) LIKE 'image/%' WHERE posts.status = ? ORDER BY posts.published_at DESC, posts.id DESC",
['published']
);
return array_map(fn(array $post): array => $this->resolveFeaturedImage($post), $posts);
}
public function getPageForAdmin(string $search, int $page): array
{
return $this->getPostPage($search, $page, false);
}
public function getPageForListing(string $search, int $page): array
{
return $this->getPostPage($search, $page, true);
}
private function getPostPage(string $search, int $page, bool $publishedOnly): array
{
$categoriesTable = $_ENV['DATABASE_PREFIX'] . 'ext__blog_categories';
$uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads';
$from = $publishedOnly
? "FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id LEFT JOIN {$uploadsTable} featured_image ON featured_image.public_id = posts.featured_image_id AND LOWER(featured_image.mime_type) LIKE 'image/%'"
: "FROM {$this->table} posts";
$filters = [];
$parameters = [];
if ($publishedOnly) {
$filters[] = 'posts.status = ?';
$parameters[] = 'published';
}
if (trim($search) !== '') {
$filters[] = '(posts.title LIKE ? ESCAPE \'!\' OR posts.slug LIKE ? ESCAPE \'!\' OR posts.excerpt LIKE ? ESCAPE \'!\' OR posts.body LIKE ? ESCAPE \'!\')';
$pattern = '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], trim($search)) . '%';
array_push($parameters, $pattern, $pattern, $pattern, $pattern);
}
$where = $filters === [] ? '' : ' WHERE ' . implode(' AND ', $filters);
$total = $this->db->select("SELECT COUNT(*) AS total {$from}{$where}", $parameters)[0]['total'] ?? 0;
$page = min(max(1, $page), max(1, (int) ceil((int) $total / self::POSTS_PER_PAGE)));
$offset = ($page - 1) * self::POSTS_PER_PAGE;
$select = $publishedOnly
? 'SELECT posts.*, categories.name AS category_name, featured_image.public_id AS featured_image_public_id, featured_image.original_file AS featured_image_original_file, featured_image.alt_text AS featured_image_alt_text'
: 'SELECT posts.*';
$order = $publishedOnly ? 'posts.published_at DESC, posts.id DESC' : 'posts.updated_at DESC, posts.id DESC';
$posts = $this->db->select(
"{$select} {$from}{$where} ORDER BY {$order} LIMIT " . self::POSTS_PER_PAGE . " OFFSET {$offset}",
$parameters
);
if ($publishedOnly) {
$posts = array_map(fn(array $post): array => $this->resolveFeaturedImage($post), $posts);
}
return ['posts' => $posts, 'total' => (int) $total];
}
public function findPublishedBySlug(string $slug): ?array
{
$categoriesTable = $_ENV['DATABASE_PREFIX'] . 'ext__blog_categories';
$uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads';
$posts = $this->db->select(
"SELECT posts.*, categories.name AS category_name, featured_image.public_id AS featured_image_public_id, featured_image.original_file AS featured_image_original_file, featured_image.alt_text AS featured_image_alt_text FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id LEFT JOIN {$uploadsTable} featured_image ON featured_image.public_id = posts.featured_image_id AND LOWER(featured_image.mime_type) LIKE 'image/%' WHERE posts.slug = ? AND posts.status = ? LIMIT 1",
[$slug, 'published']
);
return isset($posts[0]) ? $this->resolveFeaturedImage($posts[0]) : null;
}
public function clearCategory(int $categoryId): bool
{
return $this->db->query("UPDATE {$this->table} SET category_id = NULL WHERE category_id = ?", [$categoryId]);
}
private function validatedData(array $data, ?int $postId = null): array
{
$title = is_string($data['title'] ?? null) ? trim($data['title']) : '';
$slug = is_string($data['slug'] ?? null) ? trim($data['slug']) : '';
$excerpt = is_string($data['excerpt'] ?? null) ? trim($data['excerpt']) : '';
$body = is_string($data['body'] ?? null) ? $data['body'] : '';
$status = is_string($data['status'] ?? null) ? $data['status'] : '';
if ($title === '' || mb_strlen($title) > 255) {
throw new InvalidArgumentException('A title of 1–255 characters is required.');
}
if (strlen($slug) > 191 || !preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug)) {
throw new InvalidArgumentException('Use a lowercase slug with letters, numbers, and single hyphens.');
}
foreach ($this->findWhere('slug', $slug) as $post) {
if ((int) $post['id'] !== $postId) {
throw new InvalidArgumentException('That post slug is already in use.');
}
}
if (!in_array($status, ['draft', 'published'], true)) {
throw new InvalidArgumentException('Choose draft or published status.');
}
if ($status === 'published' && trim($body) === '') {
throw new InvalidArgumentException('Add the post body before publishing.');
}
$categoryId = $data['category_id'] ?? '';
if ($categoryId === '' || $categoryId === null) {
$categoryId = null;
} elseif (!is_scalar($categoryId) || !ctype_digit((string) $categoryId) || (int) $categoryId < 1 || (new CategoriesRepository())->findWithId((int) $categoryId) === null) {
throw new InvalidArgumentException('Choose an existing category.');
} else {
$categoryId = (int) $categoryId;
}
$featuredImageId = $data['featured_image_id'] ?? '';
if ($featuredImageId === '' || $featuredImageId === null) {
$featuredImageId = null;
} elseif (!is_string($featuredImageId) || strlen($featuredImageId) > 50) {
throw new InvalidArgumentException('Choose an existing image upload.');
} else {
$uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads';
$images = $this->db->select(
"SELECT public_id FROM {$uploadsTable} WHERE public_id = ? AND LOWER(mime_type) LIKE 'image/%' LIMIT 1",
[$featuredImageId]
);
if ($images === []) {
throw new InvalidArgumentException('Choose an existing image upload.');
}
$featuredImageId = $images[0]['public_id'];
}
$publishedAt = $this->validatedPublicationDate($data['published_at'] ?? '', $status);
return [
'title' => $title,
'slug' => $slug,
'excerpt' => $excerpt,
'body' => $body,
'featured_image_id' => $featuredImageId,
'category_id' => $categoryId,
'status' => $status,
'published_at' => $publishedAt,
];
}
private function resolveFeaturedImage(array $post): array
{
$publicId = $post['featured_image_public_id'] ?? null;
$originalFile = $post['featured_image_original_file'] ?? null;
if (is_string($publicId) && $publicId !== '' && is_string($originalFile) && $originalFile !== '') {
$image = new \Plugi\UploadedFile();
$image->public_id = $publicId;
$image->original_file = $originalFile;
$post['featured_image_url'] = $image->getUrl();
} else {
$post['featured_image_url'] = null;
$post['featured_image_alt_text'] = null;
}
unset($post['featured_image_public_id'], $post['featured_image_original_file']);
return $post;
}
private function validatedPublicationDate(mixed $value, string $status): ?string
{
if ($value === null || $value === '') {
return $status === 'published' ? date('Y-m-d H:i:s') : null;
}
if (!is_string($value)) {
throw new InvalidArgumentException('Enter a valid publication date.');
}
$value = trim($value);
$format = str_contains($value, 'T') ? 'Y-m-d\\TH:i' : 'Y-m-d H:i:s';
$date = DateTimeImmutable::createFromFormat('!' . $format, $value);
$errors = DateTimeImmutable::getLastErrors();
if ($date === false || ($errors !== false && ($errors['warning_count'] > 0 || $errors['error_count'] > 0)) || $date->format($format) !== $value) {
throw new InvalidArgumentException('Enter a valid publication date.');
}
if ($date > new DateTimeImmutable()) {
throw new InvalidArgumentException('Publication dates cannot be in the future.');
}
return $date->format('Y-m-d H:i:s');
}
}
@@ -0,0 +1,192 @@
<?php
use Plugi\Extensions\Blog\CategoriesRepository;
use Plugi\Extensions\Blog\PostsRepository;
use Plugi\Repositories\UploadRepository;
$postsRepository = new PostsRepository();
$post = [
'title' => '',
'slug' => '',
'excerpt' => '',
'body' => '',
'featured_image_id' => null,
'category_id' => null,
'status' => 'draft',
'published_at' => null,
];
if (isset($_GET['id']) && ctype_digit((string) $_GET['id'])) {
$post = $postsRepository->findWithId($_GET['id']) ?? $post;
}
$isEditing = isset($post['id']);
$publishedAt = $post['published_at'] ? date('Y-m-d\TH:i', strtotime($post['published_at'])) : '';
$categories = (new CategoriesRepository())->getAllForAdmin();
$imageUploads = array_values(array_filter((new UploadRepository())->getAll(), static fn($file): bool => is_string($file->mime_type ?? null) && str_starts_with(strtolower($file->mime_type), 'image/')));
?>
<header class="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div class="flex items-center gap-3">
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'posts']) ?>" class="btn btn-ghost btn-square btn-sm" aria-label="Back to posts" title="Back to posts">
<i class="ph-duotone ph-arrow-left text-xl" aria-hidden="true"></i>
</a>
<div class="space-y-1">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-primary">Blog editor</p>
<h2 class="text-xl font-bold tracking-tight"><?= $isEditing ? 'Edit post' : 'New post' ?></h2>
<p class="text-sm text-base-content/60">Save as a draft or publish the article.</p>
</div>
</div>
</header>
<form action="/ext--blog/save-post" method="post" class="space-y-6">
<?php phpb_csrf_field(); ?>
<?php if ($isEditing): ?>
<input type="hidden" name="id" value="<?= phpb_e((string) $post['id']) ?>">
<?php endif; ?>
<section class="card border border-base-300 bg-base-100 shadow-sm">
<div class="card-body gap-5 p-4 sm:p-6 lg:p-8">
<div>
<label for="post-title" class="label"><span class="label-text font-medium">Title</span></label>
<input id="post-title" type="text" name="title" maxlength="255" required value="<?= phpb_e($post['title']) ?>" class="input w-full">
</div>
<div>
<label for="post-slug" class="label"><span class="label-text font-medium">Slug</span></label>
<input id="post-slug" type="text" name="slug" maxlength="191" pattern="[a-z0-9]+(-[a-z0-9]+)*" required value="<?= phpb_e($post['slug']) ?>" class="input w-full" aria-describedby="post-slug-help">
<p id="post-slug-help" class="mt-1 text-sm text-base-content/60">Use lowercase letters, numbers, and hyphens.</p>
</div>
<div>
<label for="post-excerpt" class="label"><span class="label-text font-medium">Excerpt</span></label>
<textarea id="post-excerpt" name="excerpt" rows="3" class="textarea w-full"><?= phpb_e($post['excerpt']) ?></textarea>
</div>
<div class="space-y-3">
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<label for="post-body" class="label py-0"><span class="label-text font-medium">Post content</span></label>
<div id="post-body-view-tabs" role="tablist" class="tabs tabs-box hidden w-fit" aria-label="Post body view" hidden>
<button id="post-body-write-tab" type="button" role="tab" class="tab tab-active" aria-controls="post-body-write-panel" aria-selected="true" tabindex="0" data-view="write">Write</button>
<button id="post-body-preview-tab" type="button" role="tab" class="tab" aria-controls="post-body-preview-panel" aria-selected="false" tabindex="-1" data-view="preview">Preview</button>
</div>
</div>
<div id="post-body-write-panel" role="tabpanel" aria-labelledby="post-body-write-tab" tabindex="0" class="space-y-3">
<div class="overflow-hidden rounded-box border border-base-300 bg-base-100 shadow-sm">
<div id="post-body-toolbar" class="hidden flex flex-wrap gap-1 border-b border-base-300 bg-base-200/50 px-3 py-2" role="toolbar" aria-label="Markdown formatting" hidden>
<button type="button" class="btn btn-ghost btn-sm" data-format="bold" aria-label="Bold" title="Bold">Bold</button>
<button type="button" class="btn btn-ghost btn-sm" data-format="italic" aria-label="Italic" title="Italic">Italic</button>
<button type="button" class="btn btn-ghost btn-sm" data-format="heading" aria-label="Heading" title="Heading">Heading</button>
<button type="button" class="btn btn-ghost btn-sm" data-format="link" aria-label="Link" title="Link">Link</button>
<button type="button" class="btn btn-ghost btn-sm" data-format="list" aria-label="Bulleted list" title="Bulleted list">Bullets</button>
<button type="button" class="btn btn-ghost btn-sm" data-format="ordered-list" aria-label="Numbered list" title="Numbered list">Numbered list</button>
<button type="button" class="btn btn-ghost btn-sm" data-format="quote" aria-label="Blockquote" title="Blockquote">Quote</button>
<button type="button" class="btn btn-ghost btn-sm" data-format="horizontal-rule" aria-label="Horizontal rule" title="Horizontal rule">Rule</button>
<button type="button" class="btn btn-ghost btn-sm" data-format="code" aria-label="Inline code" title="Inline code">Code</button>
<button type="button" class="btn btn-ghost btn-sm" data-format="code-block" aria-label="Code block" title="Code block">Code block</button>
</div>
<div id="post-body-editor" class="blog-markdown-editor hidden w-full" hidden></div>
<textarea id="post-body" name="body" rows="16" class="textarea w-full rounded-none border-0 font-mono" aria-describedby="post-body-help"><?= phpb_e($post['body']) ?></textarea>
<p id="post-body-help" class="border-t border-base-300 px-4 py-2 text-sm text-base-content/60">Use Markdown for headings, lists, quotes, rules, code blocks, links, and emphasis.</p>
</div>
<div class="flex flex-col gap-3 sm:flex-row sm:items-end">
<div class="w-full sm:flex-1">
<label for="post-inline-image" class="label"><span class="label-text font-medium">Insert inline image</span></label>
<select id="post-inline-image" class="select w-full" aria-describedby="post-inline-image-help">
<option value="">Choose an image</option>
<?php foreach ($imageUploads as $file): ?>
<?php
$inlineImageUrl = $file->getUrl();
if ($file->original_file !== '') {
$inlineImageUrl = substr($inlineImageUrl, 0, -strlen($file->original_file)) . rawurlencode($file->original_file);
}
?>
<option value="<?= phpb_e($file->public_id) ?>" data-url="<?= phpb_e($inlineImageUrl) ?>" data-alt="<?= phpb_e($file->alt_text ?? '') ?>"><?= phpb_e($file->original_file) ?></option>
<?php endforeach; ?>
</select>
</div>
<button type="button" id="insert-post-inline-image" class="btn btn-outline" aria-label="Insert selected image at the cursor">Insert image</button>
</div>
<p id="post-inline-image-help" class="text-sm text-base-content/60">Alt text comes from the media library; the image Markdown is inserted at the cursor.</p>
</div>
<section id="post-body-preview-panel" role="tabpanel" aria-labelledby="post-body-preview-tab" tabindex="0" class="hidden" hidden>
<div class="min-h-96 overflow-hidden rounded-box border border-base-300 bg-base-100 shadow-sm">
<div class="flex flex-col gap-2 border-b border-base-300 bg-base-200/50 px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h3 id="post-body-preview-heading" class="font-semibold">Live preview</h3>
<p class="text-sm text-base-content/60">Rendered like the published post.</p>
</div>
<p id="post-body-preview-status" class="text-sm text-base-content/60" role="status" aria-live="polite">Waiting for the preview…</p>
</div>
<div id="post-body-preview" class="min-h-80 space-y-4 p-5 sm:p-8" role="region" aria-label="Rendered post preview" aria-busy="false"></div>
</div>
</section>
</div>
<div>
<label for="post-featured-image" class="label"><span class="label-text font-medium">Featured image</span></label>
<select id="post-featured-image" name="featured_image_id" class="select w-full" aria-describedby="post-featured-image-help">
<option value="">No featured image</option>
<?php foreach ($imageUploads as $file): ?>
<option value="<?= phpb_e($file->public_id) ?>" <?= (string) $file->public_id === (string) ($post['featured_image_id'] ?? '') ? 'selected' : '' ?>><?= phpb_e($file->original_file) ?></option>
<?php endforeach; ?>
</select>
<p id="post-featured-image-help" class="mt-1 text-sm text-base-content/60">Choose an image from the existing media library.</p>
</div>
<div class="grid gap-5 sm:grid-cols-2">
<div>
<label for="post-category" class="label"><span class="label-text font-medium">Category</span></label>
<select id="post-category" name="category_id" class="select w-full">
<option value="">No category</option>
<?php foreach ($categories as $category): ?>
<option value="<?= phpb_e((string) $category['id']) ?>" <?= (string) $category['id'] === (string) $post['category_id'] ? 'selected' : '' ?>><?= phpb_e($category['name']) ?></option>
<?php endforeach; ?>
</select>
</div>
<div>
<label for="post-status" class="label"><span class="label-text font-medium">Status</span></label>
<select id="post-status" name="status" class="select w-full">
<option value="draft" <?= $post['status'] === 'draft' ? 'selected' : '' ?>>Draft</option>
<option value="published" <?= $post['status'] === 'published' ? 'selected' : '' ?>>Published</option>
</select>
</div>
</div>
<div>
<label for="post-published-at" class="label"><span class="label-text font-medium">Publication date</span></label>
<input id="post-published-at" type="datetime-local" name="published_at" value="<?= phpb_e($publishedAt) ?>" class="input w-full" aria-describedby="post-published-at-help">
<p id="post-published-at-help" class="mt-1 text-sm text-base-content/60">Leave blank to use the current time when publishing. Future dates are not supported.</p>
</div>
</div>
</section>
<div class="flex flex-wrap justify-end gap-3">
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'posts']) ?>" class="btn btn-ghost">Cancel</a>
<button type="submit" class="btn btn-primary">Save post</button>
</div>
</form>
<script>
(function () {
const body = document.getElementById('post-body');
const imageSelect = document.getElementById('post-inline-image');
const insertButton = document.getElementById('insert-post-inline-image');
if (!body || !imageSelect || !insertButton) {
return;
}
insertButton.addEventListener('click', function () {
const option = imageSelect.selectedOptions[0];
if (!option || !option.value) {
return;
}
const altText = option.dataset.alt || option.textContent.trim();
const markdownAlt = altText.replace(/[\r\n]+/g, ' ').replace(/&/g, '&amp;').replace(/\[/g, '&#91;').replace(/\]/g, '&#93;');
const markdown = `![${markdownAlt}](${option.dataset.url})`;
if (window.blogMarkdownEditor && window.blogMarkdownEditor.insertAtCursor(markdown)) {
return;
}
const start = body.selectionStart;
const end = body.selectionEnd;
const prefix = start > 0 && !/\s/.test(body.value[start - 1]) ? ' ' : '';
const suffix = end < body.value.length && !/\s/.test(body.value[end]) ? ' ' : '';
body.setRangeText(prefix + markdown + suffix, start, end, 'end');
body.dispatchEvent(new Event('input', { bubbles: true }));
body.focus();
});
})();
</script>
@@ -0,0 +1,82 @@
<?php
use Plugi\Extensions\Blog\CategoriesRepository;
$categoriesRepository = new CategoriesRepository();
$categories = $categoriesRepository->getAllForAdmin();
$category = ['name' => '', 'slug' => ''];
if (isset($_GET['id']) && ctype_digit((string) $_GET['id'])) {
$category = $categoriesRepository->findWithId($_GET['id']) ?? $category;
}
$isEditing = isset($category['id']);
?>
<section class="space-y-5">
<header class="space-y-1">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-primary">Blog extension</p>
<h2 class="text-xl font-bold tracking-tight text-base-content">Categories</h2>
<p class="text-sm text-base-content/60">Organize posts with one optional category each.</p>
</header>
<form action="/ext--blog/save-category" method="post" class="card border border-base-300 bg-base-100 shadow-sm">
<?php phpb_csrf_field(); ?>
<?php if ($isEditing): ?>
<input type="hidden" name="id" value="<?= phpb_e((string) $category['id']) ?>">
<?php endif; ?>
<div class="card-body gap-4 p-4 sm:p-6">
<h3 class="card-title text-lg"><?= $isEditing ? 'Edit category' : 'New category' ?></h3>
<div class="grid gap-4 sm:grid-cols-2">
<div>
<label for="category-name" class="label"><span class="label-text font-medium">Name</span></label>
<input id="category-name" type="text" name="name" maxlength="255" required value="<?= phpb_e($category['name']) ?>" class="input w-full">
</div>
<div>
<label for="category-slug" class="label"><span class="label-text font-medium">Slug</span></label>
<input id="category-slug" type="text" name="slug" maxlength="191" pattern="[a-z0-9]+(-[a-z0-9]+)*" required value="<?= phpb_e($category['slug']) ?>" class="input w-full">
</div>
</div>
<div class="flex flex-wrap justify-end gap-3">
<?php if ($isEditing): ?>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'categories']) ?>" class="btn btn-ghost">Cancel</a>
<?php endif; ?>
<button type="submit" class="btn btn-primary"><?= $isEditing ? 'Save category' : 'Add category' ?></button>
</div>
</div>
</form>
<?php if (empty($categories)): ?>
<div class="card border border-dashed border-base-300 bg-base-100 shadow-sm" role="status">
<div class="card-body items-center px-5 py-10 text-center">
<h3 class="card-title text-lg">No categories yet</h3>
<p class="text-sm text-base-content/60">Create a category above to make it available to posts.</p>
</div>
</div>
<?php else: ?>
<div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
<table class="table table-zebra w-full min-w-[32rem]">
<thead><tr><th>Name</th><th>Slug</th><th class="w-40 text-right">Actions</th></tr></thead>
<tbody>
<?php foreach ($categories as $item): ?>
<tr>
<td><?= phpb_e($item['name']) ?></td>
<td><span class="font-mono text-sm"><?= phpb_e($item['slug']) ?></span></td>
<td>
<div class="flex items-center justify-end gap-1">
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'categories', 'id' => $item['id']]) ?>" class="btn btn-ghost btn-square btn-sm" title="Edit category" aria-label="Edit <?= phpb_e($item['name']) ?>">
<i class="ph-duotone ph-pencil-line text-lg" aria-hidden="true"></i>
</a>
<form action="/ext--blog/delete-category" method="post" onsubmit="return confirm('Delete this category? Posts will remain uncategorized.')">
<?php phpb_csrf_field(); ?>
<input type="hidden" name="id" value="<?= phpb_e((string) $item['id']) ?>">
<button type="submit" class="btn btn-ghost btn-square btn-sm text-error" title="Delete category" aria-label="Delete <?= phpb_e($item['name']) ?>">
<i class="ph-duotone ph-trash text-lg" aria-hidden="true"></i>
</button>
</form>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</section>
@@ -0,0 +1,128 @@
<?php
use Plugi\Extensions\Blog\CategoriesRepository;
use Plugi\Extensions\Blog\PostsRepository;
$postsRepository = new PostsRepository();
$search = is_string($_GET['q'] ?? null) ? trim($_GET['q']) : '';
$pageValue = $_GET['posts_page'] ?? null;
$page = is_string($pageValue) ? filter_var($pageValue, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) : false;
$page = $page === false ? 1 : $page;
$pageResult = $postsRepository->getPageForAdmin($search, $page);
$totalPages = max(1, (int) ceil($pageResult['total'] / PostsRepository::POSTS_PER_PAGE));
if ($page > $totalPages) {
$page = $totalPages;
}
$posts = $pageResult['posts'];
$searchParameters = $search === '' ? [] : ['q' => $search];
$adminPostsUrl = phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'posts']);
$websiteManagerUrl = phpb_url('website_manager');
$categories = (new CategoriesRepository())->getAllForAdmin();
$categoryNames = [];
foreach ($categories as $category) {
$categoryNames[$category['id']] = $category['name'];
}
?>
<section class="space-y-5">
<header class="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
<div class="space-y-1">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-primary">Blog extension</p>
<h2 class="text-xl font-bold tracking-tight text-base-content">Posts</h2>
<p class="text-sm text-base-content/60"><?= phpb_e((string) $pageResult['total']) ?> post<?= $pageResult['total'] !== 1 ? 's' : '' ?></p>
</div>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'editPost']) ?>" class="btn btn-primary">
<i class="ph-duotone ph-plus" aria-hidden="true"></i>
New post
</a>
</header>
<form class="flex flex-col gap-3 sm:flex-row sm:items-end" method="get" action="<?= phpb_e($websiteManagerUrl) ?>">
<input type="hidden" name="tab" value="ext--blog">
<input type="hidden" name="action" value="posts">
<label class="flex w-full max-w-md flex-col gap-2">
<span class="text-sm font-medium">Search posts</span>
<input class="input w-full" type="search" name="q" value="<?= phpb_e($search) ?>">
</label>
<button class="btn" type="submit">Search</button>
</form>
<?php if ($pageResult['total'] === 0 && $search !== ''): ?>
<div class="alert alert-info" role="status">
No posts found for &quot;<?= phpb_e($search) ?>&quot;.
<a class="link link-hover" href="<?= phpb_e($adminPostsUrl) ?>">Clear search</a>
</div>
<?php elseif ($pageResult['total'] === 0): ?>
<div class="card border border-dashed border-base-300 bg-base-100 shadow-sm" role="status">
<div class="card-body items-center gap-3 px-5 py-12 text-center sm:py-16">
<span class="grid size-14 place-items-center rounded-2xl bg-primary/10 text-primary">
<i class="text-3xl ph-duotone ph-article" aria-hidden="true"></i>
</span>
<h3 class="card-title mt-1 text-lg">No posts yet</h3>
<p class="max-w-md text-sm leading-relaxed text-base-content/60">Create a draft or publish your first article.</p>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'editPost']) ?>" class="btn btn-primary mt-2">
<i class="ph-duotone ph-plus" aria-hidden="true"></i>
Create your first post
</a>
</div>
</div>
<?php else: ?>
<div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
<table class="table table-zebra w-full min-w-[48rem]">
<thead>
<tr>
<th>Title</th>
<th>Category</th>
<th>Status</th>
<th>Published</th>
<th class="w-40 text-right">Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($posts as $post): ?>
<tr>
<td>
<div class="font-medium"><?= phpb_e($post['title']) ?></div>
<div class="text-xs text-base-content/60">/<?= phpb_e($post['slug']) ?></div>
</td>
<td><?= phpb_e($post['category_id'] === null ? '—' : ($categoryNames[$post['category_id']] ?? '—')) ?></td>
<td><span class="badge <?= $post['status'] === 'published' ? 'badge-success' : 'badge-warning' ?>"><?= phpb_e(ucfirst($post['status'])) ?></span></td>
<td><?= phpb_e($post['published_at'] ?? '—') ?></td>
<td>
<div class="flex items-center justify-end gap-1">
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'editPost', 'id' => $post['id']]) ?>" class="btn btn-ghost btn-square btn-sm" title="Edit post" aria-label="Edit <?= phpb_e($post['title']) ?>">
<i class="ph-duotone ph-pencil-line text-lg" aria-hidden="true"></i>
</a>
<form action="/ext--blog/delete-post" method="post" onsubmit="return confirm('Delete this post?')">
<?php phpb_csrf_field(); ?>
<input type="hidden" name="id" value="<?= phpb_e((string) $post['id']) ?>">
<button type="submit" class="btn btn-ghost btn-square btn-sm text-error" title="Delete post" aria-label="Delete <?= phpb_e($post['title']) ?>">
<i class="ph-duotone ph-trash text-lg" aria-hidden="true"></i>
</button>
</form>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
<?php if ($totalPages > 1): ?>
<nav class="flex justify-center" aria-label="Admin post pages">
<div class="join">
<?php if ($page > 1): ?>
<a class="join-item btn btn-sm" rel="prev" href="<?= phpb_e($adminPostsUrl . '&' . http_build_query($searchParameters + ['posts_page' => $page - 1])) ?>">Previous</a>
<?php else: ?>
<span class="join-item btn btn-sm btn-disabled" aria-disabled="true">Previous</span>
<?php endif; ?>
<span class="join-item btn btn-sm btn-disabled" aria-current="page">Page <?= phpb_e($page) ?> of <?= phpb_e($totalPages) ?></span>
<?php if ($page < $totalPages): ?>
<a class="join-item btn btn-sm" rel="next" href="<?= phpb_e($adminPostsUrl . '&' . http_build_query($searchParameters + ['posts_page' => $page + 1])) ?>">Next</a>
<?php else: ?>
<span class="join-item btn btn-sm btn-disabled" aria-disabled="true">Next</span>
<?php endif; ?>
</div>
</nav>
<?php endif; ?>
</section>
@@ -0,0 +1,31 @@
.blog-markdown-editor .cm-editor {
border: 0;
border-radius: 0;
height: clamp(20rem, 55vh, 38rem);
color: var(--color-base-content);
background: var(--color-base-100);
}
.blog-markdown-editor .cm-editor.cm-focused {
outline: 0;
box-shadow: inset 0 0 0 2px var(--color-primary);
}
.blog-markdown-editor .cm-scroller {
min-height: 0;
font-family: var(--default-mono-font, monospace);
}
.blog-markdown-editor .cm-content {
padding: 1rem 0.75rem;
line-height: 1.65;
}
.blog-markdown-editor .cm-line {
padding-inline: 0.25rem;
}
.blog-markdown-editor .cm-activeLineGutter {
color: var(--color-primary);
font-weight: 600;
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,302 @@
import { markdown } from '@codemirror/lang-markdown';
import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands';
import { HighlightStyle, bracketMatching, indentOnInput, syntaxHighlighting } from '@codemirror/language';
import { drawSelection, EditorView, highlightActiveLine, highlightActiveLineGutter, keymap, lineNumbers } from '@codemirror/view';
import { tags } from '@lezer/highlight';
document.addEventListener('DOMContentLoaded', () => {
const textarea = document.getElementById('post-body');
const editorMount = document.getElementById('post-body-editor');
const toolbar = document.getElementById('post-body-toolbar');
const viewTabs = document.getElementById('post-body-view-tabs');
const writePanel = document.getElementById('post-body-write-panel');
const previewPanel = document.getElementById('post-body-preview-panel');
if (!textarea || !editorMount || !toolbar || !viewTabs || !writePanel || !previewPanel) {
return;
}
let editor;
try {
editor = new EditorView({
doc: textarea.value,
extensions: [
markdown(),
lineNumbers(),
highlightActiveLineGutter(),
highlightActiveLine(),
drawSelection(),
history(),
indentOnInput(),
bracketMatching(),
syntaxHighlighting(HighlightStyle.define([
{ tag: tags.heading, color: 'var(--color-primary)', fontWeight: '700' },
{ tag: tags.strong, color: 'var(--color-base-content)', fontWeight: '700' },
{ tag: tags.emphasis, color: 'var(--color-base-content)', fontStyle: 'italic' },
{ tag: tags.link, color: 'var(--color-primary)', textDecoration: 'underline' },
{ tag: tags.url, color: 'var(--color-primary)' },
{ tag: tags.monospace, color: 'var(--color-base-content)', backgroundColor: 'var(--color-base-200)' },
{ tag: tags.quote, color: 'var(--color-base-content)', fontStyle: 'italic' },
{ tag: tags.strikethrough, color: 'var(--color-base-content)', textDecoration: 'line-through' },
])),
EditorView.theme({
'&': { color: 'var(--color-base-content)', backgroundColor: 'var(--color-base-100)' },
'.cm-content': { caretColor: 'var(--color-primary)' },
'.cm-cursor, .cm-dropCursor': { borderLeftColor: 'var(--color-primary)' },
'.cm-selectionBackground, &.cm-focused .cm-selectionBackground': { backgroundColor: 'color-mix(in oklab, var(--color-primary) 35%, transparent)' },
'.cm-gutters': { color: 'var(--color-base-content)', backgroundColor: 'var(--color-base-200)', borderRight: '1px solid var(--color-base-300)' },
'.cm-activeLine, .cm-activeLineGutter': { backgroundColor: 'color-mix(in oklab, var(--color-base-200) 70%, transparent)' },
'.cm-matchingBracket': { backgroundColor: 'var(--color-base-200)', outline: '1px solid var(--color-primary)' },
}),
keymap.of([...defaultKeymap, ...historyKeymap, indentWithTab]),
EditorView.lineWrapping,
EditorView.contentAttributes.of({
'aria-label': 'Post body Markdown',
'aria-describedby': 'post-body-help',
}),
EditorView.updateListener.of((update) => {
if (update.docChanged) {
textarea.value = update.state.doc.toString();
textarea.dispatchEvent(new Event('input', { bubbles: true }));
}
}),
],
parent: editorMount,
});
} catch (error) {
console.error('Could not initialize the blog Markdown editor.', error);
return;
}
editorMount.hidden = false;
editorMount.classList.remove('hidden');
toolbar.hidden = false;
toolbar.classList.remove('hidden');
textarea.hidden = true;
const tabs = Array.from(viewTabs.querySelectorAll('[role="tab"]'));
const activateView = (view, focus = false) => {
const showPreview = view === 'preview';
tabs.forEach((tab) => {
const active = tab.dataset.view === view;
tab.setAttribute('aria-selected', String(active));
tab.tabIndex = active ? 0 : -1;
tab.classList.toggle('tab-active', active);
if (focus && active) {
tab.focus();
}
});
writePanel.hidden = showPreview;
writePanel.classList.toggle('hidden', showPreview);
previewPanel.hidden = !showPreview;
previewPanel.classList.toggle('hidden', !showPreview);
};
activateView('write');
viewTabs.hidden = false;
viewTabs.classList.remove('hidden');
viewTabs.addEventListener('click', (event) => {
const tab = event.target.closest('[role="tab"][data-view]');
if (tab) {
activateView(tab.dataset.view);
}
});
viewTabs.addEventListener('keydown', (event) => {
const currentIndex = tabs.indexOf(document.activeElement);
if (currentIndex < 0) {
return;
}
const nextIndex = event.key === 'ArrowRight'
? (currentIndex + 1) % tabs.length
: event.key === 'ArrowLeft'
? (currentIndex - 1 + tabs.length) % tabs.length
: event.key === 'Home'
? 0
: event.key === 'End'
? tabs.length - 1
: -1;
if (nextIndex !== -1) {
event.preventDefault();
activateView(tabs[nextIndex].dataset.view, true);
}
});
const applyFormatting = (button) => {
const selection = editor.state.selection.main;
const format = button.dataset.format;
if (format === 'horizontal-rule') {
const line = editor.state.doc.lineAt(selection.from);
const insert = line.text ? '\n\n---' : '---';
editor.dispatch({
changes: { from: line.to, to: line.to, insert },
selection: { anchor: line.to + insert.length },
});
editor.focus();
return;
}
if (format === 'code-block' || format === 'quote') {
const firstLine = editor.state.doc.lineAt(selection.from);
const lastLine = editor.state.doc.lineAt(selection.to);
const selectedText = editor.state.doc.sliceString(firstLine.from, lastLine.to);
const lines = selectedText.split('\n');
const insert = format === 'code-block'
? `\`\`\`\n${selectedText || 'Code block'}\n\`\`\``
: lines.every((line) => line.startsWith('> '))
? lines.map((line) => line.slice(2)).join('\n')
: lines.map((line) => `> ${line || 'Quote'}`).join('\n');
editor.dispatch({
changes: { from: firstLine.from, to: lastLine.to, insert },
selection: format === 'code-block'
? { anchor: firstLine.from + 4, head: firstLine.from + 4 + (selectedText || 'Code block').length }
: { anchor: firstLine.from, head: firstLine.from + insert.length },
});
editor.focus();
return;
}
if (format === 'heading' || format === 'list' || format === 'ordered-list') {
const line = editor.state.doc.lineAt(selection.from);
const prefix = format === 'heading' ? '## ' : format === 'ordered-list' ? '1. ' : '- ';
const hasPrefix = format === 'ordered-list'
? /^\d+[.)]\s/.test(line.text)
: format === 'list'
? /^[-*+]\s/.test(line.text)
: line.text.startsWith(prefix);
const lineText = hasPrefix
? line.text.replace(format === 'ordered-list' ? /^\d+[.)]\s/ : format === 'list' ? /^[-*+]\s/ : /^## /, '')
: `${prefix}${line.text || (format === 'heading' ? 'Heading' : 'List item')}`;
const selectedFrom = line.from + (hasPrefix ? 0 : prefix.length);
editor.dispatch({
changes: { from: line.from, to: line.to, insert: lineText },
selection: { anchor: selectedFrom, head: line.from + lineText.length },
});
editor.focus();
return;
}
const formats = {
bold: ['**', '**', 'bold text'],
italic: ['*', '*', 'italic text'],
link: ['[', '](https://example.com)', 'link text'],
code: ['`', '`', 'code'],
};
const [before, after, placeholder] = formats[format] || [];
if (before === undefined) {
return;
}
const selectedText = editor.state.sliceDoc(selection.from, selection.to);
const text = selectedText || placeholder;
editor.dispatch({
changes: { from: selection.from, to: selection.to, insert: `${before}${text}${after}` },
selection: {
anchor: selection.from + before.length,
head: selection.from + before.length + text.length,
},
});
editor.focus();
};
toolbar.addEventListener('click', (event) => {
const button = event.target.closest('button[data-format]');
if (button) {
applyFormatting(button);
}
});
const form = textarea.form;
form?.addEventListener('submit', () => {
textarea.value = editor.state.doc.toString();
});
const preview = document.getElementById('post-body-preview');
const previewStatus = document.getElementById('post-body-preview-status');
if (form && preview && previewStatus) {
let previewTimer;
let previewRequestId = 0;
let activePreviewRequest = null;
const setPreviewStatus = (message, isError = false) => {
previewStatus.textContent = message;
previewStatus.classList.toggle('text-error', isError);
previewStatus.classList.toggle('text-base-content/60', !isError);
};
const schedulePreview = () => {
window.clearTimeout(previewTimer);
const requestId = ++previewRequestId;
activePreviewRequest?.abort();
activePreviewRequest = null;
preview.replaceChildren();
preview.setAttribute('aria-busy', 'true');
setPreviewStatus('Updating preview…');
previewTimer = window.setTimeout(async () => {
const csrfToken = form.querySelector('[name="_csrf_token"]')?.value || '';
if (!csrfToken) {
if (requestId === previewRequestId) {
setPreviewStatus('Preview unavailable. Your Markdown is unchanged and can still be saved.', true);
preview.setAttribute('aria-busy', 'false');
}
return;
}
const request = new AbortController();
activePreviewRequest = request;
const requestBody = new FormData();
requestBody.set('body', textarea.value);
requestBody.set('_csrf_token', csrfToken);
try {
const response = await fetch('/ext--blog/preview-post', {
method: 'POST',
body: requestBody,
credentials: 'same-origin',
headers: { Accept: 'application/json' },
signal: request.signal,
});
const result = await response.json();
if (requestId !== previewRequestId) {
return;
}
if (!response.ok || !result || typeof result.html !== 'string') {
throw new Error('Preview request failed.');
}
preview.innerHTML = result.html;
window.blogCodeHighlighter?.highlight(preview);
setPreviewStatus(result.html === '' ? 'The post body is empty.' : 'Preview updated.');
} catch (error) {
if (error.name !== 'AbortError' && requestId === previewRequestId) {
setPreviewStatus('Preview unavailable. Your Markdown is unchanged and can still be saved.', true);
}
} finally {
if (requestId === previewRequestId) {
activePreviewRequest = null;
preview.setAttribute('aria-busy', 'false');
}
}
}, 300);
};
textarea.addEventListener('input', schedulePreview);
schedulePreview();
}
window.blogMarkdownEditor = {
insertAtCursor(markdown) {
const selection = editor.state.selection.main;
const document = editor.state.doc;
const before = selection.from > 0 && !/\s/.test(document.sliceString(selection.from - 1, selection.from)) ? ' ' : '';
const after = selection.to < document.length && !/\s/.test(document.sliceString(selection.to, selection.to + 1)) ? ' ' : '';
const insertion = `${before}${markdown}${after}`;
editor.dispatch({
changes: { from: selection.from, to: selection.to, insert: insertion },
selection: { anchor: selection.from + insertion.length },
});
editor.focus();
return true;
},
};
});
+38
View File
@@ -0,0 +1,38 @@
<?php
$modules = [
'posts' => [
'include' => __DIR__ . '/Views/ListPosts.php',
'label' => 'Posts',
'icon' => 'ph-article',
'inMenu' => true,
],
'categories' => [
'include' => __DIR__ . '/Views/ListCategories.php',
'label' => 'Categories',
'icon' => 'ph-tag',
'inMenu' => true,
],
'editPost' => [
'include' => __DIR__ . '/Views/EditPost.php',
'inMenu' => false,
],
];
$activeModule = isset($_GET['action']) && array_key_exists($_GET['action'], $modules) ? $_GET['action'] : 'posts';
?>
<nav class="mb-6 overflow-x-auto" aria-label="Blog extension navigation">
<div class="tabs tabs-box w-max min-w-full bg-base-200/50">
<?php foreach ($modules as $name => $module): ?>
<?php if (!$module['inMenu']) continue; ?>
<a class="tab gap-2 <?= $name === $activeModule ? 'tab-active' : '' ?>" <?= $name === $activeModule ? 'aria-current="page"' : '' ?> href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => $name]) ?>">
<i class="ph-duotone <?= phpb_e($module['icon']) ?>" aria-hidden="true"></i>
<?= phpb_e($module['label']) ?>
</a>
<?php endforeach; ?>
</div>
</nav>
<div class="w-full">
<?php include $modules[$activeModule]['include']; ?>
</div>
@@ -0,0 +1,48 @@
.hljs {
color: var(--color-base-content);
}
.hljs-comment,
.hljs-quote {
opacity: 0.7;
font-style: italic;
}
.hljs-keyword,
.hljs-selector-tag,
.hljs-literal,
.hljs-section {
color: var(--color-primary);
}
.hljs-string,
.hljs-title,
.hljs-name,
.hljs-type,
.hljs-attribute,
.hljs-symbol,
.hljs-bullet,
.hljs-addition {
color: var(--color-success);
}
.hljs-number,
.hljs-regexp,
.hljs-variable,
.hljs-template-variable {
color: var(--color-secondary);
}
.hljs-built_in,
.hljs-class .hljs-title {
color: var(--color-info);
}
.hljs-meta,
.hljs-meta .hljs-keyword {
color: var(--color-warning);
}
.hljs-deletion {
color: var(--color-error);
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,33 @@
import hljs from 'highlight.js/lib/core';
import bash from 'highlight.js/lib/languages/bash';
import css from 'highlight.js/lib/languages/css';
import diff from 'highlight.js/lib/languages/diff';
import javascript from 'highlight.js/lib/languages/javascript';
import json from 'highlight.js/lib/languages/json';
import markdown from 'highlight.js/lib/languages/markdown';
import php from 'highlight.js/lib/languages/php';
import python from 'highlight.js/lib/languages/python';
import sql from 'highlight.js/lib/languages/sql';
import typescript from 'highlight.js/lib/languages/typescript';
import xml from 'highlight.js/lib/languages/xml';
import yaml from 'highlight.js/lib/languages/yaml';
Object.entries({ bash, css, diff, javascript, json, markdown, php, python, sql, typescript, xml, yaml })
.forEach(([name, language]) => hljs.registerLanguage(name, language));
window.blogCodeHighlighter = {
highlight(root = document) {
root.querySelectorAll('pre code:not(.hljs)').forEach((code) => {
const language = code.className.match(/(?:^|\s)language-([^\s]+)/)?.[1];
if (language && !hljs.getLanguage(language)) return;
hljs.highlightElement(code);
});
},
};
const highlightPage = () => window.blogCodeHighlighter.highlight(document);
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', highlightPage, { once: true });
} else {
highlightPage();
}
@@ -0,0 +1,8 @@
<?php
return [
'title' => 'Blog Post',
'category' => 'Blog',
'icon' => 'ph ph-article',
'cache' => false,
];
@@ -0,0 +1,42 @@
<?php
$slug = phpb_route_parameter('slug');
$post = is_string($slug) && $slug !== ''
? (new \Plugi\Extensions\Blog\PostsRepository())->findPublishedBySlug($slug)
: null;
?>
<?php if ($post === null): ?>
<section class="card border border-base-300 bg-base-100 shadow-sm" aria-labelledby="blog-post-not-found">
<div class="card-body">
<h1 id="blog-post-not-found" class="card-title">Article not found</h1>
<p class="text-base-content/70">This article is unavailable or may no longer be published.</p>
</div>
</section>
<?php else: ?>
<article class="mx-auto w-full max-w-3xl space-y-8">
<header class="space-y-4">
<div class="flex flex-wrap items-center gap-3 text-sm text-base-content/60">
<?php if (!empty($post['category_name'])): ?>
<span class="badge badge-outline"><?= phpb_e($post['category_name']) ?></span>
<?php endif; ?>
<?php if (!empty($post['published_at'])): ?>
<?php $publishedTimestamp = strtotime($post['published_at']); ?>
<?php if ($publishedTimestamp !== false): ?>
<time datetime="<?= phpb_e(date('c', $publishedTimestamp)) ?>"><?= phpb_e(date('F j, Y', $publishedTimestamp)) ?></time>
<?php endif; ?>
<?php endif; ?>
</div>
<h1 class="text-3xl font-bold tracking-tight text-base-content sm:text-4xl"><?= phpb_e($post['title']) ?></h1>
<?php if ($post['excerpt'] !== ''): ?>
<p class="text-lg leading-relaxed text-base-content/70"><?= phpb_e($post['excerpt']) ?></p>
<?php endif; ?>
</header>
<?php if (!empty($post['featured_image_url'])): ?>
<?php $featuredImageAlt = trim((string) ($post['featured_image_alt_text'] ?? '')) ?: $post['title']; ?>
<figure class="overflow-hidden rounded-box">
<img src="<?= phpb_e($post['featured_image_url']) ?>" alt="<?= phpb_e($featuredImageAlt) ?>" class="max-h-[32rem] w-full object-cover">
</figure>
<?php endif; ?>
<div class="space-y-4 text-base leading-7 text-base-content"><?= (new \Plugi\Extensions\Blog\PostContentRenderer())->render($post['body']) ?></div>
</article>
<?php endif; ?>
@@ -0,0 +1,8 @@
<?php
return [
'title' => 'Published Posts',
'category' => 'Blog',
'icon' => 'ph ph-article',
'cache' => false,
];
@@ -0,0 +1,87 @@
<?php
$postsRepository = new \Plugi\Extensions\Blog\PostsRepository();
$search = is_string($_GET['q'] ?? null) ? trim($_GET['q']) : '';
$pageValue = $_GET['page'] ?? null;
$page = is_string($pageValue) ? filter_var($pageValue, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) : false;
$page = $page === false ? 1 : $page;
$listingPath = isset($_SERVER['SERVER_NAME'], $_SERVER['REQUEST_URI']) ? phpb_full_url(phpb_current_relative_url(true)) : '/';
$pageResult = $postsRepository->getPageForListing($search, $page);
$totalPages = max(1, (int) ceil($pageResult['total'] / \Plugi\Extensions\Blog\PostsRepository::POSTS_PER_PAGE));
if ($page > $totalPages) {
$page = $totalPages;
}
$posts = $pageResult['posts'];
$searchParameters = $search === '' ? [] : ['q' => $search];
?>
<section class="space-y-6" aria-label="Blog posts">
<form class="flex flex-col gap-3 sm:flex-row sm:items-end" method="get" action="<?= phpb_e($listingPath) ?>">
<label class="flex w-full max-w-md flex-col gap-2">
<span class="text-sm font-medium">Search posts</span>
<input class="input w-full" type="search" name="q" value="<?= phpb_e($search) ?>" />
</label>
<button class="btn" type="submit">Search</button>
</form>
<?php if ($pageResult['total'] === 0): ?>
<div class="alert alert-info" role="status">
<?= $search === '' ? 'No published posts yet.' : 'No published posts match &quot;' . phpb_e($search) . '&quot;.' ?>
</div>
<?php else: ?>
<div class="grid gap-6 md:grid-cols-2">
<?php foreach ($posts as $post): ?>
<article class="card h-full border border-base-300 bg-base-100 shadow-sm">
<?php if (!empty($post['featured_image_url'])): ?>
<?php $featuredImageAlt = trim((string) ($post['featured_image_alt_text'] ?? '')) ?: $post['title']; ?>
<figure class="px-6 pt-6">
<img src="<?= phpb_e($post['featured_image_url']) ?>" alt="<?= phpb_e($featuredImageAlt) ?>" class="aspect-video w-full rounded-box object-cover">
</figure>
<?php endif; ?>
<div class="card-body gap-4">
<div class="flex flex-wrap items-center gap-3 text-sm text-base-content/60">
<?php if (!empty($post['category_name'])): ?>
<span class="badge badge-outline"><?= phpb_e($post['category_name']) ?></span>
<?php endif; ?>
<?php if (!empty($post['published_at'])): ?>
<?php $publishedTimestamp = strtotime($post['published_at']); ?>
<?php if ($publishedTimestamp !== false): ?>
<time datetime="<?= phpb_e(date('c', $publishedTimestamp)) ?>"><?= phpb_e(date('F j, Y', $publishedTimestamp)) ?></time>
<?php endif; ?>
<?php endif; ?>
</div>
<h2 class="card-title text-xl">
<a class="link link-hover" href="<?= phpb_e(phpb_full_url('/blog/' . rawurlencode($post['slug']))) ?>"><?= phpb_e($post['title']) ?></a>
</h2>
<?php if ($post['excerpt'] !== ''): ?>
<p class="whitespace-pre-line text-base-content/80"><?= phpb_e($post['excerpt']) ?></p>
<?php endif; ?>
<div class="card-actions mt-auto justify-end">
<a class="btn btn-ghost btn-sm" href="<?= phpb_e(phpb_full_url('/blog/' . rawurlencode($post['slug']))) ?>">
Read article<span class="sr-only">: <?= phpb_e($post['title']) ?></span>
<i class="ph ph-arrow-right" aria-hidden="true"></i>
</a>
</div>
</div>
</article>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php if ($totalPages > 1): ?>
<nav class="flex justify-center" aria-label="Blog post pages">
<div class="join">
<?php if ($page > 1): ?>
<a class="join-item btn btn-sm" rel="prev" href="<?= phpb_e($listingPath . '?' . http_build_query($searchParameters + ['page' => $page - 1])) ?>">Previous</a>
<?php else: ?>
<span class="join-item btn btn-sm btn-disabled" aria-disabled="true">Previous</span>
<?php endif; ?>
<span class="join-item btn btn-sm btn-disabled" aria-current="page">Page <?= phpb_e($page) ?> of <?= phpb_e($totalPages) ?></span>
<?php if ($page < $totalPages): ?>
<a class="join-item btn btn-sm" rel="next" href="<?= phpb_e($listingPath . '?' . http_build_query($searchParameters + ['page' => $page + 1])) ?>">Next</a>
<?php else: ?>
<span class="join-item btn btn-sm btn-disabled" aria-disabled="true">Next</span>
<?php endif; ?>
</div>
</nav>
<?php endif; ?>
</section>
+17
View File
@@ -0,0 +1,17 @@
import { rolldown } from 'rolldown';
const bundle = await rolldown({ input: 'admin/assets/src/markdown-editor.js' });
await bundle.write({
file: 'admin/assets/markdown-editor.js',
format: 'iife',
sourcemap: true,
minify: true,
});
const highlighterBundle = await rolldown({ input: 'assets/src/code-highlighter.js' });
await highlighterBundle.write({
file: 'assets/code-highlighter.js',
format: 'iife',
sourcemap: true,
minify: true,
});
+71
View File
@@ -0,0 +1,71 @@
<?php
return [
'title' => 'Blog',
'author' => 'Paul Spenke',
'identifier' => 'blog',
'licence' => 'MIT',
'version' => '1.0.0',
'assets' => [
[
'src' => '/assets/code-highlighter.css',
'type' => 'style',
'location' => 'footer',
],
[
'src' => '/assets/code-highlighter.js',
'type' => 'script',
'location' => 'footer',
],
[
'src' => '/assets/code-highlighter.css',
'type' => 'style',
'location' => 'admin-header',
],
[
'src' => '/assets/code-highlighter.js',
'type' => 'script',
'location' => 'admin-header',
],
[
'src' => '/admin/assets/markdown-editor.css',
'type' => 'style',
'location' => 'admin-header',
],
[
'src' => '/admin/assets/markdown-editor.js',
'type' => 'script',
'location' => 'admin-header',
],
],
'tables' => [
'posts' => [
'columns' => [
'title' => 'varchar(255) NOT NULL',
'slug' => 'varchar(191) NOT NULL',
'excerpt' => 'text NOT NULL',
'body' => 'longtext NOT NULL',
'featured_image_id' => 'varchar(50) NULL',
'category_id' => 'int NULL',
'status' => "varchar(20) NOT NULL DEFAULT 'draft'",
'published_at' => 'datetime NULL',
'created_at' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP',
'updated_at' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
],
'uniqueKeys' => [
'slug' => ['slug'],
],
],
'categories' => [
'columns' => [
'name' => 'varchar(255) NOT NULL',
'slug' => 'varchar(191) NOT NULL',
'created_at' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP',
'updated_at' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
],
'uniqueKeys' => [
'slug' => ['slug'],
],
],
],
];
+22
View File
@@ -0,0 +1,22 @@
<?php
use Plugi\Extensions;
Extensions::addRoutes([
'/ext--blog/save-post' => __DIR__ . '/routes/savePost.php',
'/ext--blog/preview-post' => __DIR__ . '/routes/previewPost.php',
'/ext--blog/delete-post' => __DIR__ . '/routes/deletePost.php',
'/ext--blog/save-category' => __DIR__ . '/routes/saveCategory.php',
'/ext--blog/delete-category' => __DIR__ . '/routes/deleteCategory.php',
]);
Extensions::addBlocks([
'post-list' => __DIR__ . '/blocks/post-list',
'post-detail' => __DIR__ . '/blocks/post-detail',
]);
Extensions::registerBackend('blog', [
'title' => 'Blog',
'include' => __DIR__ . '/admin/blog.php',
'icon' => '<i class="ph ph-article"></i>',
]);
+582
View File
@@ -0,0 +1,582 @@
{
"name": "plugi-ext-blog",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "plugi-ext-blog",
"dependencies": {
"@codemirror/commands": "^6.11.2",
"@codemirror/lang-markdown": "^6.5.3",
"@codemirror/language": "^6.13.1",
"@codemirror/view": "^6.44.2",
"@lezer/highlight": "^1.2.5",
"highlight.js": "^11.11.1"
},
"devDependencies": {
"rolldown": "^1.3.3"
}
},
"node_modules/@codemirror/autocomplete": {
"version": "6.20.4",
"resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.4.tgz",
"integrity": "sha512-yF8RhOf2SXlg00+qtupzLhrglcas61boqaONiNcbPIebHCpJocpqTBA6dyrtUrQO47hqyTdeob/3XnYilT7TaQ==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0"
}
},
"node_modules/@codemirror/commands": {
"version": "6.11.2",
"resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.11.2.tgz",
"integrity": "sha512-NbH6Q9lmcXvf9s5/mMJIwL2Hjl2NEdsN/dDlezGnaFOQgNZ59dT7ndKUf21/PIjJacD/Ti2Ifi4TsBkO6WHvsg==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.7.0",
"@codemirror/view": "^6.27.0",
"@lezer/common": "^1.1.0"
}
},
"node_modules/@codemirror/lang-css": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz",
"integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@lezer/common": "^1.0.2",
"@lezer/css": "^1.1.7"
}
},
"node_modules/@codemirror/lang-html": {
"version": "6.4.12",
"resolved": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.12.tgz",
"integrity": "sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/lang-css": "^6.0.0",
"@codemirror/lang-javascript": "^6.0.0",
"@codemirror/language": "^6.4.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0",
"@lezer/css": "^1.1.0",
"@lezer/html": "^1.3.12"
}
},
"node_modules/@codemirror/lang-javascript": {
"version": "6.2.5",
"resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz",
"integrity": "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.6.0",
"@codemirror/lint": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0",
"@lezer/javascript": "^1.0.0"
}
},
"node_modules/@codemirror/lang-markdown": {
"version": "6.5.3",
"resolved": "https://registry.npmjs.org/@codemirror/lang-markdown/-/lang-markdown-6.5.3.tgz",
"integrity": "sha512-gNfFYi5jS6JkWD5kLW3cXB3g2uMYec9wzjYurMLDHeB0P2Ppc/Qe8UtDv7EBR5BzPQbkaW3/50+7qLtS//1Pqw==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.7.1",
"@codemirror/lang-html": "^6.0.0",
"@codemirror/language": "^6.3.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.0.0",
"@lezer/common": "^1.2.1",
"@lezer/markdown": "^1.0.0"
}
},
"node_modules/@codemirror/language": {
"version": "6.13.1",
"resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.13.1.tgz",
"integrity": "sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/streamparser": "^6.0.0",
"@codemirror/view": "^6.23.0",
"@lezer/common": "^1.5.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0",
"style-mod": "^4.0.0"
}
},
"node_modules/@codemirror/lint": {
"version": "6.9.8",
"resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.8.tgz",
"integrity": "sha512-qNvtcE73xUto/D1RvtgSRI4A1Hg8ekxlvtZpjHpdpisLBnhyu82EUEJMEgaxkjuQCA8vqnrylENWKOsEDCOHcw==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.42.0",
"crelt": "^1.0.5"
}
},
"node_modules/@codemirror/state": {
"version": "6.7.6",
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.6.tgz",
"integrity": "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==",
"license": "MIT",
"dependencies": {
"@marijn/find-cluster-break": "^1.0.0"
}
},
"node_modules/@codemirror/streamparser": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/@codemirror/streamparser/-/streamparser-6.0.0.tgz",
"integrity": "sha512-JTFPF6xrfjt0mnfGPgzcLiMwYmvIyNaoizp8BYzv8FE8KrT6GBGDZ190rtt+O7Wke3gG/MFHyiY9YGNeimof4w==",
"license": "MIT"
},
"node_modules/@codemirror/view": {
"version": "6.44.2",
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.44.2.tgz",
"integrity": "sha512-7yxTh7+iCbxIV9QCJAVlkYjWV/TCHD0zmLIaIR3NOb47YpCWwVUuFUnHwkRC3z+8cXNgeJzrCy4QtlR3fVt5kg==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.7.0",
"crelt": "^1.0.6",
"style-mod": "^4.1.0",
"w3c-keyname": "^2.2.4"
}
},
"node_modules/@lezer/common": {
"version": "1.5.7",
"resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.7.tgz",
"integrity": "sha512-3+3PN+M/3xSjrlQz8/wBPOl+JYGJ+G37ZszHfnhphFwj41qPUPxsz4WEic3ZyVpL23rX1qefaGqz0lA7jGUqwg==",
"license": "MIT"
},
"node_modules/@lezer/css": {
"version": "1.3.9",
"resolved": "https://registry.npmjs.org/@lezer/css/-/css-1.3.9.tgz",
"integrity": "sha512-ZmzgvTOBdJWGIsY/ItAfN7UW8DV802oZG+jeG6E508SwEzz5YhuAajptpWPICvIyqYAD2+VjMdOS40GgGkyEOQ==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.3.0"
}
},
"node_modules/@lezer/highlight": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.5.tgz",
"integrity": "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.3.0"
}
},
"node_modules/@lezer/html": {
"version": "1.3.13",
"resolved": "https://registry.npmjs.org/@lezer/html/-/html-1.3.13.tgz",
"integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0"
}
},
"node_modules/@lezer/javascript": {
"version": "1.5.7",
"resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.7.tgz",
"integrity": "sha512-o3Rn+TzKuN25sdILOZFXi8hz4K/ed4OK0I+QrAi7Zzn3tXRBZmfsQrZpLX47ZYK/rZU8Vu4jLkz4SOSYRzBfjw==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.1.3",
"@lezer/lr": "^1.3.0"
}
},
"node_modules/@lezer/lr": {
"version": "1.4.13",
"resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.13.tgz",
"integrity": "sha512-Ez6qF9rXdnR/7hTcA6kHq1uTcPV+17hyUFjiHBVYNi0a81TgbkC0SwiNvxcuUMkvX7phuhTHo+QAXh9L2kjGdg==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.0.0"
}
},
"node_modules/@lezer/markdown": {
"version": "1.8.3",
"resolved": "https://registry.npmjs.org/@lezer/markdown/-/markdown-1.8.3.tgz",
"integrity": "sha512-rI5BN6IpWmigtUPwvWvFck8/nptMhyYshEKCnyponMu8B+lBlt1d9rMbwHm4ejS+wd1fwd6P7hgAWZirfZ1lYg==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.5.0",
"@lezer/highlight": "^1.0.0"
}
},
"node_modules/@marijn/find-cluster-break": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz",
"integrity": "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==",
"license": "MIT"
},
"node_modules/@oxc-project/types": {
"version": "0.160.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.160.0.tgz",
"integrity": "sha512-gw4k9syEmnckbOgw2A2FU1TBDdX9hfwV9jEn/uio65pguPzwWiXQS3OIJDMEhv9m06tj9XiEe6RoD0YA+LgreA==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/oxc-project"
}
},
"node_modules/@rolldown/binding-android-arm-eabi": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.3.4.tgz",
"integrity": "sha512-xCW8CkL/ualx/SbYqeG9iK87lJCZGDQ0soE+kaORJ0Bd+pHALyE4qK7BStmEAyYWLEzZ3/biSIpA6/7GDFvzIg==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-android-arm64": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.3.4.tgz",
"integrity": "sha512-5lifIO+b/prcM9sx/bkPN4w6UEToEfQ3gjhx0+0neuL+dkYskI792CfAq03T51jc8JFcaYXs2hi3l8RjiH/VWQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-darwin-arm64": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.3.4.tgz",
"integrity": "sha512-RCgxTI4AJQxhVF//BI3ImQOsXTHrF4Eg+f99jBy8WoETA2kSEGFxpnrVmW0leQq/2aBR4R5AC6csmy3rc66e3Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-darwin-x64": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.3.4.tgz",
"integrity": "sha512-zNPJVVPUaDEj+L0lImoK3rFv2b+Z5gNijI6DWu/fcD3/1TfmRXKb9ZyxbSN+2AhlctqjbNzUvCsMa+EBhnEM4Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-freebsd-x64": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.3.4.tgz",
"integrity": "sha512-upP6g7ZIRy5by1RDQ/EphHIdJ5xK0eUD7sUgfZFWJ49s4XdbYsIvIlAPtrFpayR70Hhf9J22lb4Pm8/9FhrZmg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-arm-gnueabihf": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.3.4.tgz",
"integrity": "sha512-SAX5C5+poMLCxu8dkPF6h5yst40rkzs+9Y3cbPn2OFSydmHjAEprrGi64zGgnYyPIVZfdGUFqJ2fJbfbnHI+mA==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-arm64-gnu": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.3.4.tgz",
"integrity": "sha512-nwHqdlRZS6GWBef3dG5/pMY6RNTBBUjj7s0Da+m6xsFpe7jx6IC46SLZcCu8f46JOfCovZmwnrz51EzGE+7Fyw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-arm64-musl": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.3.4.tgz",
"integrity": "sha512-Gr78X2ur/AgLCkmZgHffk/FerIX8S5zb/eII4bCcvJo0ANzeXhTShahdNbpnY6bpiszIAgIfiuKS9ziziWsamw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-ppc64-gnu": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.3.4.tgz",
"integrity": "sha512-o9Wcn8nWrsQasaBRYM4d//FwhlBsTJYWkPVlhlt6FwzpwEoovY4IopRZjk5Fq3+ntRuSDORJjF/nA8sFeF2q6w==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-s390x-gnu": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.3.4.tgz",
"integrity": "sha512-UDWu4jkVcx2kiBKm3Ec//4lVCbeTWj8gmJ9SyLWCdLWtTlyq7fQVeVV/14nXvRtSLErvJ2+yA/Ux5taS31Y17Q==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-x64-gnu": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.3.4.tgz",
"integrity": "sha512-W9mGtTa0w4fWh8RLMNPyaEhhcuqUfO07Q4I1bBc4PDMNg7gQSw0yPQNQ3D0qwbkXwxbyL4YrIzc8n6k1vuFExQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-x64-musl": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.3.4.tgz",
"integrity": "sha512-8B+ofyQZ7/aCmkqnyMonPr5zKLqMVNczhRGFNtdIuItiwNn8iQWJawMq2E58r7bxD1XEbtRRsULY/eCWwZQ01Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-openharmony-arm64": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.3.4.tgz",
"integrity": "sha512-TlD0FSZaC7o2B4NCe9V5N11ugTnhzTM9ksj4sgRLvrKosDzjEkvlsTX3ehkw4ZlPv8AADimZZTvJGEa16pfXug==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-wasm32-wasi": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.3.4.tgz",
"integrity": "sha512-jwO8P3o53ygo7b5061B7BeaJ1BGv3BKZ6jroFdw/01qWry7Z+qNBlDvulzbTle5s/A0Fc1FRgsTxrke9DvsSbA==",
"cpu": [
"wasm32"
],
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@oxc-project/types": "0.160.0"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
}
},
"node_modules/@rolldown/binding-win32-arm64-msvc": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.3.4.tgz",
"integrity": "sha512-8adGMrNtrdzi2WD1ozhYapER59gD8Q/DV6SCKJlyG2HqULPdeQUBvMa33lTsiEYwIqTZUaIU2MmvPp5f1wbtXA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-win32-x64-msvc": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.3.4.tgz",
"integrity": "sha512-rIMjtESdXJCIoOiUTroQ1Y1rjVDZkuUVRUxs3APX2vNv175D7TDWvzdELiIhzGq9cUNUFat+co+PTmPHPqSREg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/pluginutils": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz",
"integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==",
"dev": true,
"license": "MIT"
},
"node_modules/crelt": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz",
"integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==",
"license": "MIT"
},
"node_modules/highlight.js": {
"version": "11.12.0",
"resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.12.0.tgz",
"integrity": "sha512-nbfWpyRMcMrPMmDwJB+dhX/eiaPKtc2RB+0QZskqJ3WjRA/FDS0e9hZrx8EC/lbEv8gXy98FcDbNa/dspAaJMg==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/rolldown": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.4.tgz",
"integrity": "sha512-p2rq4bfBmF0M6yaR8+A89fbkBQynZI2fxUW4G07eq9kpctAkpo7q5BZ4X4Mo4XZ7HHROu33cX9PeopUFN6u+2Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"@oxc-project/types": "=0.160.0",
"@rolldown/pluginutils": "^1.0.0"
},
"bin": {
"rolldown": "bin/cli.mjs"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"optionalDependencies": {
"@rolldown/binding-android-arm-eabi": "1.3.4",
"@rolldown/binding-android-arm64": "1.3.4",
"@rolldown/binding-darwin-arm64": "1.3.4",
"@rolldown/binding-darwin-x64": "1.3.4",
"@rolldown/binding-freebsd-x64": "1.3.4",
"@rolldown/binding-linux-arm-gnueabihf": "1.3.4",
"@rolldown/binding-linux-arm64-gnu": "1.3.4",
"@rolldown/binding-linux-arm64-musl": "1.3.4",
"@rolldown/binding-linux-ppc64-gnu": "1.3.4",
"@rolldown/binding-linux-s390x-gnu": "1.3.4",
"@rolldown/binding-linux-x64-gnu": "1.3.4",
"@rolldown/binding-linux-x64-musl": "1.3.4",
"@rolldown/binding-openharmony-arm64": "1.3.4",
"@rolldown/binding-wasm32-wasi": "1.3.4",
"@rolldown/binding-win32-arm64-msvc": "1.3.4",
"@rolldown/binding-win32-x64-msvc": "1.3.4"
}
},
"node_modules/style-mod": {
"version": "4.1.5",
"resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.5.tgz",
"integrity": "sha512-WQ2llCZa9sZSkJA+aOwpg5DkfbAXFKGh//t3MRTBeruFiSBC+GXUmbBzrw3bXyboCWAbtCW9InDfBsXrRD/rAg==",
"license": "MIT"
},
"node_modules/w3c-keyname": {
"version": "2.2.8",
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
"integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
"license": "MIT"
}
}
}
+19
View File
@@ -0,0 +1,19 @@
{
"name": "plugi-ext-blog",
"type": "module",
"dependencies": {
"@codemirror/commands": "^6.11.2",
"@codemirror/lang-markdown": "^6.5.3",
"@codemirror/language": "^6.13.1",
"@codemirror/view": "^6.44.2",
"@lezer/highlight": "^1.2.5",
"highlight.js": "^11.11.1"
},
"devDependencies": {
"rolldown": "^1.3.3"
},
"scripts": {
"build": "node build.js",
"test": "node --test tests/CodeHighlighterTest.js"
}
}
@@ -0,0 +1,24 @@
<?php
phpb_requires_authenticated();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
exit();
}
if (!phpb_validate_csrf()) {
http_response_code(403);
exit();
}
$deleted = false;
try {
if (isset($_POST['id']) && is_string($_POST['id']) && ctype_digit($_POST['id']) && (int) $_POST['id'] > 0) {
$deleted = (new \Plugi\Extensions\Blog\CategoriesRepository())->destroy((int) $_POST['id']);
}
} catch (\Throwable) {
$deleted = false;
}
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'categories']), [
'message-type' => $deleted ? 'success' : 'error',
'message' => $deleted ? 'Category deleted; associated posts are uncategorized.' : 'The category could not be deleted.',
]);
@@ -0,0 +1,24 @@
<?php
phpb_requires_authenticated();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
exit();
}
if (!phpb_validate_csrf()) {
http_response_code(403);
exit();
}
$deleted = false;
try {
if (isset($_POST['id']) && is_string($_POST['id']) && ctype_digit($_POST['id']) && (int) $_POST['id'] > 0) {
$deleted = (new \Plugi\Extensions\Blog\PostsRepository())->destroy((int) $_POST['id']);
}
} catch (\Throwable) {
$deleted = false;
}
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'posts']), [
'message-type' => $deleted ? 'success' : 'error',
'message' => $deleted ? 'Post deleted.' : 'The post could not be deleted.',
]);
@@ -0,0 +1,35 @@
<?php
phpb_requires_authenticated();
$respond = static function (int $status, array $payload): void {
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
};
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
$respond(405, ['error' => 'Preview requests must use POST.']);
return;
}
if (!phpb_validate_csrf()) {
$respond(403, ['error' => 'The preview request could not be verified.']);
return;
}
$body = $_POST['body'] ?? null;
if (!is_string($body)) {
$respond(400, ['error' => 'A Markdown body is required.']);
return;
}
if (strlen($body) > 1000000) {
$respond(413, ['error' => 'The Markdown body is too large to preview.']);
return;
}
try {
$html = (new \Plugi\Extensions\Blog\PostContentRenderer())->render($body);
$respond(200, ['html' => $html]);
} catch (\Throwable) {
$respond(500, ['error' => 'The Markdown preview could not be rendered.']);
}
@@ -0,0 +1,30 @@
<?php
phpb_requires_authenticated();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
exit();
}
if (!phpb_validate_csrf()) {
http_response_code(403);
exit();
}
$categoriesRepository = new \Plugi\Extensions\Blog\CategoriesRepository();
$redirectUrl = phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'categories']);
$data = array_intersect_key($_POST, array_flip(['name', 'slug']));
try {
if (isset($_POST['id']) && is_string($_POST['id']) && ctype_digit($_POST['id']) && (int) $_POST['id'] > 0) {
$saved = $categoriesRepository->update(['id' => (int) $_POST['id']], $data);
} elseif (!isset($_POST['id'])) {
$saved = $categoriesRepository->create($data);
} else {
$saved = false;
}
$message = $saved ? ['message-type' => 'success', 'message' => 'Category saved.'] : ['message-type' => 'error', 'message' => 'The category could not be saved.'];
} catch (\InvalidArgumentException $exception) {
$message = ['message-type' => 'error', 'message' => $exception->getMessage()];
} catch (\Throwable) {
$message = ['message-type' => 'error', 'message' => 'The category could not be saved. Check that the slug is unique.'];
}
phpb_redirect($redirectUrl, $message);
@@ -0,0 +1,31 @@
<?php
phpb_requires_authenticated();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
exit();
}
if (!phpb_validate_csrf()) {
http_response_code(403);
exit();
}
$postsRepository = new \Plugi\Extensions\Blog\PostsRepository();
$redirectUrl = phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'posts']);
$fields = ['title', 'slug', 'excerpt', 'body', 'featured_image_id', 'category_id', 'status', 'published_at'];
$data = array_intersect_key($_POST, array_flip($fields));
try {
if (isset($_POST['id']) && is_string($_POST['id']) && ctype_digit($_POST['id']) && (int) $_POST['id'] > 0) {
$saved = $postsRepository->update(['id' => (int) $_POST['id']], $data);
} elseif (!isset($_POST['id'])) {
$saved = $postsRepository->create($data);
} else {
$saved = false;
}
$message = $saved ? ['message-type' => 'success', 'message' => 'Post saved.'] : ['message-type' => 'error', 'message' => 'The post could not be saved.'];
} catch (\InvalidArgumentException $exception) {
$message = ['message-type' => 'error', 'message' => $exception->getMessage()];
} catch (\Throwable) {
$message = ['message-type' => 'error', 'message' => 'The post could not be saved. Check that the slug is unique.'];
}
phpb_redirect($redirectUrl, $message);
@@ -0,0 +1,118 @@
<?php
namespace Plugi\Extensions\Blog {
class PostsRepository
{
public static int $instances = 0;
public function __construct()
{
self::$instances++;
throw new \RuntimeException('Preview must not access the posts repository.');
}
}
}
namespace {
require_once dirname(__DIR__) . '/admin/Classes/PostContentRenderer.php';
function assertPreviewRoute(bool $condition, string $message): void
{
if (!$condition) {
throw new RuntimeException($message);
}
}
$previewMarkdown = "## Preview\n\nSafe **source**.\n\n- list item\n\n---\n\n> Quoted text.\n\n```php\n<code>safe</code>\n```\n\n~~~php\" onclick=\"alert(1)\n<script>alert(1)</script>\n~~~";
if (($argv[1] ?? '') === '--child') {
$scenario = $argv[2] ?? '';
$GLOBALS['previewAuthenticated'] = $scenario !== 'unauthenticated';
$GLOBALS['previewCsrfValid'] = $scenario !== 'invalid-csrf';
function phpb_requires_authenticated(): void
{
if (!$GLOBALS['previewAuthenticated']) {
http_response_code(403);
exit();
}
}
function phpb_validate_csrf(): bool
{
return $GLOBALS['previewCsrfValid'];
}
register_shutdown_function(static function (): void {
echo "\n__STATUS__" . http_response_code() . "\n";
echo '__REPOSITORY_INSTANTIATIONS__' . \Plugi\Extensions\Blog\PostsRepository::$instances . "\n";
});
$_SERVER['REQUEST_METHOD'] = $scenario === 'non-post' ? 'GET' : 'POST';
$_POST = match ($scenario) {
'invalid-body' => ['body' => ['not', 'markdown']],
'oversized-body' => ['body' => str_repeat('x', 1000001)],
default => ['body' => $previewMarkdown],
};
include dirname(__DIR__) . '/routes/previewPost.php';
exit();
}
function requestPreviewRoute(string $scenario): array
{
$process = proc_open(
[PHP_BINARY, __FILE__, '--child', $scenario],
[0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']],
$pipes,
dirname(__DIR__, 3)
);
if (!is_resource($process)) {
throw new RuntimeException('Could not start the preview route test process.');
}
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
$error = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exitCode = proc_close($process);
if ($exitCode !== 0 || !preg_match('/\n__STATUS__(\d+)\n__REPOSITORY_INSTANTIATIONS__(\d+)\n$/', $output, $matches)) {
throw new RuntimeException('Preview route subprocess failed: ' . $error . $output);
}
$responseLength = strpos($output, "\n__STATUS__");
return [
'status' => (int) $matches[1],
'repository_instances' => (int) $matches[2],
'body' => substr($output, 0, $responseLength),
];
}
foreach ([
'unauthenticated' => 403,
'non-post' => 405,
'invalid-csrf' => 403,
'invalid-body' => 400,
'oversized-body' => 413,
] as $scenario => $expectedStatus) {
$response = requestPreviewRoute($scenario);
assertPreviewRoute($response['status'] === $expectedStatus, 'The preview route should reject ' . $scenario . ' requests.');
assertPreviewRoute($response['repository_instances'] === 0, 'Rejected preview requests must not access saved posts.');
if ($scenario !== 'unauthenticated') {
$payload = json_decode($response['body'], true);
assertPreviewRoute(is_array($payload) && isset($payload['error']), 'Rejected preview requests should return a JSON error.');
}
}
$response = requestPreviewRoute('valid');
$payload = json_decode($response['body'], true);
$expectedHtml = (new \Plugi\Extensions\Blog\PostContentRenderer())->render($previewMarkdown);
assertPreviewRoute($response['status'] === 200, 'A valid preview request should succeed.');
assertPreviewRoute($payload === ['html' => $expectedHtml], 'The preview should return shared renderer output as JSON.');
assertPreviewRoute(str_contains($payload['html'], '<ul class="list-disc') && str_contains($payload['html'], '<hr class="my-6 border-base-300">') && str_contains($payload['html'], '<blockquote') && str_contains($payload['html'], '<pre'), 'The live preview should render lists, horizontal rules, quotes, and code blocks.');
assertPreviewRoute(str_contains($payload['html'], '<code class="language-php">&lt;code&gt;safe&lt;/code&gt;</code>') && str_contains($payload['html'], '<code>&lt;script&gt;alert(1)&lt;/script&gt;</code>') && !str_contains($payload['html'], 'onclick='), 'The preview should keep safe language metadata, reject malformed labels, and escape code.');
assertPreviewRoute($response['repository_instances'] === 0, 'Preview rendering must not read or write saved posts.');
fwrite(STDOUT, "Blog preview route tests passed.\n");
}
@@ -0,0 +1,444 @@
<?php
use Plugi\Core\DB;
use Plugi\Extensions\Blog\CategoriesRepository;
use Plugi\Extensions\Blog\PostsRepository;
use Plugi\Repositories\UploadRepository;
require_once dirname(__DIR__, 3) . '/plugi-core/src/Extensions.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Core/DB.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Core/helpers.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Repositories/BaseRepository.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Repositories/UploadRepository.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/UploadedFile.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Contracts/PageContract.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Contracts/ThemeContract.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Page.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Modules/GrapesJS/PageRenderer.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Modules/GrapesJS/Block/BaseModel.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Modules/GrapesJS/Block/BaseController.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/ThemeBlock.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Modules/GrapesJS/Block/BlockRenderer.php';
require_once dirname(__DIR__) . '/admin/Classes/PostsRepository.php';
require_once dirname(__DIR__) . '/admin/Classes/CategoriesRepository.php';
require_once dirname(__DIR__) . '/admin/Classes/PostContentRenderer.php';
$blogConfig = require dirname(__DIR__) . '/config.php';
\Plugi\Extensions::registerConfig('blog', $blogConfig);
require_once dirname(__DIR__) . '/extension.php';
assertBlog(($blogConfig['tables']['posts']['columns']['featured_image_id'] ?? null) === 'varchar(50) NULL', 'Featured image metadata should be declared as nullable extension schema.');
class BlogTestDatabase extends DB
{
public function __construct()
{
$this->pdo = new PDO('sqlite::memory:');
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->databaseName = 'blog_test';
}
public function createSchema(): void
{
$this->query('CREATE TABLE test_ext__blog_posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title VARCHAR(255) NOT NULL,
slug VARCHAR(191) NOT NULL UNIQUE,
excerpt TEXT NOT NULL,
body TEXT NOT NULL,
featured_image_id VARCHAR(50) NULL,
category_id INTEGER NULL,
status VARCHAR(20) NOT NULL,
published_at DATETIME NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)');
$this->query('CREATE TABLE test_uploads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
public_id VARCHAR(50) NOT NULL UNIQUE,
original_file VARCHAR(512) NOT NULL,
mime_type VARCHAR(50) NOT NULL,
server_file VARCHAR(512) NOT NULL,
alt_text VARCHAR(1000) NOT NULL DEFAULT "",
folder VARCHAR(255) NOT NULL DEFAULT ""
)');
$this->query('CREATE TABLE test_ext__blog_categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(255) NOT NULL,
slug VARCHAR(191) NOT NULL UNIQUE,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)');
}
}
class BlogTestTheme implements \Plugi\Contracts\ThemeContract
{
public function getThemeBlocks()
{
return [];
}
public function getThemeLayouts()
{
return [];
}
public function getFolder()
{
return '';
}
}
function assertBlog(bool $condition, string $message): void
{
if (!$condition) {
throw new RuntimeException($message);
}
}
function expectBlogValidation(callable $callback, string $message): void
{
try {
$callback();
} catch (InvalidArgumentException) {
return;
}
throw new RuntimeException($message);
}
function renderBlogBlock(string $slug): string
{
$theme = new BlogTestTheme();
$page = new \Plugi\Page();
$themeBlock = new \Plugi\ThemeBlock($theme, \Plugi\Extensions::getBlock($slug), true, $slug);
return (new \Plugi\Modules\GrapesJS\Block\BlockRenderer($theme, $page))->render($themeBlock);
}
function renderBlogListing(): string
{
return renderBlogBlock('post-list');
}
function renderBlogDetail(?string $slug): string
{
$GLOBALS['phpb_route_parameters'] = $slug === null ? [] : ['slug' => $slug];
return renderBlogBlock('post-detail');
}
function renderBlogAdminList(): string
{
ob_start();
include dirname(__DIR__) . '/admin/Views/ListPosts.php';
return (string) ob_get_clean();
}
function renderBlogEditor(int $postId): string
{
$_GET = ['id' => (string) $postId];
ob_start();
include dirname(__DIR__) . '/admin/Views/EditPost.php';
return (string) ob_get_clean();
}
$_ENV['DATABASE_PREFIX'] = 'test_';
$phpb_db = new BlogTestDatabase();
$phpb_db->createSchema();
assertBlog(isset($phpb_db->getDBDefinition()['ext__blog_posts'], $phpb_db->getDBDefinition()['ext__blog_categories']), 'The blog tables should be included in the core database definition.');
assertBlog(isset(\Plugi\Extensions::getBackends()['ext--blog']), 'The blog admin backend should be registered.');
assertBlog(in_array('/admin/assets/markdown-editor.js', array_column($blogConfig['assets'], 'src'), true) && in_array('/admin/assets/markdown-editor.css', array_column($blogConfig['assets'], 'src'), true), 'The editor script and stylesheet should be registered as extension assets.');
$publicAssets = array_values(array_filter($blogConfig['assets'], fn(array $asset): bool => $asset['location'] === 'footer'));
$adminAssets = array_values(array_filter($blogConfig['assets'], fn(array $asset): bool => $asset['location'] === 'admin-header'));
assertBlog(in_array(['src' => '/assets/code-highlighter.css', 'type' => 'style', 'location' => 'footer'], $publicAssets, true) && in_array(['src' => '/assets/code-highlighter.js', 'type' => 'script', 'location' => 'footer'], $publicAssets, true), 'The highlighter assets should be registered for public pages.');
assertBlog(in_array(['src' => '/assets/code-highlighter.css', 'type' => 'style', 'location' => 'admin-header'], $adminAssets, true) && in_array(['src' => '/assets/code-highlighter.js', 'type' => 'script', 'location' => 'admin-header'], $adminAssets, true), 'The highlighter assets should be registered for admin pages.');
assertBlog(array_search('/assets/code-highlighter.js', array_column($adminAssets, 'src'), true) < array_search('/admin/assets/markdown-editor.js', array_column($adminAssets, 'src'), true), 'The admin highlighter should load before the Markdown editor.');
$highlighterSource = file_get_contents(dirname(__DIR__) . '/assets/src/code-highlighter.js');
$editorSource = file_get_contents(dirname(__DIR__) . '/admin/assets/src/markdown-editor.js');
assertBlog(str_contains($highlighterSource, 'highlightPage') && str_contains($highlighterSource, "document.addEventListener('DOMContentLoaded'"), 'The highlighter should initialize code blocks on initial page content.');
assertBlog(str_contains($editorSource, 'window.blogCodeHighlighter?.highlight(preview)'), 'The editor should highlight preview code after replacing its contents.');
assertBlog(count(array_intersect(['/ext--blog/save-post', '/ext--blog/preview-post', '/ext--blog/delete-post', '/ext--blog/save-category', '/ext--blog/delete-category'], array_keys(\Plugi\Extensions::getRoutes()))) === 5, 'Blog post and category routes should be registered.');
assertBlog(\Plugi\Extensions::getBlock('post-list') === dirname(__DIR__) . '/blocks/post-list', 'The published-post block should be registered.');
assertBlog((require dirname(__DIR__) . '/blocks/post-list/config.php')['cache'] === false, 'The listing block should avoid stale cached post data.');
assertBlog(\Plugi\Extensions::getBlock('post-detail') === dirname(__DIR__) . '/blocks/post-detail', 'The post-detail block should be registered.');
assertBlog((require dirname(__DIR__) . '/blocks/post-detail/config.php')['cache'] === false, 'The detail block should avoid stale route-specific output.');
$posts = new PostsRepository();
$categories = new CategoriesRepository();
$category = $categories->create(['name' => 'News', 'slug' => 'news']);
assertBlog(is_array($category) && (int) $category['id'] > 0, 'Category creation should return the new category.');
$phpb_db->query('INSERT INTO test_uploads (public_id, original_file, mime_type, server_file, alt_text) VALUES (?, ?, ?, ?, ?)', [
'blog-cover-1', 'cover.jpg', 'image/jpeg', 'cover.jpg', 'A "featured" & <cover>',
]);
$phpb_db->query('INSERT INTO test_uploads (public_id, original_file, mime_type, server_file, alt_text) VALUES (?, ?, ?, ?, ?)', [
'blog-document-1', 'notes.pdf', 'application/pdf', 'notes.pdf', 'A document',
]);
$post = $posts->create([
'title' => 'First post',
'slug' => 'first-post',
'excerpt' => 'A short summary',
'body' => 'Post body',
'featured_image_id' => 'blog-cover-1',
'category_id' => $category['id'],
'status' => 'published',
'published_at' => '',
]);
assertBlog(is_array($post) && $post['status'] === 'published', 'A valid published post should be created.');
assertBlog($post['published_at'] !== null, 'Publishing without a date should set the current publication timestamp.');
assertBlog($post['featured_image_id'] === 'blog-cover-1', 'A valid image upload reference should be persisted on the post.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Missing featured image', 'slug' => 'missing-featured-image', 'excerpt' => '', 'body' => 'Body', 'featured_image_id' => 'missing-upload', 'category_id' => '', 'status' => 'draft', 'published_at' => '',
]), 'Missing upload references should be rejected.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Non-image featured image', 'slug' => 'non-image-featured-image', 'excerpt' => '', 'body' => 'Body', 'featured_image_id' => 'blog-document-1', 'category_id' => '', 'status' => 'draft', 'published_at' => '',
]), 'Non-image upload references should be rejected.');
$olderPost = $posts->create([
'title' => 'Older published post',
'slug' => 'older-published-post',
'excerpt' => 'Older excerpt',
'body' => "## Markdown heading\n\nA **bold** and *emphasized* phrase with `inline code`, a [safe link](https://example.com), an [unsafe link](javascript:alert), and an [encoded unsafe link](java&#x73;cript:alert).\n\n- first item\n- second item\n\n1. first numbered item\n2. second numbered item\n\n![Inline &amp; &#93;](https://images.example/photo.jpg)\n![Unsafe JavaScript](javascript:alert)\n![Encoded JavaScript](java&#x73;cript:alert)\n![Unsafe data](data:text/html;base64,abc)\n\n<script>alert(\"x\")</script>&safe\n\n---\n\n> Quoted **text**.\n\n```php\n<script>alert(\"code\")</script>\n```\n\n~~~php\" onmouseover=\"alert(1)\n<script>alert(1)</script>\n~~~",
'category_id' => '',
'status' => 'published',
'published_at' => '2020-01-01T00:00',
]);
$pastPublication = date('Y-m-d\\TH:i', time() - 3600);
$datedPost = $posts->create([
'title' => 'Dated draft',
'slug' => 'dated-draft',
'excerpt' => '',
'body' => " Draft body\n",
'category_id' => '',
'status' => 'draft',
'published_at' => $pastPublication,
]);
$secondPost = $posts->create([
'title' => 'Second post',
'slug' => 'second-post',
'excerpt' => '',
'body' => '',
'category_id' => $category['id'],
'status' => 'draft',
'published_at' => '',
]);
$_ENV['BASE_URL'] = 'https://blog.example';
$phpb_config = ['website_manager' => ['url' => '/website-manager'], 'general' => ['uploads_url' => '/uploads']];
$publishedPosts = $posts->getPublishedForListing();
assertBlog(count($publishedPosts) === 2, 'The public listing should exclude drafts.');
assertBlog($publishedPosts[0]['slug'] === $post['slug'] && $publishedPosts[0]['category_name'] === 'News', 'Published posts should be newest first and include their category name.');
assertBlog($publishedPosts[1]['slug'] === $olderPost['slug'], 'Older published posts should follow newer posts.');
$editorHtml = renderBlogEditor((int) $post['id']);
assertBlog(str_contains($editorHtml, '<textarea id="post-body" name="body"') && str_contains($editorHtml, 'Post body'), 'The visible fallback textarea should retain and submit the stored body value.');
assertBlog(str_contains($editorHtml, 'id="post-body-toolbar"') && str_contains($editorHtml, 'data-format="bold"') && str_contains($editorHtml, 'data-format="heading"'), 'The editor should provide accessible Markdown formatting controls.');
assertBlog(str_contains($editorHtml, 'data-format="list"') && str_contains($editorHtml, 'data-format="ordered-list"') && str_contains($editorHtml, 'data-format="quote"') && str_contains($editorHtml, 'data-format="horizontal-rule"') && str_contains($editorHtml, 'data-format="code-block"'), 'The editor toolbar should offer unordered and ordered lists, quotes, horizontal rules, and code blocks.');
assertBlog(str_contains($editorHtml, 'id="post-body-editor"') && str_contains($editorHtml, 'id="post-body-preview"') && str_contains($editorHtml, 'id="post-body-view-tabs"'), 'The editor should include a CodeMirror mount and a preview toggle in the editor workspace.');
assertBlog(str_contains($editorHtml, 'data-view="write"') && str_contains($editorHtml, 'data-view="preview"') && str_contains($editorHtml, 'role="tabpanel"') && str_contains($editorHtml, 'aria-live="polite"'), 'The editor and preview tabs should expose accessible panels and status.');
assertBlog(str_contains($editorHtml, 'name="featured_image_id"') && str_contains($editorHtml, 'value="blog-cover-1" selected'), 'The editor should select a post featured image.');
assertBlog(!str_contains($editorHtml, 'notes.pdf'), 'The featured-image selector should omit non-image uploads.');
assertBlog(str_contains($editorHtml, 'id="post-inline-image"') && str_contains($editorHtml, 'id="insert-post-inline-image"'), 'The editor should offer a control for inserting inline images.');
assertBlog(str_contains($editorHtml, 'data-url="https://blog.example/uploads/blog-cover-1/cover.jpg"') && str_contains($editorHtml, 'data-alt="A &quot;featured&quot; &amp; &lt;cover&gt;"'), 'The inline picker should expose escaped media URL and alt metadata.');
assertBlog(str_contains($editorHtml, 'selectionStart') && str_contains($editorHtml, 'setRangeText'), 'The inline picker should insert Markdown at the textarea cursor.');
assertBlog(str_contains($editorHtml, 'window.blogMarkdownEditor.insertAtCursor(markdown)'), 'The inline picker should insert at the CodeMirror cursor when the editor is initialized.');
$listingHtml = renderBlogListing();
assertBlog(str_contains($listingHtml, 'href="https://blog.example/blog/first-post"'), 'The listing should link to the configured post detail URL.');
assertBlog(str_contains($listingHtml, 'src="https://blog.example/uploads/blog-cover-1/cover.jpg" alt="A &quot;featured&quot; &amp; &lt;cover&gt;"'), 'The public listing should display a featured image with escaped alt text.');
assertBlog(strpos($listingHtml, 'first-post') < strpos($listingHtml, 'older-published-post'), 'The rendered listing should preserve newest-first order.');
assertBlog(!str_contains($listingHtml, 'dated-draft') && !str_contains($listingHtml, 'second-post'), 'Draft posts should not appear in the rendered listing.');
$detailHtml = renderBlogDetail('older-published-post');
assertBlog(str_contains($detailHtml, '<h1 class="text-3xl font-bold tracking-tight text-base-content sm:text-4xl">Older published post</h1>'), 'The detail block should resolve a published post from the named slug route parameter.');
assertBlog(str_contains($detailHtml, '<h2 class="text-2xl font-bold tracking-tight">Markdown heading</h2>') && str_contains($detailHtml, '<strong>bold</strong>') && str_contains($detailHtml, '<em>emphasized</em>'), 'The detail block should render Markdown headings and emphasis.');
assertBlog(str_contains($detailHtml, '<a class="link link-hover" href="https://example.com">safe link</a>') && !str_contains($detailHtml, 'href="javascript:') && !str_contains($detailHtml, 'href="java'), 'The detail block should render safe links and reject unsafe protocols.');
assertBlog(str_contains($detailHtml, '<ul class="list-disc') && str_contains($detailHtml, '<li>first item</li>') && str_contains($detailHtml, '<li>second item</li>'), 'The detail block should render Markdown lists.');
assertBlog(str_contains($detailHtml, '<ol class="list-decimal') && str_contains($detailHtml, '<li>first numbered item</li>'), 'The detail block should render ordered Markdown lists.');
assertBlog(str_contains($detailHtml, '<code>inline code</code>'), 'The detail block should render inline code.');
assertBlog(str_contains($detailHtml, '<hr class="my-6 border-base-300">'), 'The detail block should render Markdown horizontal rules.');
assertBlog(str_contains($detailHtml, '<blockquote class="border-l-4 border-base-300 pl-4 text-base-content/80"><p>Quoted <strong>text</strong>.</p></blockquote>'), 'The detail block should render Markdown blockquotes with inline formatting.');
assertBlog(str_contains($detailHtml, '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code class="language-php">&lt;script&gt;alert(&quot;code&quot;)&lt;/script&gt;</code></pre>'), 'The detail block should add a language class and escape fenced code.');
assertBlog(str_contains($detailHtml, '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code>&lt;script&gt;alert(1)&lt;/script&gt;</code></pre>') && !str_contains($detailHtml, 'onmouseover='), 'Malformed fence info should not create attributes, and its code should remain escaped.');
assertBlog(str_contains($detailHtml, '<img src="https://images.example/photo.jpg" alt="Inline &amp; ]" class="max-w-full rounded-box">'), 'The detail block should render inline Markdown images with escaped alt text.');
assertBlog(!str_contains($detailHtml, 'src="javascript:') && !str_contains($detailHtml, 'src="java') && !str_contains($detailHtml, 'src="data:'), 'The detail block should reject unsafe image URL protocols.');
assertBlog(str_contains($detailHtml, '&lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;&amp;safe') && !str_contains($detailHtml, '<script>alert'), 'The detail block should escape raw HTML in post bodies.');
assertBlog(!str_contains($detailHtml, 'src="https://blog.example/uploads/blog-cover-1/cover.jpg"'), 'Posts without featured images should omit the featured-image URL.');
$plainTextHtml = renderBlogDetail('first-post');
assertBlog(str_contains($plainTextHtml, '<p>Post body</p>'), 'Existing plain-text post bodies should remain readable.');
assertBlog(str_contains($plainTextHtml, 'src="https://blog.example/uploads/blog-cover-1/cover.jpg" alt="A &quot;featured&quot; &amp; &lt;cover&gt;"'), 'The public detail block should display a featured image with escaped alt text.');
$phpb_db->query('INSERT INTO test_uploads (public_id, original_file, mime_type, server_file, alt_text) VALUES (?, ?, ?, ?, ?)', [
'blog-cover-deleted', 'deleted.jpg', 'image/jpeg', 'deleted.jpg', 'Deleted cover',
]);
$deletedCoverPost = $posts->create([
'title' => 'Deleted featured image', 'slug' => 'deleted-featured-image', 'excerpt' => '', 'body' => 'Body', 'featured_image_id' => 'blog-cover-deleted', 'category_id' => '', 'status' => 'published', 'published_at' => '2019-01-01T00:00',
]);
$phpb_db->query('DELETE FROM test_uploads WHERE public_id = ?', ['blog-cover-deleted']);
assertBlog(!str_contains(renderBlogDetail('deleted-featured-image'), '<img'), 'Deleted featured-image uploads should be omitted from public detail pages.');
assertBlog(!str_contains(renderBlogListing(), 'deleted.jpg'), 'Deleted featured-image uploads should be omitted from public post cards.');
$posts->destroy($deletedCoverPost['id']);
assertBlog(str_contains(renderBlogDetail(null), 'Article not found'), 'A missing route slug should render a not-found state.');
assertBlog(str_contains(renderBlogDetail('unknown-post'), 'Article not found'), 'An unknown route slug should render a not-found state.');
assertBlog(str_contains(renderBlogDetail('dated-draft'), 'Article not found'), 'An unpublished post should render a not-found state.');
assertBlog(str_contains(renderBlogDetail('second-post'), 'Article not found'), 'A draft post should render a not-found state.');
assertBlog($datedPost['published_at'] === str_replace('T', ' ', $pastPublication) . ':00', 'A valid local publication date should be normalized for storage.');
assertBlog($datedPost['body'] === " Draft body\n", 'Post body whitespace should be preserved.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Invalid date', 'slug' => 'invalid-date', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => 'not-a-date',
]), 'Invalid publication dates should be rejected.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Future date', 'slug' => 'future-date', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => date('Y-m-d\\TH:i', time() + 86400),
]), 'Future publication dates should be rejected.');
$updated = $posts->update(['id' => $post['id']], [
'title' => 'Updated post',
'slug' => 'updated-post',
'excerpt' => '',
'body' => 'Updated body',
'featured_image_id' => '',
'category_id' => '',
'status' => 'draft',
'published_at' => '',
]);
assertBlog($updated === true, 'An existing post should update.');
$updatedPost = $posts->findWithId($post['id']);
assertBlog($updatedPost['title'] === 'Updated post' && $updatedPost['category_id'] === null && $updatedPost['published_at'] === null && $updatedPost['featured_image_id'] === null, 'Post updates should persist edited fields and clear optional values.');
assertBlog(is_array($secondPost), 'A draft with an empty body should be saved.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Duplicate post', 'slug' => 'second-post', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => '',
]), 'Duplicate post slugs should be rejected.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Bad slug', 'slug' => 'Invalid Slug', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => '',
]), 'Invalid post slugs should be rejected.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Bad status', 'slug' => 'bad-status', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'scheduled', 'published_at' => '',
]), 'Unsupported post statuses should be rejected.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Missing category', 'slug' => 'missing-category', 'excerpt' => '', 'body' => '', 'category_id' => '999', 'status' => 'draft', 'published_at' => '',
]), 'Unknown categories should be rejected.');
expectBlogValidation(fn() => $posts->create([
'title' => 'No body', 'slug' => 'no-body', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'published', 'published_at' => '',
]), 'Published posts should require body content.');
expectBlogValidation(fn() => $categories->create(['name' => 'Duplicate', 'slug' => 'news']), 'Duplicate category slugs should be rejected.');
expectBlogValidation(fn() => $categories->create(['name' => 'Bad slug', 'slug' => 'not a slug']), 'Invalid category slugs should be rejected.');
$updatedCategory = $categories->update(['id' => $category['id']], ['name' => 'Announcements', 'slug' => 'announcements']);
assertBlog($updatedCategory === true, 'An existing category should update.');
assertBlog($categories->destroy($category['id']) === true, 'A category should be deleted.');
assertBlog($posts->findWithId($secondPost['id'])['category_id'] === null, 'Deleting a category should detach its posts.');
assertBlog($posts->destroy($secondPost['id']) === true, 'A post should be deleted.');
assertBlog($posts->destroy($datedPost['id']) === true, 'A dated post should be deleted.');
assertBlog($posts->destroy($olderPost['id']) === true, 'An older published post should be deleted.');
assertBlog($posts->destroy($post['id']) === true, 'The remaining draft should be deleted.');
assertBlog($categories->findWithId($category['id']) === null && $posts->findWithId($secondPost['id']) === null, 'Deleted records should no longer be found.');
assertBlog(str_contains(renderBlogListing(), 'No published posts yet.'), 'The listing should show an empty state when no posts are published.');
$phpb_config = ['website_manager' => ['url' => '/website-manager']];
$_GET = [];
assertBlog(str_contains(renderBlogAdminList(), 'No posts yet'), 'The admin list should show its empty-list state when no posts exist.');
for ($index = 1; $index <= 12; $index++) {
$number = str_pad((string) $index, 2, '0', STR_PAD_LEFT);
$batchPost = $posts->create([
'title' => 'Pagination batch ' . $number,
'slug' => 'pagination-batch-' . $number,
'excerpt' => 'Batch excerpt',
'body' => 'Batch body',
'category_id' => '',
'status' => $index === 12 ? 'draft' : 'published',
'published_at' => '2025-01-' . $number . 'T00:00',
]);
$phpb_db->query('UPDATE test_ext__blog_posts SET updated_at = ? WHERE id = ?', ['2025-02-' . $number . ' 00:00:00', $batchPost['id']]);
}
foreach ([
'title' => 'TitleSearchMarker',
'slug' => 'slugsearchmarker',
'excerpt' => 'ExcerptSearchMarker',
'body' => 'BodySearchMarker',
] as $field => $term) {
$fieldPost = [
'title' => 'Field-only test post',
'slug' => 'field-only-test-post',
'excerpt' => 'Field-only excerpt',
'body' => 'Field-only body',
'category_id' => '',
'status' => 'published',
'published_at' => '2025-03-01T00:00',
];
$fieldPost[$field] = $term;
$fieldPost['slug'] = $field === 'slug' ? $term : 'field-only-' . $field;
$fieldPost = $posts->create($fieldPost);
$adminMatch = $posts->getPageForAdmin($term, 1);
$publicMatch = $posts->getPageForListing($term, 1);
assertBlog($adminMatch['total'] === 1 && $adminMatch['posts'][0]['slug'] === $fieldPost['slug'], 'Admin search should match the ' . $field . ' field.');
assertBlog($publicMatch['total'] === 1 && $publicMatch['posts'][0]['slug'] === $fieldPost['slug'], 'Public search should match the ' . $field . ' field.');
}
foreach ([
['term' => '100%', 'match' => 'literal-percent', 'title' => 'Price 100% complete', 'decoy' => 'wildcard-percent-decoy', 'decoyTitle' => 'Price 100X complete'],
['term' => 'under_score', 'match' => 'literal-underscore', 'title' => 'under_score example', 'decoy' => 'wildcard-underscore-decoy', 'decoyTitle' => 'underXscore example'],
['term' => 'bang!mark', 'match' => 'literal-escape-character', 'title' => 'bang!mark example', 'decoy' => 'escape-character-decoy', 'decoyTitle' => 'bangXmark example'],
] as $literalSearch) {
foreach ([[$literalSearch['match'], $literalSearch['title']], [$literalSearch['decoy'], $literalSearch['decoyTitle']]] as [$slug, $title]) {
$posts->create([
'title' => $title,
'slug' => $slug,
'excerpt' => '',
'body' => 'Search wildcard regression test',
'category_id' => '',
'status' => 'published',
'published_at' => '2025-03-01T00:00',
]);
}
$adminMatch = $posts->getPageForAdmin($literalSearch['term'], 1);
$publicMatch = $posts->getPageForListing($literalSearch['term'], 1);
assertBlog($adminMatch['total'] === 1 && $adminMatch['posts'][0]['slug'] === $literalSearch['match'], 'Admin search should treat LIKE metacharacters literally.');
assertBlog($publicMatch['total'] === 1 && $publicMatch['posts'][0]['slug'] === $literalSearch['match'], 'Public search should treat LIKE metacharacters literally.');
}
$adminFirstPage = $posts->getPageForAdmin('pagination', 1);
$adminLastPage = $posts->getPageForAdmin('pagination', 2);
assertBlog($adminFirstPage['total'] === 12 && count($adminFirstPage['posts']) === 10, 'Admin pagination should report all matching posts and cap each page at ten.');
assertBlog($adminFirstPage['posts'][0]['slug'] === 'pagination-batch-12' && $adminFirstPage['posts'][9]['slug'] === 'pagination-batch-03', 'Admin pages should preserve the newest-updated-first order.');
assertBlog(count($adminLastPage['posts']) === 2 && $adminLastPage['posts'][0]['slug'] === 'pagination-batch-02', 'The admin final page should contain the remaining posts in order.');
assertBlog($posts->getPageForAdmin('pagination', 0)['posts'][0]['slug'] === 'pagination-batch-12', 'Invalid low page numbers should normalize to the first page.');
assertBlog($posts->getPageForAdmin('pagination', PHP_INT_MAX)['posts'][0]['slug'] === 'pagination-batch-02', 'Oversized page numbers should safely resolve to the last matching page.');
$publicFirstPage = $posts->getPageForListing('pagination', 1);
$publicLastPage = $posts->getPageForListing('pagination', 2);
assertBlog($publicFirstPage['total'] === 11 && count($publicFirstPage['posts']) === 10, 'Public pagination should exclude the matching draft and report published totals.');
assertBlog($publicFirstPage['posts'][0]['slug'] === 'pagination-batch-11', 'Public pages should preserve newest-published-first order.');
assertBlog(count($publicLastPage['posts']) === 1 && $publicLastPage['posts'][0]['slug'] === 'pagination-batch-01', 'The public final page should contain its remaining published post.');
$noMatches = $posts->getPageForAdmin("pagination' OR '1'='1", 1);
assertBlog($noMatches['total'] === 0 && $noMatches['posts'] === [], 'Search input should be treated as a value rather than SQL.');
$_SERVER['HTTPS'] = 'on';
$_SERVER['SERVER_NAME'] = 'blog.example';
$_SERVER['SERVER_PORT'] = 443;
$_ENV['BASE_URL'] = 'https://blog.example/app';
$_SERVER['REQUEST_URI'] = '/app/news?keep=old';
$_GET = ['q' => 'pagination', 'page' => '2'];
$publicSearchPage = renderBlogListing();
assertBlog(str_contains($publicSearchPage, 'Pagination batch 01') && !str_contains($publicSearchPage, 'Pagination batch 11'), 'The public block should render only the requested search page.');
assertBlog(str_contains($publicSearchPage, 'action="https://blog.example/app/news"') && str_contains($publicSearchPage, 'name="q" value="pagination"'), 'The public search form should submit to the current path and retain its search value.');
assertBlog(str_contains($publicSearchPage, 'href="https://blog.example/app/news?q=pagination&amp;page=1"') && str_contains($publicSearchPage, 'Page 2 of 2'), 'Public pagination should retain the search term and current page position.');
$_GET = ['q' => 'pagination', 'page' => '0'];
assertBlog(str_contains(renderBlogListing(), 'Pagination batch 11'), 'Invalid public page values should safely show the first page.');
$_GET = ['q' => 'no-such-post'];
$publicNoMatches = renderBlogListing();
assertBlog(str_contains($publicNoMatches, 'No published posts match &quot;no-such-post&quot;') && !str_contains($publicNoMatches, 'No published posts yet.'), 'The public block should distinguish no matches from an empty blog.');
$_GET = ['q' => 'pagination', 'page' => '99', 'posts_page' => '2'];
$adminSearchPage = renderBlogAdminList();
assertBlog(str_contains($adminSearchPage, 'Pagination batch 02') && str_contains($adminSearchPage, 'Pagination batch 01') && !str_contains($adminSearchPage, 'Pagination batch 12'), 'The admin list should render only the requested page.');
assertBlog(str_contains($adminSearchPage, 'name="tab" value="ext--blog"') && str_contains($adminSearchPage, 'name="q" value="pagination"'), 'The admin search form should retain the extension route and search term.');
assertBlog(str_contains($adminSearchPage, 'href="https://blog.example/app/website-manager?tab=ext--blog&amp;action=posts&amp;q=pagination&amp;posts_page=1"') && str_contains($adminSearchPage, 'Page 2 of 2'), 'Admin pagination should preserve the extension route, search term, and posts_page parameter.');
$_GET = ['q' => 'pagination', 'page' => '2', 'posts_page' => '1'];
$adminFirstPageHtml = renderBlogAdminList();
assertBlog(str_contains($adminFirstPageHtml, 'Pagination batch 12') && str_contains($adminFirstPageHtml, '>Draft</span>'), 'The admin list should include matching drafts.');
$_GET = ['q' => 'pagination', 'page' => '2', 'posts_page' => '0'];
assertBlog(str_contains(renderBlogAdminList(), 'Pagination batch 12'), 'Invalid admin page values should safely show the first page.');
$_GET = ['q' => 'no-such-post'];
$adminNoMatches = renderBlogAdminList();
assertBlog(str_contains($adminNoMatches, 'No posts found for &quot;no-such-post&quot;') && !str_contains($adminNoMatches, 'No posts yet'), 'The admin list should distinguish no matches from an empty post list.');
fwrite(STDOUT, "Blog repository tests passed.\n");
@@ -0,0 +1,44 @@
import assert from 'node:assert/strict';
import test from 'node:test';
const createCodeBlock = (className, text) => {
const classes = new Set(className.split(/\s+/).filter(Boolean));
const code = {
className: [...classes].join(' '),
children: [],
dataset: {},
innerHTML: '',
textContent: text,
classList: {
add(name) {
classes.add(name);
code.className = [...classes].join(' ');
},
},
};
return code;
};
globalThis.document = { readyState: 'complete', querySelectorAll: () => [] };
globalThis.window = {};
await import('../assets/src/code-highlighter.js');
test('unsupported language labels remain plain without interrupting later blocks', () => {
const unsupported = createCodeBlock('language-not-a-language', '<?php echo 1;');
const supported = createCodeBlock('language-php', '<?php echo 1;');
const warnings = [];
const originalWarn = console.warn;
console.warn = (...args) => warnings.push(args);
try {
window.blogCodeHighlighter.highlight({ querySelectorAll: () => [unsupported, supported] });
} finally {
console.warn = originalWarn;
}
assert.deepEqual(warnings, []);
assert.equal(unsupported.className, 'language-not-a-language');
assert.deepEqual(unsupported.dataset, {});
assert.equal(supported.dataset.highlighted, 'yes');
assert.match(supported.innerHTML, /<span class="hljs-/);
});
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2023 Paul Spenke
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -1,29 +1,36 @@
<?php
namespace Plugi\Extensions\Form\Finishers;
use Plugi\Extensions\Form\DefinitionsRepository;
class DefaultFinisher {
public $formId;
public $form;
public $data;
public function __construct()
public $submission;
public $options;
public function __construct(array $context = [], array $options = [])
{
$formRepository = new DefinitionsRepository();
$this->formId = $_GET['id'] ?? 0;
$this->form = $formRepository->findWithId($this->formId);
$this->data = file_get_contents('php://input');
$this->formId = $context['formId'] ?? null;
$this->form = $context['form'] ?? [];
$this->data = $context['rawData'] ?? '';
$this->submission = $context['submission'] ?? [];
$this->options = $options;
}
public function execute (): bool {
return true;
}
public function getFormFields (): array {
return json_decode($this->form['fields'], true);
return $this->form['formFields'] ?? [];
}
public function getEntryFields (): array {
return json_decode($this->data, true)['fields'];
return $this->submission['fields'] ?? [];
}
public function getFormName (): string {
return $this->form['name'];
return (string) ($this->form['name'] ?? '');
}
}
@@ -15,6 +15,19 @@ class FinishersRepository {
return $this->config['finishers'][$key] ?? null;
}
public function getEditorConfig(): array
{
$editorConfig = [];
foreach ($this->config['finishers'] as $key => $config) {
$editorConfig[$key] = [
'label' => $config['label'] ?? $key,
'settings' => $config['settings'] ?? [],
];
}
return $editorConfig;
}
public function finisherExists (string $key) : bool
{
return array_key_exists($key, $this->config['finishers']);
@@ -6,10 +6,9 @@ class SaveEntryToDatabase extends DefaultFinisher
public function execute(): bool
{
$entriesRepository = new \Plugi\Extensions\Form\EntriesRepository();
$entriesRepository->create([
return $entriesRepository->create([
'formId' => $this->formId,
'data' => $this->data,
]);
return true;
]) !== null;
}
}
@@ -0,0 +1,44 @@
<?php
namespace Plugi\Extensions\Form\Finishers;
class SendConfirmationEmailToSubmitter extends DefaultFinisher
{
public function execute(): bool
{
$recipientField = $this->options['recipientField'] ?? null;
if (!is_string($recipientField) || $recipientField === '') {
return false;
}
$emailFieldExists = false;
foreach ($this->getFormFields() as $field) {
if (($field['name'] ?? null) === $recipientField && ($field['type'] ?? null) === 'email') {
$emailFieldExists = true;
break;
}
}
if (!$emailFieldExists) {
return false;
}
$recipient = $this->getEntryFields()[$recipientField] ?? null;
if (!is_string($recipient) || filter_var($recipient, FILTER_VALIDATE_EMAIL) === false) {
return false;
}
$subject = $this->options['subject'] ?? null;
$message = $this->options['message'] ?? null;
if (!is_string($subject) || trim($subject) === '' || strpbrk($subject, "\r\n") !== false || !is_string($message) || trim($message) === '') {
return false;
}
return $this->sendMail($recipient, $subject, $message);
}
protected function sendMail(string $recipient, string $subject, string $message): bool
{
$mailer = phpb_instance('mail');
return $mailer !== null && $mailer->send($recipient, $subject, $message) === true;
}
}
@@ -7,21 +7,45 @@ class SendEmailToAdmin extends DefaultFinisher
{
public function execute(): bool
{
$to = Extensions::getSettings('form')['email']['value'];
$subject = 'Formulareinsendung: '.$this->getFormName();
$settings = Extensions::getSettings('form');
$to = $this->options['recipient'] ?? '';
if (!is_string($to)) {
return false;
}
if (trim($to) === '') {
$to = $settings['email']['value'] ?? null;
}
if (!is_string($to) || filter_var($to, FILTER_VALIDATE_EMAIL) === false) {
return false;
}
$subject = $this->options['subject'] ?? '';
if (!is_string($subject)) {
return false;
}
if (trim($subject) === '') {
$subject = 'Form submission: '.$this->getFormName();
}
if (strpbrk($subject, "\r\n") !== false) {
return false;
}
$message = $this->getNiceFields();
return mail(
$to,
$subject,
$message,
$additional_headers = [],
$additional_params = ""
);
$mailer = phpb_instance('mail');
return $mailer !== null && $mailer->send($to, $subject, $message) === true;
}
private function getNiceFields(): string {
$text = '';
foreach ($this->getFormFields() as $field) {
$text .= $field['label'] . ': ' . $this->getEntryFields()[$field['name']] . "\n";
$name = $field['name'] ?? '';
$label = $field['label'] ?? $name;
$value = $this->getEntryFields()[$name] ?? '';
if (is_array($value)) {
$value = implode(', ', array_map('strval', $value));
} elseif (!is_scalar($value)) {
$value = '';
}
$text .= $label . ': ' . $value . "\n";
}
return $text;
}
@@ -0,0 +1,108 @@
<?php
namespace Plugi\Extensions\Form\Finishers;
class SendWebhook extends DefaultFinisher
{
public function execute(): bool
{
$url = $this->options['url'] ?? null;
$method = $this->options['method'] ?? 'POST';
$bearerToken = $this->options['bearerToken'] ?? '';
$timeout = filter_var($this->options['timeout'] ?? null, FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1, 'max_range' => 30],
]);
if (!is_string($url) || !$this->isValidUrl($url)
|| !is_string($method) || !in_array($method, ['POST', 'PUT'], true)
|| !is_string($bearerToken) || strlen($bearerToken) > 4096
|| preg_match('/\A[\x21-\x7E]*\z/', $bearerToken) !== 1
|| $timeout === false
) {
return false;
}
$payload = json_encode([
'formId' => $this->formId,
'formName' => $this->getFormName(),
'fields' => $this->getEntryFields(),
], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
if (!is_string($payload)) {
return false;
}
$responseCode = $this->sendRequest($url, $method, $bearerToken !== '' ? $bearerToken : null, $payload, $timeout);
return $responseCode !== null && $responseCode >= 200 && $responseCode < 300;
}
private function isValidUrl(string $url): bool
{
if (strlen($url) > 2048 || filter_var($url, FILTER_VALIDATE_URL) === false
|| preg_match('/[\r\n\x00-\x20\x7F]/', $url) === 1
) {
return false;
}
$parts = parse_url($url);
if (!is_array($parts) || !isset($parts['scheme'], $parts['host'])
|| !in_array(strtolower($parts['scheme']), ['http', 'https'], true)
|| isset($parts['user']) || isset($parts['pass']) || isset($parts['fragment'])
) {
return false;
}
if (isset($parts['port']) && ($parts['port'] < 1 || $parts['port'] > 65535)) {
return false;
}
$host = $parts['host'];
if (filter_var($host, FILTER_VALIDATE_IP) !== false) {
return true;
}
return preg_match('/\A(?=.{1,253}\z)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)(?:\.(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?))*\z/', $host) === 1;
}
protected function sendRequest(string $url, string $method, ?string $bearerToken, string $payload, int $timeout): ?int
{
$headers = "Content-Type: application/json\r\nAccept: application/json";
if ($bearerToken !== null) {
$headers .= "\r\nAuthorization: Bearer " . $bearerToken;
}
$host = parse_url($url, PHP_URL_HOST);
$context = stream_context_create([
'http' => [
'method' => $method,
'header' => $headers,
'content' => $payload,
'timeout' => $timeout,
'ignore_errors' => true,
'follow_location' => 0,
'max_redirects' => 0,
'protocol_version' => 1.1,
],
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
'peer_name' => $host,
'SNI_enabled' => true,
],
]);
$stream = @fopen($url, 'r', false, $context);
if (!is_resource($stream)) {
return null;
}
$metadata = stream_get_meta_data($stream);
fclose($stream);
foreach ($metadata['wrapper_data'] ?? [] as $statusLine) {
if (is_string($statusLine) && preg_match('/\AHTTP\/\d(?:\.\d)?\s+(\d{3})(?:\s|\z)/', $statusLine, $matches) === 1) {
$responseCode = (int) $matches[1];
}
}
return $responseCode ?? null;
}
}
@@ -4,11 +4,95 @@ return [
'finishers' => [
'saveToDatabase' => [
'class' => \Plugi\Extensions\Form\Finishers\SaveEntryToDatabase::class,
'label' => 'In Datenbank speichern'
'label' => 'Save to database',
'settings' => [],
],
'sendMailToAdmin' => [
'class' => \Plugi\Extensions\Form\Finishers\SendEmailToAdmin::class,
'label' => 'Email an Admin senden'
]
'label' => 'Send email to admin',
'settings' => [
[
'name' => 'recipient',
'label' => 'Recipient email',
'type' => 'email',
'default' => '',
'placeholder' => 'Uses the form extension default when blank',
],
[
'name' => 'subject',
'label' => 'Subject',
'type' => 'text',
'default' => '',
'placeholder' => 'Uses the form name when blank',
],
],
],
'sendConfirmationEmailToSubmitter' => [
'class' => \Plugi\Extensions\Form\Finishers\SendConfirmationEmailToSubmitter::class,
'label' => 'Send confirmation email to submitter',
'settings' => [
[
'name' => 'recipientField',
'label' => 'Recipient email field',
'type' => 'emailField',
'default' => '',
'required' => true,
],
[
'name' => 'subject',
'label' => 'Subject',
'type' => 'text',
'default' => 'Thank you for your submission',
'required' => true,
],
[
'name' => 'message',
'label' => 'Message',
'type' => 'textarea',
'default' => 'Thank you for contacting us. We have received your message.',
'required' => true,
],
],
],
'sendWebhook' => [
'class' => \Plugi\Extensions\Form\Finishers\SendWebhook::class,
'label' => 'Send webhook',
'settings' => [
[
'name' => 'url',
'label' => 'Webhook URL',
'type' => 'url',
'default' => '',
'required' => true,
'placeholder' => 'https://example.com/webhook',
'help' => 'Receives a JSON object with the form ID, form name, and submitted fields.',
],
[
'name' => 'method',
'label' => 'HTTP method',
'type' => 'select',
'default' => 'POST',
'options' => [
['value' => 'POST', 'label' => 'POST'],
['value' => 'PUT', 'label' => 'PUT'],
],
],
[
'name' => 'bearerToken',
'label' => 'Bearer token (optional)',
'type' => 'password',
'default' => '',
],
[
'name' => 'timeout',
'label' => 'Timeout (seconds)',
'type' => 'number',
'default' => 10,
'min' => 1,
'max' => 30,
'required' => true,
],
],
],
]
];
@@ -0,0 +1,262 @@
<?php
namespace Plugi\Extensions\Form;
use Plugi\Extensions\Form\Finishers\DefaultFinisher;
use Plugi\Extensions\Form\Finishers\FinishersRepository;
class SubmissionHandler
{
public const MAX_REQUEST_BYTES = 65536;
public const MAX_FIELD_BYTES = 16384;
public const MAX_FIELDS = 100;
private $formsRepository;
private $finishersRepository;
private $rateLimiter;
public function __construct($formsRepository = null, $finishersRepository = null, $rateLimiter = null)
{
$this->formsRepository = $formsRepository ?? new DefinitionsRepository();
$this->finishersRepository = $finishersRepository ?? new FinishersRepository();
$this->rateLimiter = $rateLimiter ?? new SubmissionRateLimiter();
}
public function handle($formId, string $rawData): array
{
if (strlen($rawData) > self::MAX_REQUEST_BYTES) {
return $this->failure(413, ['The submission is too large.']);
}
$formId = filter_var($formId, FILTER_VALIDATE_INT);
if ($formId === false || $formId < 1) {
return $this->failure(400, ['A valid form id is required.']);
}
$clientIp = $_SERVER['REMOTE_ADDR'] ?? '';
if (!is_string($clientIp) || filter_var($clientIp, FILTER_VALIDATE_IP) === false) {
$clientIp = 'unknown';
}
try {
if (!$this->rateLimiter->consume($formId, $clientIp)) {
return $this->failure(429, ['Too many submissions. Please try again later.']);
}
} catch (\Throwable $exception) {
return $this->failure(503, ['Submissions are temporarily unavailable.']);
}
try {
$form = $this->formsRepository->findWithId($formId);
} catch (\Throwable $exception) {
return $this->failure(500, ['The form could not be loaded.']);
}
if (!$form) {
return $this->failure(404, ['The requested form was not found.']);
}
$form = (array) $form;
$payload = json_decode($rawData, true);
if (json_last_error() !== JSON_ERROR_NONE || !is_array($payload) || !isset($payload['fields']) || !is_array($payload['fields'])) {
return $this->failure(400, ['The submission payload is invalid.']);
}
foreach (array_keys($payload) as $key) {
if ($key !== 'fields') {
return $this->failure(400, ['The submission payload contains unsupported data.']);
}
}
$formFields = json_decode($form['fields'] ?? '', true);
if (json_last_error() !== JSON_ERROR_NONE || !is_array($formFields) || !$this->isList($formFields)) {
return $this->failure(422, ['The form fields configuration is invalid.']);
}
$fieldErrors = $this->validateFormFields($formFields, $payload['fields']);
if ($fieldErrors) {
return $this->failure(422, $fieldErrors);
}
$finisherEntries = json_decode($form['finishers'] ?? '', true);
if (json_last_error() !== JSON_ERROR_NONE || !is_array($finisherEntries) || !$this->isList($finisherEntries)) {
return $this->failure(422, ['The form actions configuration is invalid.']);
}
$configuredFinishers = [];
foreach ($finisherEntries as $entry) {
if (!is_array($entry) || !isset($entry['type']) || !is_string($entry['type']) || $entry['type'] === '') {
return $this->failure(422, ['The form contains an invalid action entry.']);
}
foreach (array_keys($entry) as $key) {
if ($key !== 'type' && $key !== 'options') {
return $this->failure(422, ['The form contains unsupported action settings.']);
}
}
$options = array_key_exists('options', $entry) ? $entry['options'] : [];
if (!is_array($options) || !$this->finishersRepository->finisherExists($entry['type'])) {
return $this->failure(422, ['The form contains an unknown or invalid action.']);
}
$config = $this->finishersRepository->getFinisherConfig($entry['type']);
$class = $config['class'] ?? null;
if (!is_string($class) || !is_subclass_of($class, DefaultFinisher::class)) {
return $this->failure(422, ['The form contains an invalid action configuration.']);
}
$configuredFinishers[] = [
'type' => $entry['type'],
'class' => $class,
'options' => $options,
];
}
$form['formFields'] = $formFields;
$context = [
'formId' => $formId,
'form' => $form,
'rawData' => $rawData,
'submission' => $payload,
];
$actions = [];
foreach ($configuredFinishers as $finisher) {
$success = false;
try {
$instance = new $finisher['class']($context, $finisher['options']);
$success = $instance->execute() === true;
} catch (\Throwable $exception) {
$success = false;
}
$actions[] = [
'type' => $finisher['type'],
'success' => $success,
];
}
$success = !in_array(false, array_column($actions, 'success'), true);
$body = [
'success' => $success,
'actions' => $actions,
'errors' => $success ? [] : ['One or more actions could not be completed.'],
];
return [
'status' => $success ? 200 : 500,
'body' => $body,
];
}
private function validateFormFields(array $formFields, array $submittedFields): array
{
$errors = [];
$knownFields = [];
$supportedTypes = ['text', 'email', 'textarea', 'checkbox', 'radio', 'select'];
if (count($submittedFields) > self::MAX_FIELDS) {
return ['The submission contains too many fields.'];
}
foreach ($formFields as $field) {
if (!is_array($field) || !isset($field['name']) || !is_string($field['name']) || trim($field['name']) === '' || !isset($field['label']) || !is_string($field['label']) || !isset($field['type']) || !is_string($field['type']) || !in_array($field['type'], $supportedTypes, true)) {
return ['The form contains an invalid field configuration.'];
}
$name = $field['name'];
if (array_key_exists($name, $knownFields)) {
return ['The form contains duplicate field names.'];
}
if (array_key_exists('required', $field) && !is_bool($field['required'])) {
return ['The form contains an invalid required-field setting.'];
}
$options = array_key_exists('options', $field) ? $field['options'] : [];
if (!is_array($options) || !$this->isList($options)) {
return ['The form contains invalid field options.'];
}
$optionValues = [];
foreach ($options as $option) {
if (!is_array($option) || !isset($option['label']) || !is_string($option['label']) || !isset($option['value']) || !is_scalar($option['value'])) {
return ['The form contains invalid field options.'];
}
$optionValues[] = (string) $option['value'];
}
$knownFields[$name] = [
'type' => $field['type'],
'required' => $field['required'] ?? false,
'options' => $optionValues,
];
}
foreach (array_keys($submittedFields) as $name) {
if (!is_string($name) || !array_key_exists($name, $knownFields)) {
return ['The submission contains an unknown field.'];
}
$value = $submittedFields[$name];
if (is_string($value) && strlen($value) > self::MAX_FIELD_BYTES) {
return ['A submitted field is too large.'];
}
if (is_array($value)) {
if (count($value) > self::MAX_FIELDS) {
return ['A submitted field contains too many values.'];
}
foreach ($value as $item) {
if (is_string($item) && strlen($item) > self::MAX_FIELD_BYTES) {
return ['A submitted field is too large.'];
}
}
}
}
foreach ($knownFields as $name => $field) {
$value = $submittedFields[$name] ?? null;
$empty = $value === null || $value === false || (is_string($value) && trim($value) === '') || (is_array($value) && count($value) === 0);
if ($field['required'] && $empty) {
$errors[] = 'A value is required for ' . $name . '.';
continue;
}
if ($empty) {
continue;
}
if ($field['type'] === 'checkbox') {
$values = is_array($value) ? $value : [$value];
foreach ($values as $selectedValue) {
if (!is_string($selectedValue) && !is_int($selectedValue)) {
$errors[] = 'The value for ' . $name . ' is invalid.';
break;
}
if (!in_array((string) $selectedValue, $field['options'], true)) {
$errors[] = 'The value for ' . $name . ' is invalid.';
break;
}
}
continue;
}
if (!is_string($value) && !is_int($value) && !is_float($value)) {
$errors[] = 'The value for ' . $name . ' is invalid.';
continue;
}
if (($field['type'] === 'select' || $field['type'] === 'radio') && !in_array((string) $value, $field['options'], true)) {
$errors[] = 'The value for ' . $name . ' is invalid.';
}
if ($field['type'] === 'email' && filter_var($value, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'The email value for ' . $name . ' is invalid.';
}
}
return $errors;
}
private function failure(int $status, array $errors): array
{
return [
'status' => $status,
'body' => [
'success' => false,
'actions' => [],
'errors' => $errors,
],
];
}
private function isList(array $values): bool
{
return $values === [] || array_keys($values) === range(0, count($values) - 1);
}
}
@@ -0,0 +1,79 @@
<?php
namespace Plugi\Extensions\Form;
use RuntimeException;
class SubmissionRateLimiter
{
private const MAX_SUBMISSIONS = 5;
private const WINDOW_SECONDS = 600;
private $db;
private string $table;
public function __construct($db = null)
{
global $phpb_db;
$this->db = $db ?? $phpb_db ?? null;
$prefix = preg_replace('/[^a-zA-Z0-9_]/', '', $_ENV['DATABASE_PREFIX'] ?? '');
$this->table = '`' . $prefix . 'ext__form_submission_limits`';
}
public function consume(int $formId, string $clientIp): bool
{
if (!is_object($this->db)) {
throw new RuntimeException('The submission rate limit store is unavailable.');
}
$now = time();
$ipHash = hash('sha256', $clientIp);
if (!$this->db->query(
"INSERT IGNORE INTO {$this->table} (formId, ipHash, startedAt, submissions) VALUES (?, ?, ?, 0)",
[$formId, $ipHash, $now]
)) {
throw new RuntimeException('The submission rate limit could not be initialized.');
}
$allowed = $this->db->transaction(function () use ($formId, $ipHash, $now): bool {
$rows = $this->db->select(
"SELECT startedAt, submissions FROM {$this->table} WHERE formId = ? AND ipHash = ? FOR UPDATE",
[$formId, $ipHash]
);
if (empty($rows)) {
throw new RuntimeException('The submission rate limit could not be loaded.');
}
$startedAt = (int) $rows[0]['startedAt'];
$submissions = (int) $rows[0]['submissions'];
if ($now - $startedAt >= self::WINDOW_SECONDS) {
$startedAt = $now;
$submissions = 0;
}
if ($submissions >= self::MAX_SUBMISSIONS) {
return false;
}
if (!$this->db->query(
"UPDATE {$this->table} SET startedAt = ?, submissions = ? WHERE formId = ? AND ipHash = ?",
[$startedAt, $submissions + 1, $formId, $ipHash]
)) {
throw new RuntimeException('The submission rate limit could not be updated.');
}
return true;
});
if ($allowed && random_int(1, 100) === 1) {
try {
$this->db->query(
"DELETE FROM {$this->table} WHERE startedAt < ?",
[$now - (self::WINDOW_SECONDS * 2)]
);
} catch (\Throwable $exception) {
}
}
return $allowed;
}
}
+195 -115
View File
@@ -1,11 +1,14 @@
<?php
use Plugi\Extensions\Form\DefinitionsRepository;
use Plugi\Extensions\Form\Finishers\FinishersRepository;
$formsRepository = new DefinitionsRepository();
$finisherRepository = new FinishersRepository();
$finisherDefinitions = $finisherRepository->getEditorConfig();
$form = [
'name' => "Neues Formular",
'name' => "New Form",
'fields' => "[]",
'finishers' => "[]",
];
@@ -14,36 +17,42 @@ if(isset($_GET['id']))
$form = $formsRepository->findWithId($_GET['id']);
$isEditing = isset($form['id']) && $form['id'] > 0;
$fieldsJson = json_encode(json_decode($form['fields']) ?? [], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
$finishersJson = json_encode(json_decode($form['finishers']) ?? [], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
$fieldsJson = $fieldsJson === false ? '[]' : $fieldsJson;
$finishersJson = $finishersJson === false ? '[]' : $finishersJson;
?>
<div class="mb-6">
<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="?tab=ext--form" class="btn btn-ghost btn-sm btn-circle">
<i class="ph-duotone ph-arrow-left text-xl"></i>
<a href="?tab=ext--form" class="btn btn-ghost btn-square btn-sm" aria-label="Back to forms" title="Back to forms">
<i class="ph-duotone ph-arrow-left text-xl" aria-hidden="true"></i>
</a>
<div>
<h2 class="text-xl font-bold"><?= $isEditing ? 'Formular bearbeiten' : 'Neues Formular' ?></h2>
<p class="text-sm text-base-content/60"><?= $isEditing ? 'Ändere die Einstellungen deines Formulars.' : 'Erstelle ein neues Formular mit Feldern und Aktionen.' ?></p>
<div class="space-y-1">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-primary">Form builder</p>
<h2 class="text-xl font-bold tracking-tight"><?= $isEditing ? 'Edit form' : 'New form' ?></h2>
<p class="text-sm text-base-content/60"><?= $isEditing ? 'Change your form settings.' : 'Create a new form with fields and actions.' ?></p>
</div>
</div>
</div>
<span class="badge badge-outline self-start sm:self-center"><?= $isEditing ? 'Editing form' : 'New form' ?></span>
</header>
<script>
const fields = <?= $form["fields"] ?>;
const finishers = <?= $form["finishers"] ?>;
const fields = <?= $fieldsJson ?>;
const finishers = <?= $finishersJson ?>;
const finisherDefinitions = <?= json_encode($finisherDefinitions, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;
</script>
<form action="/ext--form/save-form" method="post" x-data="{
<form action="/ext--form/save-form" method="post" class="space-y-6" x-data="{
fields: fields,
finishers: finishers,
defaultField: {name: 'formularfeld', label: 'Formularfeld', type: 'text', required: false, options: []},
defaultFinisher: {type: 'saveToDatabase'},
defaultField: {name: 'form_field', label: 'Form field', type: 'text', required: false, options: []},
dragIndex: null,
addField() {
const nextNum = this.fields.length + 1;
this.fields.push({
name: 'feld_' + nextNum,
label: 'Feld ' + nextNum,
name: 'field_' + nextNum,
label: 'Field ' + nextNum,
type: 'text',
required: false,
options: []
@@ -52,23 +61,44 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
getValidationErrors(field, index) {
const errors = [];
if (!field.name || !field.name.trim()) {
errors.push('Feldname darf nicht leer sein.');
errors.push('Field name cannot be empty.');
}
if (!field.label || !field.label.trim()) {
errors.push('Beschriftung darf nicht leer sein.');
errors.push('Label cannot be empty.');
}
// Check for duplicate names
const nameCount = this.fields.filter((f, i) => i !== index && f.name && f.name.trim() === field.name && field.name.trim() !== '').length;
if (nameCount > 0) {
errors.push('Feldname wird bereits verwendet.');
errors.push('Field name is already in use.');
}
return errors;
},
getOptionsLabel(type) {
if (type === 'select') return 'Dropdown-Optionen';
if (type === 'checkbox') return 'Checkbox-Optionen (mehrfach wählbar)';
if (type === 'radio') return 'Radio-Optionen (einzeln wählbar)';
return 'Optionen';
if (type === 'select') return 'Dropdown options';
if (type === 'checkbox') return 'Checkbox options (multiple selections)';
if (type === 'radio') return 'Radio options (single selection)';
return 'Options';
},
getFinisherSettings(type) {
return finisherDefinitions[type]?.settings ?? [];
},
addFinisher() {
this.finishers.push({type: 'saveToDatabase', options: {}});
},
setFinisherType(finisher, type) {
finisher.type = type;
finisher.options = {};
this.getFinisherSettings(type).forEach(setting => {
finisher.options[setting.name] = setting.default ?? '';
});
},
init() {
this.finishers.forEach(finisher => {
if (!finisher.options || typeof finisher.options !== 'object' || Array.isArray(finisher.options)) finisher.options = {};
this.getFinisherSettings(finisher.type).forEach(setting => {
if (typeof finisher.options[setting.name] === 'undefined') finisher.options[setting.name] = setting.default ?? '';
});
});
},
moveField(fromIndex, toIndex) {
if (toIndex < 0 || toIndex >= this.fields.length) return;
@@ -76,46 +106,57 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
this.fields.splice(toIndex, 0, field);
}
}">
<?php phpb_csrf_field(); ?>
<?php
if(isset($form['id'])) echo '<input type="hidden" name="id" value="'.$form['id'].'">';
?>
<div class="card bg-base-100 shadow mb-6">
<div class="card-body">
<div class="flex items-center gap-2 mb-4">
<i class="ph-duotone ph-text-aa text-2xl text-base-content/60"></i>
<h3 class="card-title text-lg">Grundlegendes</h3>
</div>
<div class="form-control">
<label class="label">
<span class="label-text font-medium">Formularname</span>
<section class="card border border-base-300 bg-base-100 shadow-sm" aria-labelledby="form-basics-title">
<div class="card-body gap-5 p-4 sm:p-6 lg:p-8">
<header class="flex items-start gap-3 border-b border-base-300 pb-4">
<span class="grid size-10 shrink-0 place-items-center rounded-xl bg-primary/10 text-primary">
<i class="text-xl ph-duotone ph-text-aa" aria-hidden="true"></i>
</span>
<div>
<h3 class="card-title text-lg" id="form-basics-title">Basics</h3>
<p class="mt-1 text-sm text-base-content/60">Give the form a name that will be easy to identify later.</p>
</div>
</header>
<div class="form-control w-full max-w-2xl gap-1">
<label class="label" for="form-name">
<span class="label-text font-medium">Form name</span>
<span class="label-text-alt">Required</span>
</label>
<input type="text" name="name" value="<?= $form['name'] ?>" placeholder="z.B. Kontaktformular" class="input input-bordered w-full" required />
<span class="label-text-alt text-base-content/60">Ein eindeutiger Name für dein Formular.</span>
<input id="form-name" type="text" name="name" value="<?= phpb_e($form['name']) ?>" placeholder="e.g. Contact form" class="input input-bordered w-full" required aria-describedby="form-name-help" />
<span class="label-text-alt mt-1 text-base-content/60" id="form-name-help">A unique name for your form.</span>
</div>
</div>
</div>
</section>
<div class="card bg-base-100 shadow mb-6">
<div class="card-body">
<div class="flex items-center gap-2 mb-4">
<i class="ph-duotone ph-list-dashes text-2xl text-base-content/60"></i>
<h3 class="card-title text-lg">Formularfelder</h3>
</div>
<p class="text-sm text-base-content/60 mb-4">Definiere die Felder, die Nutzer ausfüllen können.</p>
<section class="card border border-base-300 bg-base-100 shadow-sm" aria-labelledby="form-fields-title">
<div class="card-body gap-5 p-4 sm:p-6 lg:p-8">
<header class="flex items-start gap-3 border-b border-base-300 pb-4">
<span class="grid size-10 shrink-0 place-items-center rounded-xl bg-secondary/10 text-secondary">
<i class="text-xl ph-duotone ph-list-dashes" aria-hidden="true"></i>
</span>
<div>
<h3 class="card-title text-lg" id="form-fields-title">Form fields</h3>
<p class="mt-1 text-sm text-base-content/60">Define the fields people can fill out. Drag a field to change its order.</p>
</div>
</header>
<input type="hidden" name="fields" :value="JSON.stringify(fields)">
<div x-show="fields.length === 0" class="text-center py-8 border-2 border-dashed border-base-300 rounded-lg">
<i class="ph-duotone ph-plus-circle text-4xl text-base-content/30"></i>
<p class="text-sm text-base-content/50 mt-2">Noch keine Felder hinzugefügt</p>
<a href="javascript:void(0)" @click="addField()" class="btn btn-sm btn-primary mt-2">Erstes Feld hinzufügen</a>
<div x-show="fields.length === 0" class="rounded-box border border-dashed border-base-300 bg-base-200/40 px-4 py-10 text-center">
<i class="ph-duotone ph-plus-circle text-4xl text-base-content/30" aria-hidden="true"></i>
<p class="mt-2 text-sm text-base-content/60">No fields added yet</p>
<button type="button" @click="addField()" class="btn btn-primary btn-sm mt-3">Add your first field</button>
</div>
<div x-show="fields.length > 0" class="space-y-3">
<div x-show="fields.length > 0" class="space-y-4">
<template x-for="(field, index) in fields">
<div
class="border rounded-lg p-3 bg-base-200/50 transition-colors"
class="rounded-box border border-base-300 bg-base-200/40 p-4 shadow-sm transition-colors sm:p-5"
:class="{
'border-error': getValidationErrors(field, index).length > 0,
'border-base-300': getValidationErrors(field, index).length === 0,
@@ -127,72 +168,74 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
@drop.prevent="moveField(dragIndex, index)"
@dragend="dragIndex = null"
>
<div class="flex items-center gap-2 mb-2">
<div class="mb-3 flex flex-col gap-2 sm:flex-row sm:items-center">
<!-- Drag handle -->
<button type="button" class="btn btn-ghost btn-xs btn-square cursor-grab active:cursor-grabbing text-base-content/40 hover:text-base-content" title="Ziehen zum Verschieben">
<i class="ph-duotone ph-dots-six-vertical text-lg"></i>
<button type="button" class="btn btn-ghost btn-xs btn-square cursor-grab active:cursor-grabbing text-base-content/40 hover:text-base-content" title="Drag to move" aria-label="Drag to move field">
<i class="ph-duotone ph-dots-six-vertical text-lg" aria-hidden="true"></i>
</button>
<span class="text-xs font-mono text-base-content/40 w-6">#[<span x-text="index + 1"></span>]</span>
<div class="flex-1">
<div class="w-full flex-1">
<input
type="text"
x-model="field.name"
placeholder="Feldname"
placeholder="Field name"
:aria-label="'Field ' + (index + 1) + ' name'"
class="input input-bordered input-sm w-full"
:class="{'input-error': getValidationErrors(field, index).some(e => e.includes('Feldname'))}"
:class="{'input-error': getValidationErrors(field, index).some(e => e.includes('Field name'))}"
/>
</div>
<div class="flex-1">
<div class="w-full flex-1">
<input
type="text"
x-model="field.label"
placeholder="Beschriftung"
placeholder="Label"
:aria-label="'Field ' + (index + 1) + ' label'"
class="input input-bordered input-sm w-full"
:class="{'input-error': getValidationErrors(field, index).some(e => e.includes('Beschriftung'))}"
:class="{'input-error': getValidationErrors(field, index).some(e => e.includes('Label'))}"
/>
</div>
</div>
<!-- Validation errors -->
<div x-show="getValidationErrors(field, index).length > 0" x-transition class="mb-2 p-2 bg-error/10 border border-error/30 rounded text-error text-xs">
<div x-show="getValidationErrors(field, index).length > 0" x-transition class="alert alert-error alert-soft mb-3 px-3 py-2 text-xs" role="alert" aria-live="polite">
<template x-for="(error, errIndex) in getValidationErrors(field, index)">
<div :key="errIndex" class="flex items-center gap-1">
<i class="ph-duotone ph-warning text-sm"></i>
<i class="ph-duotone ph-warning text-sm" aria-hidden="true"></i>
<span x-text="error"></span>
</div>
</template>
</div>
<div class="flex items-center gap-2">
<select x-model="field.type" class="select select-bordered select-sm flex-1">
<div class="flex flex-wrap items-center gap-2">
<select x-model="field.type" class="select select-bordered select-sm min-w-40 flex-1" :aria-label="'Field ' + (index + 1) + ' type'">
<option value="text">Text</option>
<option value="email">Email</option>
<option value="textarea">Textbereich</option>
<option value="textarea">Text area</option>
<option value="checkbox">Checkbox</option>
<option value="radio">Radio</option>
<option value="select">Auswahl</option>
<option value="select">Select</option>
</select>
<label class="label cursor-pointer gap-2">
<span class="label-text text-sm">Pflichtfeld</span>
<input type="checkbox" x-model="field.required" class="checkbox checkbox-sm checkbox-primary" />
<span class="label-text text-sm">Required</span>
<input type="checkbox" x-model="field.required" class="checkbox checkbox-sm checkbox-primary" :aria-label="'Field ' + (index + 1) + ' is required'" />
</label>
<button @click="fields.splice(index, 1)" type="button" class="btn btn-ghost btn-sm btn-circle text-error" title="Entfernen">
<button @click="fields.splice(index, 1)" type="button" class="btn btn-ghost btn-sm btn-circle text-error" title="Remove" :aria-label="'Remove field ' + (index + 1)">
<i class="ph-duotone ph-trash"></i>
</button>
</div>
<div x-show="field.type === 'select' || field.type === 'checkbox' || field.type === 'radio'" x-transition class="mt-3 ml-2 pl-4 border-l-2 border-primary/30">
<div class="flex items-center gap-2 mb-2">
<span class="text-xs font-medium text-base-content/60 uppercase tracking-wide" x-text="getOptionsLabel(field.type)"></span>
<a href="javascript:void(0)" @click="field.options.push({label: 'Option', value: 'option'})" class="btn btn-xs btn-ghost btn-primary">
<i class="ph-duotone ph-plus"></i>
Neu
</a>
<div x-show="field.type === 'select' || field.type === 'checkbox' || field.type === 'radio'" x-transition class="mt-4 rounded-box border-l-2 border-primary/50 bg-base-100 p-3 sm:ml-2 sm:p-4">
<div class="mb-3 flex items-center gap-2">
<span class="text-xs font-semibold uppercase tracking-wide text-base-content/60" x-text="getOptionsLabel(field.type)"></span>
<button type="button" @click="field.options.push({label: 'Option', value: 'option'})" class="btn btn-xs btn-ghost btn-primary">
<i class="ph-duotone ph-plus" aria-hidden="true"></i>
Add
</button>
</div>
<div class="space-y-1">
<template x-for="(option, optIndex) in field.options">
<div class="flex items-center gap-2">
<div class="flex flex-col gap-2 sm:flex-row sm:items-center">
<span class="text-xs text-base-content/40 w-4">#[<span x-text="optIndex + 1"></span>]</span>
<input type="text" x-model="option.label" placeholder="Beschriftung" class="input input-bordered input-sm flex-1" />
<input type="text" x-model="option.value" placeholder="Wert" class="input input-bordered input-sm flex-1" />
<button @click="field.options.splice(optIndex, 1)" type="button" class="btn btn-ghost btn-xs btn-circle text-error" title="Entfernen">
<input type="text" x-model="option.label" placeholder="Label" class="input input-bordered input-sm w-full flex-1" :aria-label="'Field ' + (index + 1) + ' option ' + (optIndex + 1) + ' label'" />
<input type="text" x-model="option.value" placeholder="Value" class="input input-bordered input-sm w-full flex-1" :aria-label="'Field ' + (index + 1) + ' option ' + (optIndex + 1) + ' value'" />
<button @click="field.options.splice(optIndex, 1)" type="button" class="btn btn-ghost btn-xs btn-circle text-error" title="Remove" :aria-label="'Remove option ' + (optIndex + 1) + ' from field ' + (index + 1)">
<i class="ph-duotone ph-x"></i>
</button>
</div>
@@ -203,62 +246,99 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
</template>
</div>
<div class="mt-4">
<a href="javascript:void(0)" @click="addField()" class="btn btn-outline btn-sm btn-primary">
<i class="ph-duotone ph-plus"></i>
Feld hinzufügen
</a>
<div class="border-t border-base-300 pt-4">
<button type="button" @click="addField()" class="btn btn-outline btn-sm btn-primary">
<i class="ph-duotone ph-plus" aria-hidden="true"></i>
Add field
</button>
</div>
</div>
</div>
</section>
<div class="card bg-base-100 shadow mb-6">
<div class="card-body">
<div class="flex items-center gap-2 mb-4">
<i class="ph-duotone ph-gear text-2xl text-base-content/60"></i>
<h3 class="card-title text-lg">Aktionen</h3>
</div>
<p class="text-sm text-base-content/60 mb-4">Was soll passieren, wenn ein Formular abgeschickt wird?</p>
<section class="card border border-base-300 bg-base-100 shadow-sm" aria-labelledby="form-actions-title">
<div class="card-body gap-5 p-4 sm:p-6 lg:p-8">
<header class="flex items-start gap-3 border-b border-base-300 pb-4">
<span class="grid size-10 shrink-0 place-items-center rounded-xl bg-accent/15 text-base-content">
<i class="text-xl ph-duotone ph-gear" aria-hidden="true"></i>
</span>
<div>
<h3 class="card-title text-lg" id="form-actions-title">Actions</h3>
<p class="mt-1 text-sm text-base-content/60">Choose what should happen when someone submits this form.</p>
</div>
</header>
<input type="hidden" name="finishers" :value="JSON.stringify(finishers)">
<div x-show="finishers.length === 0" class="text-center py-8 border-2 border-dashed border-base-300 rounded-lg">
<i class="ph-duotone ph-plus-circle text-4xl text-base-content/30"></i>
<p class="text-sm text-base-content/50 mt-2">Noch keine Aktionen hinzugefügt</p>
<a href="javascript:void(0)" @click="finishers.push({...defaultFinisher})" class="btn btn-sm btn-primary mt-2">Erste Aktion hinzufügen</a>
<div x-show="finishers.length === 0" class="rounded-box border border-dashed border-base-300 bg-base-200/40 px-4 py-10 text-center">
<i class="ph-duotone ph-plus-circle text-4xl text-base-content/30" aria-hidden="true"></i>
<p class="mt-2 text-sm text-base-content/60">No actions added yet</p>
<button type="button" @click="addFinisher()" class="btn btn-primary btn-sm mt-3">Add your first action</button>
</div>
<div x-show="finishers.length > 0" class="space-y-2">
<div x-show="finishers.length > 0" class="space-y-4">
<template x-for="(finisher, index) in finishers">
<div class="flex items-center gap-3 p-3 border border-base-300 rounded-lg bg-base-200/50">
<span class="text-xs font-mono text-base-content/40">#[<span x-text="index + 1"></span>]</span>
<select x-model="finisher.type" class="select select-bordered select-sm flex-1">
<option value="saveToDatabase">In Datenbank speichern</option>
<option value="sendMailToAdmin">Email an Admin senden</option>
</select>
<button @click="finishers.splice(index, 1)" type="button" class="btn btn-ghost btn-sm btn-circle text-error" title="Entfernen">
<i class="ph-duotone ph-trash"></i>
</button>
<div class="space-y-4 rounded-box border border-base-300 bg-base-200/40 p-4 shadow-sm sm:p-5">
<div class="flex flex-col gap-3 sm:flex-row sm:items-center">
<span class="text-xs font-mono text-base-content/40">#[<span x-text="index + 1"></span>]</span>
<select :value="finisher.type" @change="setFinisherType(finisher, $event.target.value)" class="select select-bordered select-sm min-w-40 flex-1" :aria-label="'Action ' + (index + 1) + ' type'">
<template x-for="(definition, type) in finisherDefinitions" :key="type">
<option :value="type" x-text="definition.label"></option>
</template>
</select>
<button @click="finishers.splice(index, 1)" type="button" class="btn btn-ghost btn-sm btn-circle text-error" title="Remove" :aria-label="'Remove action ' + (index + 1)">
<i class="ph-duotone ph-trash" aria-hidden="true"></i>
</button>
</div>
<div x-show="getFinisherSettings(finisher.type).length > 0" class="space-y-4 border-t border-base-300 pt-4 sm:pl-9">
<template x-for="setting in getFinisherSettings(finisher.type)" :key="setting.name">
<div class="form-control">
<label class="label" :for="'finisher-' + index + '-' + setting.name"><span class="label-text" x-text="setting.label"></span></label>
<template x-if="setting.type === 'emailField'">
<select :id="'finisher-' + index + '-' + setting.name" x-model="finisher.options[setting.name]" :required="setting.required || false" class="select select-bordered select-sm w-full">
<option value="">Select an email field</option>
<template x-for="field in fields.filter(field => field.type === 'email')" :key="field.name">
<option :value="field.name" x-text="field.label + ' (' + field.name + ')' "></option>
</template>
</select>
</template>
<template x-if="setting.type === 'select'">
<select :id="'finisher-' + index + '-' + setting.name" x-model="finisher.options[setting.name]" :required="setting.required || false" class="select select-bordered select-sm w-full">
<template x-for="option in setting.options || []" :key="option.value">
<option :value="option.value" x-text="option.label"></option>
</template>
</select>
</template>
<template x-if="setting.type === 'textarea'">
<textarea :id="'finisher-' + index + '-' + setting.name" x-model="finisher.options[setting.name]" :required="setting.required || false" :placeholder="setting.placeholder || ''" class="textarea textarea-bordered w-full" rows="4"></textarea>
</template>
<template x-if="!['emailField', 'select', 'textarea'].includes(setting.type)">
<input :id="'finisher-' + index + '-' + setting.name" x-model="finisher.options[setting.name]" :type="setting.type" :required="setting.required || false" :min="setting.min" :max="setting.max" :placeholder="setting.placeholder || ''" class="input input-bordered input-sm w-full" />
</template>
<span x-show="setting.help" class="label-text-alt text-base-content/60 mt-1" x-text="setting.help"></span>
</div>
</template>
<span x-show="getFinisherSettings(finisher.type).some(setting => setting.type === 'emailField') && fields.filter(field => field.type === 'email').length === 0" class="alert alert-warning alert-soft text-sm" role="status">Add an email field to the form before using this action.</span>
</div>
</div>
</template>
</div>
<div class="mt-4">
<a href="javascript:void(0)" @click="finishers.push({...defaultFinisher})" class="btn btn-outline btn-sm btn-primary">
<i class="ph-duotone ph-plus"></i>
Aktion hinzufügen
</a>
<div class="border-t border-base-300 pt-4">
<button type="button" @click="addFinisher()" class="btn btn-outline btn-sm btn-primary">
<i class="ph-duotone ph-plus" aria-hidden="true"></i>
Add action
</button>
</div>
</div>
</div>
</section>
<div class="flex justify-end gap-2">
<a href="?tab=ext--form" class="btn btn-ghost btn-sm">
Abbrechen
<div class="flex flex-col-reverse gap-2 border-t border-base-300 pt-5 sm:flex-row sm:justify-end">
<a href="?tab=ext--form" class="btn btn-ghost btn-sm sm:min-w-28">
Cancel
</a>
<button type="submit" class="btn btn-primary btn-sm">
<i class="ph-duotone ph-floppy-disk"></i>
Speichern
<button type="submit" class="btn btn-primary btn-sm sm:min-w-28">
<i class="ph-duotone ph-floppy-disk" aria-hidden="true"></i>
Save
</button>
</div>
</form>
@@ -1,11 +1,16 @@
<div class="card bg-base-100 shadow">
<div class="card-body">
<div class="flex items-center gap-2 mb-4">
<i class="ph-duotone ph-gear text-2xl text-base-content/60"></i>
<h3 class="card-title text-lg">Einstellungen</h3>
<section class="card border border-base-300/60 bg-base-100 shadow-sm" aria-labelledby="form-extension-settings-title">
<div class="card-body gap-5 p-4 sm:p-6 lg:p-8">
<div class="flex items-start gap-3 border-b border-base-300 pb-5">
<span class="grid size-11 shrink-0 place-items-center rounded-2xl bg-primary/10 text-primary">
<i class="text-2xl ph-duotone ph-gear" aria-hidden="true"></i>
</span>
<div>
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-primary">Form extension</p>
<h2 class="card-title mt-1 text-xl" id="form-extension-settings-title">Settings</h2>
<p class="mt-1 text-sm text-base-content/60">Configure the global settings for the Form extension.</p>
</div>
</div>
<p class="text-sm text-base-content/60 mb-4">Konfiguriere die globalen Einstellungen für das Formulare-Extension.</p>
<div class="space-y-4">
<div class="space-y-5">
<?php
foreach (\Plugi\Extensions::getSettings('form') as $setting) {
phpb_render_setting($setting);
@@ -13,4 +18,4 @@
?>
</div>
</div>
</div>
</section>
@@ -13,76 +13,83 @@ $entries = $entriesRepository->findWhere('formId', $id);
?>
<div class="mb-6">
<div class="flex items-center gap-3">
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form']) ?>" class="btn btn-ghost btn-sm btn-circle">
<i class="ph-duotone ph-arrow-left text-xl"></i>
</a>
<div>
<h2 class="text-xl font-bold"><?= phpb_e($form['name']) ?></h2>
<p class="text-sm text-base-content/60"><?= count($entries) ?> Eintrag<?= count($entries) !== 1 ? 'e' : '' ?> für dieses Formular</p>
<section class="space-y-5">
<header class="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--form']) ?>" class="btn btn-ghost btn-square btn-sm" aria-label="Back to forms" title="Back to forms">
<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">Form submissions</p>
<h2 class="text-xl font-bold tracking-tight"><?= phpb_e($form['name']) ?></h2>
<p class="text-sm text-base-content/60"><?= count($entries) ?> submission<?= count($entries) !== 1 ? 's' : '' ?> for this form</p>
</div>
</div>
</div>
</div>
<span class="badge badge-outline self-start sm:self-center"><?= count($entries) ?> total</span>
</header>
<?php if (empty($entries)): ?>
<div class="card bg-base-100 shadow">
<div class="card-body items-center text-center py-16">
<i class="ph-duotone ph-inbox text-6xl text-base-content/20"></i>
<h3 class="card-title text-lg mt-4">Noch keine Einträge</h3>
<p class="text-base-content/60 mt-1">Wenn jemand das Formular ausfüllt, erscheint die Eintragung hier.</p>
<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-info/10 text-info">
<i class="text-3xl ph-duotone ph-inbox" aria-hidden="true"></i>
</span>
<h3 class="card-title mt-1 text-lg">No submissions yet</h3>
<p class="max-w-md text-sm leading-relaxed text-base-content/60">Submissions will appear here when someone fills out the form.</p>
</div>
</div>
<?php else: ?>
<div class="card bg-base-100 shadow">
<div class="card-body p-0">
<div class="overflow-x-auto">
<table class="table w-full">
<thead>
<tr class="bg-base-200/50">
<th class="w-16">ID</th>
<th class="w-40">Erstellt</th>
<?php foreach ($fields as $field): ?>
<th><?= phpb_e($field['label']) ?></th>
<?php endforeach; ?>
<th class="w-12 text-center"><?= phpb_trans('website-manager.actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($entries as $entry):
$entryData = json_decode($entry['data'], true);
$createdDate = new DateTime($entry['created'] . ' UTC');
$createdDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
<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 class="w-16">ID</th>
<th class="w-40">Created</th>
<?php foreach ($fields as $field): ?>
<th><?= phpb_e($field['label']) ?></th>
<?php endforeach; ?>
<th class="w-40 text-right"><?= phpb_trans('website-manager.actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($entries as $entry):
$entryData = json_decode($entry['data'], true);
$createdDate = new DateTime($entry['created'] . ' UTC');
$createdDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
?>
<tr>
<td><span class="badge badge-ghost font-mono"><?= phpb_e($entry['id']) ?></span></td>
<td class="text-sm"><?= $createdDate->format('d.m.Y H:i') ?></td>
<?php foreach ($fields as $field):
$fieldName = $field['name'];
$fieldValue = '';
if (isset($entryData['fields'][$fieldName])) {
$fieldValue = $entryData['fields'][$fieldName];
// Handle array values (e.g., from checkboxes)
if (is_array($fieldValue)) {
$fieldValue = implode(', ', $fieldValue);
}
}
?>
<tr class="hover:bg-base-200/30">
<td class="font-mono text-sm text-base-content/60"><?= phpb_e($entry['id']) ?></td>
<td class="text-sm"><?= $createdDate->format('d.m.Y H:i') ?></td>
<?php foreach ($fields as $field):
$fieldName = $field['name'];
$fieldValue = '';
if (isset($entryData['fields'][$fieldName])) {
$fieldValue = $entryData['fields'][$fieldName];
// Handle array values (e.g., from checkboxes)
if (is_array($fieldValue)) {
$fieldValue = implode(', ', $fieldValue);
}
}
?>
<td class="text-sm"><?= phpb_e($fieldValue) ?></td>
<?php endforeach; ?>
<td>
<div class="flex justify-center">
<a href="/ext--form/delete-entry?id=<?= $entry['id'] ?>&formId=<?= $id ?>" class="btn btn-ghost btn-sm btn-circle text-error" title="<?= phpb_trans('website-manager.remove') ?>">
<i class="ph-duotone ph-trash text-lg"></i>
</a>
</div>
</td>
</tr>
<td class="max-w-72 text-sm"><span class="line-clamp-3 break-words"><?= phpb_e($fieldValue) ?></span></td>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<td>
<div class="flex justify-end">
<form action="/ext--form/delete-entry" method="post">
<?php phpb_csrf_field(); ?>
<input type="hidden" name="id" value="<?= phpb_e((string) $entry['id']) ?>">
<input type="hidden" name="formId" value="<?= phpb_e((string) $id) ?>">
<button type="submit" class="btn btn-ghost btn-square btn-sm text-error" title="<?= phpb_trans('website-manager.remove') ?>" aria-label="<?= phpb_trans('website-manager.remove') ?> submission <?= phpb_e($entry['id']) ?>">
<i class="ph-duotone ph-trash text-lg" aria-hidden="true"></i>
</button>
</form>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</section>
@@ -6,67 +6,72 @@ $forms = $formsRepository->getAll();
?>
<div class="flex items-center justify-between mb-6">
<div>
<h2 class="text-xl font-bold">Formulare</h2>
<p class="text-sm text-base-content/60"><?= count($forms) ?> Formular<?= count($forms) !== 1 ? 'e' : '' ?> vorhanden</p>
</div>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'editForm']) ?>" class="btn btn-primary btn-sm">
<i class="ph-duotone ph-plus"></i>
Neues Formular
</a>
</div>
<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">Form extension</p>
<h2 class="text-xl font-bold tracking-tight text-base-content">Forms</h2>
<p class="text-sm text-base-content/60"><?= count($forms) ?> form<?= count($forms) !== 1 ? 's' : '' ?> available</p>
</div>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'editForm']) ?>" class="btn btn-primary">
<i class="ph-duotone ph-plus" aria-hidden="true"></i>
New form
</a>
</header>
<?php if (empty($forms)): ?>
<div class="card bg-base-100 shadow">
<div class="card-body items-center text-center py-16">
<i class="ph-duotone ph-notebook text-6xl text-base-content/20"></i>
<h3 class="card-title text-lg mt-4">Noch keine Formulare</h3>
<p class="text-base-content/60 mt-1">Erstelle dein erstes Formular, um Einträge von deiner Website zu sammeln.</p>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'editForm']) ?>" class="btn btn-primary mt-4">
<i class="ph-duotone ph-plus"></i>
Erstes Formular erstellen
<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-notebook" aria-hidden="true"></i>
</span>
<h3 class="card-title mt-1 text-lg">No forms yet</h3>
<p class="max-w-md text-sm leading-relaxed text-base-content/60">Create your first form to collect submissions from your website.</p>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'editForm']) ?>" class="btn btn-primary mt-2">
<i class="ph-duotone ph-plus" aria-hidden="true"></i>
Create your first form
</a>
</div>
</div>
<?php else: ?>
<div class="card bg-base-100 shadow">
<div class="card-body p-0">
<div class="overflow-x-auto">
<table class="table w-full">
<thead>
<tr class="bg-base-200/50">
<th class="w-16">ID</th>
<th><?= phpb_trans('website-manager.name') ?></th>
<th class="w-16 text-center"><?= phpb_trans('website-manager.actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($forms as $form): ?>
<tr class="hover:bg-base-200/30">
<td class="font-mono text-sm text-base-content/60"><?= phpb_e($form['id']) ?></td>
<td>
<div class="font-medium"><?= phpb_e($form['name']) ?></div>
</td>
<td>
<div class="flex items-center justify-center gap-1">
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'listEntries', 'id' => $form['id']]) ?>" class="btn btn-ghost btn-sm btn-circle" title="Einträge ansehen">
<i class="ph-duotone ph-eye text-lg"></i>
</a>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'editForm', 'id' => $form['id']]) ?>" class="btn btn-ghost btn-sm btn-circle" title="<?= phpb_trans('website-manager.edit') ?>">
<i class="ph-duotone ph-pencil-line text-lg"></i>
</a>
<a href="/ext--form/delete-form?id=<?= $form['id'] ?>" class="btn btn-ghost btn-sm btn-circle text-error" title="<?= phpb_trans('website-manager.remove') ?>">
<i class="ph-duotone ph-trash text-lg"></i>
</a>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
<table class="table table-zebra w-full min-w-[36rem]">
<thead>
<tr>
<th class="w-16">ID</th>
<th><?= phpb_trans('website-manager.name') ?></th>
<th class="w-40 text-right"><?= phpb_trans('website-manager.actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($forms as $form): ?>
<tr>
<td><span class="badge badge-ghost font-mono"><?= phpb_e($form['id']) ?></span></td>
<td>
<div class="font-medium"><?= phpb_e($form['name']) ?></div>
</td>
<td>
<div class="flex items-center justify-end gap-1">
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'listEntries', 'id' => $form['id']]) ?>" class="btn btn-ghost btn-square btn-sm" title="View entries" aria-label="View entries for <?= phpb_e($form['name']) ?>">
<i class="ph-duotone ph-eye text-lg" aria-hidden="true"></i>
</a>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'editForm', 'id' => $form['id']]) ?>" class="btn btn-ghost btn-square btn-sm" title="<?= phpb_trans('website-manager.edit') ?>" aria-label="<?= phpb_trans('website-manager.edit') ?> <?= phpb_e($form['name']) ?>">
<i class="ph-duotone ph-pencil-line text-lg" aria-hidden="true"></i>
</a>
<form action="/ext--form/delete-form" method="post">
<?php phpb_csrf_field(); ?>
<input type="hidden" name="id" value="<?= phpb_e((string) $form['id']) ?>">
<button type="submit" class="btn btn-ghost btn-square btn-sm text-error" title="<?= phpb_trans('website-manager.remove') ?>" aria-label="<?= phpb_trans('website-manager.remove') ?> <?= phpb_e($form['name']) ?>">
<i class="ph-duotone ph-trash text-lg" aria-hidden="true"></i>
</button>
</form>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</section>
+7 -5
View File
@@ -2,14 +2,14 @@
$modules = [
'listForms' => [
'include' => __DIR__ . '/Views/ListForms.php',
'label' => 'Formulare',
'label' => 'Forms',
'icon' => 'ph-list-dashes',
'showTabs' => true,
'inMenu' => true,
],
'settings' => [
'include' => __DIR__ . '/Views/ExtSettings.php',
'label' => 'Einstellungen',
'label' => 'Settings',
'icon' => 'ph-gear',
'showTabs' => true,
'inMenu' => true,
@@ -33,20 +33,22 @@ if (isset($_GET['action']) && array_key_exists($_GET['action'], $modules)) $acti
<?php
if ($modules[$activeModule]['showTabs'] === true):
?>
<div class="tabs tabs-boxed bg-base-200/50 mb-6">
<nav class="mb-6 overflow-x-auto" aria-label="Form extension navigation">
<div class="tabs tabs-box w-max min-w-full bg-base-200/50">
<?php
foreach ($modules as $name => $module):
if ($module['inMenu'] === false) continue;
$icon = $module['icon'] ?? 'ph-circle';
?>
<a class="tab gap-2 <?= $name === $activeModule ? 'tab-active' : '' ?>" href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => $name]) ?>">
<i class="ph-duotone <?= $icon ?>"></i>
<a class="tab gap-2 <?= $name === $activeModule ? 'tab-active' : '' ?>" <?= $name === $activeModule ? 'aria-current="page"' : '' ?> href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => $name]) ?>">
<i class="ph-duotone <?= $icon ?>" aria-hidden="true"></i>
<?= $module['label'] ?>
</a>
<?php
endforeach;
?>
</div>
</nav>
<?php
endif;
?>
+225 -40
View File
@@ -9,6 +9,7 @@
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono",
"Courier New", monospace;
--spacing: 0.25rem;
--container-md: 28rem;
--container-2xl: 42rem;
--text-xs: 0.75rem;
--text-xs--line-height: calc(1 / 0.75);
@@ -24,12 +25,14 @@
--text-3xl--line-height: calc(2.25 / 1.875);
--text-4xl: 2.25rem;
--text-4xl--line-height: calc(2.5 / 2.25);
--text-6xl: 3.75rem;
--text-6xl--line-height: 1;
--font-weight-medium: 500;
--font-weight-semibold: 600;
--font-weight-bold: 700;
--tracking-tight: -0.025em;
--tracking-wide: 0.025em;
--radius-lg: 0.5rem;
--leading-relaxed: 1.625;
--radius-xl: 0.75rem;
--radius-2xl: 1rem;
--default-transition-duration: 150ms;
--default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
--default-font-family: var(--font-sans);
@@ -185,6 +188,20 @@
}
}
@layer utilities {
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
border-width: 0;
}
.static {
position: static;
}
.mx-auto {
margin-inline: auto;
}
@@ -209,8 +226,11 @@
.mb-2 {
margin-bottom: calc(var(--spacing) * 2);
}
.mb-4 {
margin-bottom: calc(var(--spacing) * 4);
.mb-3 {
margin-bottom: calc(var(--spacing) * 3);
}
.mb-5 {
margin-bottom: calc(var(--spacing) * 5);
}
.mb-6 {
margin-bottom: calc(var(--spacing) * 6);
@@ -218,18 +238,36 @@
.ml-1 {
margin-left: var(--spacing);
}
.ml-2 {
margin-left: calc(var(--spacing) * 2);
.line-clamp-3 {
overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
}
.flex {
display: flex;
}
.grid {
display: grid;
}
.hidden {
display: none;
}
.table {
display: table;
}
.size-10 {
width: calc(var(--spacing) * 10);
height: calc(var(--spacing) * 10);
}
.size-11 {
width: calc(var(--spacing) * 11);
height: calc(var(--spacing) * 11);
}
.size-14 {
width: calc(var(--spacing) * 14);
height: calc(var(--spacing) * 14);
}
.h-16 {
height: calc(var(--spacing) * 16);
}
@@ -239,9 +277,6 @@
.w-6 {
width: calc(var(--spacing) * 6);
}
.w-12 {
width: calc(var(--spacing) * 12);
}
.w-16 {
width: calc(var(--spacing) * 16);
}
@@ -251,23 +286,59 @@
.w-full {
width: 100%;
}
.w-max {
width: max-content;
}
.max-w-2xl {
max-width: var(--container-2xl);
}
.max-w-72 {
max-width: calc(var(--spacing) * 72);
}
.max-w-md {
max-width: var(--container-md);
}
.min-w-40 {
min-width: calc(var(--spacing) * 40);
}
.min-w-\[36rem\] {
min-width: 36rem;
}
.min-w-\[48rem\] {
min-width: 48rem;
}
.min-w-full {
min-width: 100%;
}
.flex-1 {
flex: 1;
}
.shrink-0 {
flex-shrink: 0;
}
.cursor-grab {
cursor: grab;
}
.cursor-pointer {
cursor: pointer;
}
.flex-col {
flex-direction: column;
}
.flex-col-reverse {
flex-direction: column-reverse;
}
.flex-wrap {
flex-wrap: wrap;
}
.place-items-center {
place-items: center;
}
.items-center {
align-items: center;
}
.justify-between {
justify-content: space-between;
.items-start {
align-items: flex-start;
}
.justify-center {
justify-content: center;
@@ -275,6 +346,9 @@
.justify-end {
justify-content: flex-end;
}
.justify-start {
justify-content: flex-start;
}
.gap-1 {
gap: var(--spacing);
}
@@ -284,6 +358,12 @@
.gap-3 {
gap: calc(var(--spacing) * 3);
}
.gap-4 {
gap: calc(var(--spacing) * 4);
}
.gap-5 {
gap: calc(var(--spacing) * 5);
}
:where(.space-y-1 > :not(:last-child)) {
--tw-space-y-reverse: 0;
margin-block-start: calc(var(--spacing) * var(--tw-space-y-reverse));
@@ -294,27 +374,35 @@
margin-block-start: calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));
margin-block-end: calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)));
}
:where(.space-y-3 > :not(:last-child)) {
--tw-space-y-reverse: 0;
margin-block-start: calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));
margin-block-end: calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)));
}
:where(.space-y-4 > :not(:last-child)) {
--tw-space-y-reverse: 0;
margin-block-start: calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));
margin-block-end: calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)));
}
:where(.space-y-5 > :not(:last-child)) {
--tw-space-y-reverse: 0;
margin-block-start: calc(calc(var(--spacing) * 5) * var(--tw-space-y-reverse));
margin-block-end: calc(calc(var(--spacing) * 5) * calc(1 - var(--tw-space-y-reverse)));
}
:where(.space-y-6 > :not(:last-child)) {
--tw-space-y-reverse: 0;
margin-block-start: calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));
margin-block-end: calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)));
}
.self-start {
align-self: flex-start;
}
.overflow-x-auto {
overflow-x: auto;
}
.rounded {
border-radius: 0.25rem;
.rounded-2xl {
border-radius: var(--radius-2xl);
}
.rounded-full {
border-radius: calc(infinity * 1px);
}
.rounded-lg {
border-radius: var(--radius-lg);
.rounded-xl {
border-radius: var(--radius-xl);
}
.border {
border-style: var(--tw-border-style);
@@ -324,6 +412,14 @@
border-style: var(--tw-border-style);
border-width: 2px;
}
.border-t {
border-top-style: var(--tw-border-style);
border-top-width: 1px;
}
.border-b {
border-bottom-style: var(--tw-border-style);
border-bottom-width: 1px;
}
.border-l-2 {
border-left-style: var(--tw-border-style);
border-left-width: 2px;
@@ -332,27 +428,54 @@
--tw-border-style: dashed;
border-style: dashed;
}
.p-0 {
padding: 0px;
}
.p-2 {
padding: calc(var(--spacing) * 2);
}
.p-3 {
padding: calc(var(--spacing) * 3);
}
.p-4 {
padding: calc(var(--spacing) * 4);
}
.px-0 {
padding-inline: 0px;
}
.px-3 {
padding-inline: calc(var(--spacing) * 3);
}
.px-4 {
padding-inline: calc(var(--spacing) * 4);
}
.px-5 {
padding-inline: calc(var(--spacing) * 5);
}
.py-2 {
padding-block: calc(var(--spacing) * 2);
}
.py-8 {
padding-block: calc(var(--spacing) * 8);
}
.py-16 {
padding-block: calc(var(--spacing) * 16);
.py-10 {
padding-block: calc(var(--spacing) * 10);
}
.pl-4 {
padding-left: calc(var(--spacing) * 4);
.py-12 {
padding-block: calc(var(--spacing) * 12);
}
.pt-4 {
padding-top: calc(var(--spacing) * 4);
}
.pt-5 {
padding-top: calc(var(--spacing) * 5);
}
.pb-4 {
padding-bottom: calc(var(--spacing) * 4);
}
.pb-5 {
padding-bottom: calc(var(--spacing) * 5);
}
.text-center {
text-align: center;
}
.text-right {
text-align: right;
}
.font-mono {
font-family: var(--font-mono);
}
@@ -368,10 +491,6 @@
font-size: var(--text-4xl);
line-height: var(--tw-leading, var(--text-4xl--line-height));
}
.text-6xl {
font-size: var(--text-6xl);
line-height: var(--tw-leading, var(--text-6xl--line-height));
}
.text-lg {
font-size: var(--text-lg);
line-height: var(--tw-leading, var(--text-lg--line-height));
@@ -388,6 +507,10 @@
font-size: var(--text-xs);
line-height: var(--tw-leading, var(--text-xs--line-height));
}
.leading-relaxed {
--tw-leading: var(--leading-relaxed);
line-height: var(--leading-relaxed);
}
.font-bold {
--tw-font-weight: var(--font-weight-bold);
font-weight: var(--font-weight-bold);
@@ -396,21 +519,32 @@
--tw-font-weight: var(--font-weight-medium);
font-weight: var(--font-weight-medium);
}
.font-semibold {
--tw-font-weight: var(--font-weight-semibold);
font-weight: var(--font-weight-semibold);
}
.tracking-\[0\.18em\] {
--tw-tracking: 0.18em;
letter-spacing: 0.18em;
}
.tracking-tight {
--tw-tracking: var(--tracking-tight);
letter-spacing: var(--tracking-tight);
}
.tracking-wide {
--tw-tracking: var(--tracking-wide);
letter-spacing: var(--tracking-wide);
}
.break-words {
overflow-wrap: break-word;
}
.uppercase {
text-transform: uppercase;
}
.shadow {
.shadow-sm {
--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1));
box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);
}
.shadow-lg {
--tw-shadow: 0 10px 15px -3px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 4px 6px -4px var(--tw-shadow-color, rgb(0 0 0 / 0.1));
box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);
}
.transition-colors {
transition-property: color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, --tw-gradient-from, --tw-gradient-via, --tw-gradient-to;
transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));
@@ -419,6 +553,52 @@
.active\:cursor-grabbing:active {
cursor: grabbing;
}
@media (width >= 40rem) {
.sm\:ml-2 {
margin-left: calc(var(--spacing) * 2);
}
.sm\:min-w-28 {
min-width: calc(var(--spacing) * 28);
}
.sm\:flex-row {
flex-direction: row;
}
.sm\:items-center {
align-items: center;
}
.sm\:items-end {
align-items: flex-end;
}
.sm\:justify-between {
justify-content: space-between;
}
.sm\:justify-end {
justify-content: flex-end;
}
.sm\:self-center {
align-self: center;
}
.sm\:p-4 {
padding: calc(var(--spacing) * 4);
}
.sm\:p-5 {
padding: calc(var(--spacing) * 5);
}
.sm\:p-6 {
padding: calc(var(--spacing) * 6);
}
.sm\:py-16 {
padding-block: calc(var(--spacing) * 16);
}
.sm\:pl-9 {
padding-left: calc(var(--spacing) * 9);
}
}
@media (width >= 64rem) {
.lg\:p-8 {
padding: calc(var(--spacing) * 8);
}
}
}
@layer theme, base, components, utilities;
@layer theme;
@@ -581,6 +761,10 @@
inherits: false;
initial-value: solid;
}
@property --tw-leading {
syntax: "*";
inherits: false;
}
@property --tw-font-weight {
syntax: "*";
inherits: false;
@@ -659,6 +843,7 @@
*, ::before, ::after, ::backdrop {
--tw-space-y-reverse: 0;
--tw-border-style: solid;
--tw-leading: initial;
--tw-font-weight: initial;
--tw-tracking: initial;
--tw-shadow: 0 0 #0000;
+1
View File
@@ -0,0 +1 @@
(()=>{let e=`Your submission could not be completed. Please try again.`;function t(e,t){e&&(e.hidden=!t,e.classList.toggle(`hidden`,!t))}function n(e){let t=Array.from(e.querySelectorAll(`input[type="checkbox"]`));t.length!==0&&(t[0].required=!t.some(e=>e.checked))}function r(e){let t={},n=Array.from(e.querySelectorAll(`input[name], select[name], textarea[name]`)).filter(e=>!e.matches(`:disabled`)),r=/* @__PURE__ */ new Map;return n.forEach(e=>{e instanceof HTMLInputElement&&[`button`,`submit`,`reset`,`image`].includes(e.type)||(r.has(e.name)||r.set(e.name,[]),r.get(e.name).push(e))}),r.forEach((e,n)=>{let r=e[0];if(r instanceof HTMLInputElement&&r.type===`checkbox`)t[n]=e.filter(e=>e.checked).map(e=>e.value);else if(r instanceof HTMLInputElement&&r.type===`radio`){let r=e.find(e=>e.checked);t[n]=r?r.value:``}else t[n]=r.value}),{fields:t}}function i(e,n){let r=e.querySelector(`[data-form-submit]`),i=e.querySelector(`[data-form-submit-idle]`),a=e.querySelector(`[data-form-submit-busy]`);e.setAttribute(`aria-busy`,String(n)),r&&(r.disabled=n,r.setAttribute(`aria-busy`,String(n))),t(i,!n),t(a,n)}function a(){document.querySelectorAll(`[data-field-type="checkbox"][data-field-required="true"]`).forEach(n)}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,a,{once:!0}):a(),document.addEventListener(`change`,e=>{if(!(e.target instanceof HTMLInputElement)||e.target.type!==`checkbox`)return;let t=e.target.closest(`[data-field-type="checkbox"][data-field-required="true"]`);t&&n(t)}),document.addEventListener(`submit`,async n=>{let a=n.target;if(!(a instanceof HTMLFormElement)||!a.matches(`[data-form-wrapper]`)||(n.preventDefault(),a.dataset.submitting===`true`))return;a.dataset.submitting=`true`;let o=a.parentElement,s=o.querySelector(`[data-form-error]`),c=o.querySelector(`[data-form-success]`);t(s,!1),s&&(s.textContent=``),i(a,!0);try{let n=await fetch(`/ext--form/submit?id=${encodeURIComponent(a.dataset.formId)}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r(a))}),i=await n.json();if(!n.ok||!i||!i.success){let t=i&&Array.isArray(i.errors)?i.errors.join(` `):``;throw Error(t||e)}a.hidden=!0,a.classList.add(`hidden`),t(c,!0)}catch(n){s&&(s.textContent=n instanceof Error&&n.message?n.message:e,t(s,!0))}finally{i(a,!1),delete a.dataset.submitting}})})();
+145
View File
@@ -0,0 +1,145 @@
(() => {
const defaultErrorMessage = 'Your submission could not be completed. Please try again.';
function setVisible(element, visible) {
if (!element) {
return;
}
element.hidden = !visible;
element.classList.toggle('hidden', !visible);
}
function updateCheckboxGroupRequired(group) {
const checkboxes = Array.from(group.querySelectorAll('input[type="checkbox"]'));
if (checkboxes.length === 0) {
return;
}
checkboxes[0].required = !checkboxes.some(checkbox => checkbox.checked);
}
function collectFields(form) {
const fields = {};
const controls = Array.from(form.querySelectorAll('input[name], select[name], textarea[name]'))
.filter(control => !control.matches(':disabled'));
const groups = new Map();
controls.forEach(control => {
if (control instanceof HTMLInputElement && ['button', 'submit', 'reset', 'image'].includes(control.type)) {
return;
}
if (!groups.has(control.name)) {
groups.set(control.name, []);
}
groups.get(control.name).push(control);
});
groups.forEach((groupControls, name) => {
const firstControl = groupControls[0];
if (firstControl instanceof HTMLInputElement && firstControl.type === 'checkbox') {
fields[name] = groupControls
.filter(control => control.checked)
.map(control => control.value);
return;
}
if (firstControl instanceof HTMLInputElement && firstControl.type === 'radio') {
const selectedControl = groupControls.find(control => control.checked);
fields[name] = selectedControl ? selectedControl.value : '';
return;
}
fields[name] = firstControl.value;
});
return { fields };
}
function setBusy(form, busy) {
const submitButton = form.querySelector('[data-form-submit]');
const idleContent = form.querySelector('[data-form-submit-idle]');
const busyContent = form.querySelector('[data-form-submit-busy]');
form.setAttribute('aria-busy', String(busy));
if (submitButton) {
submitButton.disabled = busy;
submitButton.setAttribute('aria-busy', String(busy));
}
setVisible(idleContent, !busy);
setVisible(busyContent, busy);
}
function initializeCheckboxGroups() {
document.querySelectorAll('[data-field-type="checkbox"][data-field-required="true"]')
.forEach(updateCheckboxGroupRequired);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initializeCheckboxGroups, { once: true });
} else {
initializeCheckboxGroups();
}
document.addEventListener('change', event => {
if (!(event.target instanceof HTMLInputElement) || event.target.type !== 'checkbox') {
return;
}
const group = event.target.closest('[data-field-type="checkbox"][data-field-required="true"]');
if (group) {
updateCheckboxGroupRequired(group);
}
});
document.addEventListener('submit', async event => {
const form = event.target;
if (!(form instanceof HTMLFormElement) || !form.matches('[data-form-wrapper]')) {
return;
}
event.preventDefault();
if (form.dataset.submitting === 'true') {
return;
}
form.dataset.submitting = 'true';
const formContainer = form.parentElement;
const errorMessage = formContainer.querySelector('[data-form-error]');
const successMessage = formContainer.querySelector('[data-form-success]');
setVisible(errorMessage, false);
if (errorMessage) {
errorMessage.textContent = '';
}
setBusy(form, true);
try {
const response = await fetch(`/ext--form/submit?id=${encodeURIComponent(form.dataset.formId)}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(collectFields(form))
});
const result = await response.json();
if (!response.ok || !result || !result.success) {
const errors = result && Array.isArray(result.errors) ? result.errors.join(' ') : '';
throw new Error(errors || defaultErrorMessage);
}
form.hidden = true;
form.classList.add('hidden');
setVisible(successMessage, true);
} catch (error) {
if (errorMessage) {
errorMessage.textContent = error instanceof Error && error.message
? error.message
: defaultErrorMessage;
setVisible(errorMessage, true);
}
} finally {
setBusy(form, false);
delete form.dataset.submitting;
}
});
})();
@@ -18,7 +18,7 @@ return [
"settings" => [
"formId" => [
"type" => "select",
"label" => "Formular",
"label" => "Form",
"value" => 0,
"options" => $formOptions,
],
@@ -5,109 +5,120 @@ if ($id > 0):
$form = $formRepository->findWithId($id);
$fields = json_decode($form["fields"], true);
$formInstanceId = uniqid("form-$id-");
?>
<div class="max-w-2xl mx-auto">
<div x-data="{data: {fields : {}}, status: 'idle', submitted: false}">
<form x-show="!submitted" x-transition:leave x-transition:leave-opacity-0 x-on:submit.prevent="
status = 'busy';
fetch('/ext--form/submit?id=<?= $id ?>', {
method: 'POST',
body: JSON.stringify(data)
}).finally(() => {
status = 'idle';
submitted = true;
})
">
<?php foreach ($fields as $field):
<div class="mx-auto w-full max-w-2xl">
<div class="space-y-4">
<form data-form-wrapper data-form-id="<?= phpb_e($id) ?>" aria-busy="false">
<?php foreach ($fields as $fieldIndex => $field):
$fieldName = $field["name"];
$fieldLabel = $field["label"];
$fieldType = $field["type"];
$fieldId = $formInstanceId . "-field-" . (int) $fieldIndex;
$fieldRequired =
isset($field["required"]) && $field["required"];
$fieldOptions = isset($field["options"])
? $field["options"]
: [];
?>
<div class="form-control mb-4">
<label class="label mb-1">
?>
<div class="form-control mb-5">
<?php if ($fieldType === "checkbox" || $fieldType === "radio"): ?>
<fieldset class="space-y-2" data-field-type="<?= phpb_e($fieldType) ?>" data-field-required="<?= $fieldRequired ? "true" : "false" ?>">
<legend class="label mb-1 px-0">
<span class="label-text font-medium">
<?= $fieldLabel ?>
<?= phpb_e($fieldLabel) ?>
<?php if ($fieldRequired): ?>
<span class="text-error ml-1">*</span>
<span class="ml-1 text-error" aria-hidden="true">*</span>
<span class="sr-only">(required)</span>
<?php endif; ?>
</span>
</legend>
<?php else: ?>
<label for="<?= phpb_e($fieldId) ?>" class="label mb-1 px-0">
<span class="label-text font-medium">
<?= phpb_e($fieldLabel) ?>
<?php if ($fieldRequired): ?>
<span class="ml-1 text-error" aria-hidden="true">*</span>
<span class="sr-only">(required)</span>
<?php endif; ?>
</span>
</label>
<?php endif; ?>
<?php if ($fieldType === "select"): ?>
<select x-model="data.fields.<?= $fieldName ?>" class="select select-bordered w-full" <?= $fieldRequired
<select id="<?= phpb_e($fieldId) ?>" name="<?= phpb_e($fieldName) ?>" class="select select-bordered w-full" <?= $fieldRequired
? "required"
: "" ?>>
<option value="" disabled selected>Bitte wählen</option>
<option value="" disabled selected>Please select</option>
<?php foreach ($fieldOptions as $option): ?>
<option value="<?= $option[
<option value="<?= phpb_e($option[
"value"
] ?>"><?= $option["label"] ?></option>
]) ?>"><?= phpb_e($option["label"]) ?></option>
<?php endforeach; ?>
</select>
<?php elseif ($fieldType === "checkbox"): ?>
<div class="space-y-2">
<?php foreach ($fieldOptions as $option): ?>
<label class="label cursor-pointer gap-3">
<span class="label-text"><?= $option[
"label"
] ?></span>
<input type="checkbox" value="<?= $option[
<?php foreach ($fieldOptions as $optionIndex => $option): ?>
<label class="label cursor-pointer justify-start gap-3 rounded-box border border-base-300 px-3 py-2">
<input type="checkbox" name="<?= phpb_e($fieldName) ?>" value="<?= phpb_e($option[
"value"
] ?>" x-model="data.fields.<?= $fieldName ?>" class="checkbox checkbox-sm checkbox-primary" />
]) ?>" <?= $fieldRequired && $optionIndex === 0 ? "required" : "" ?> class="checkbox checkbox-sm checkbox-primary" />
<span class="label-text"><?= phpb_e($option[
"label"
]) ?></span>
</label>
<?php endforeach; ?>
</div>
<?php elseif ($fieldType === "radio"): ?>
<div class="space-y-2">
<?php foreach ($fieldOptions as $option): ?>
<label class="label cursor-pointer gap-3">
<span class="label-text"><?= $option[
"label"
] ?></span>
<input type="radio" name="<?= $fieldName ?>" value="<?= $option[
<?php foreach ($fieldOptions as $optionIndex => $option): ?>
<label class="label cursor-pointer justify-start gap-3 rounded-box border border-base-300 px-3 py-2">
<input type="radio" id="<?= phpb_e($fieldId) ?>-<?= (int) $optionIndex ?>" name="<?= phpb_e($fieldName) ?>" value="<?= phpb_e($option[
"value"
] ?>" x-model="data.fields.<?= $fieldName ?>" class="radio radio-sm radio-primary" />
]) ?>" <?= $fieldRequired && $optionIndex === 0 ? "required" : "" ?> class="radio radio-sm radio-primary" />
<span class="label-text"><?= phpb_e($option[
"label"
]) ?></span>
</label>
<?php endforeach; ?>
</div>
<?php elseif ($fieldType === "textarea"): ?>
<textarea x-model="data.fields.<?= $fieldName ?>" class="textarea textarea-bordered w-full" placeholder="<?= $fieldLabel ?>" <?= $fieldRequired
<textarea id="<?= phpb_e($fieldId) ?>" name="<?= phpb_e($fieldName) ?>" class="textarea textarea-bordered w-full" placeholder="<?= phpb_e($fieldLabel) ?>" <?= $fieldRequired
? "required"
: "" ?> rows="4"></textarea>
<?php else: ?>
<input type="<?= $fieldType ?>" x-model="data.fields.<?= $fieldName ?>" class="input input-bordered w-full" placeholder="<?= $fieldLabel ?>" <?= $fieldRequired
<input id="<?= phpb_e($fieldId) ?>" name="<?= phpb_e($fieldName) ?>" type="<?= phpb_e($fieldType) ?>" class="input input-bordered w-full" placeholder="<?= phpb_e($fieldLabel) ?>" <?= $fieldRequired
? "required"
: "" ?>>
<?php endif; ?>
<?php if ($fieldType === "checkbox" || $fieldType === "radio"): ?>
</fieldset>
<?php endif; ?>
</div>
<?php
endforeach; ?>
<div class="mt-6">
<button type="submit" class="btn btn-primary w-full" :disabled="status === 'busy'">
<span x-show="status === 'idle'">
<i class="ph-duotone ph-paper-plane-tilt"></i>
Absenden
<button type="submit" class="btn btn-primary w-full" data-form-submit aria-busy="false">
<span data-form-submit-idle aria-live="polite">
<i class="ph-duotone ph-paper-plane-tilt" aria-hidden="true"></i>
Submit
</span>
<span x-show="status === 'busy'">
<span class="loading loading-spinner loading-sm"></span>
Wird gesendet...
<span data-form-submit-busy class="hidden" hidden role="status" aria-live="polite">
<span class="loading loading-spinner loading-sm" aria-hidden="true"></span>
Sending...
</span>
</button>
</div>
</form>
<div x-show="submitted" x-transition:enter x-transition:enter-opacity-0 x-transition:enter-delay-100 class="card bg-base-100 shadow-lg mt-4">
<div data-form-error class="alert alert-error mt-4 shadow-sm hidden" hidden role="alert" aria-live="assertive" aria-atomic="true"></div>
<div data-form-success class="card mt-4 border border-success/30 bg-base-100 shadow-sm hidden" hidden role="status" aria-live="polite">
<div class="card-body items-center text-center">
<div class="w-16 h-16 rounded-full bg-success/20 flex items-center justify-center mb-2">
<i class="ph-duotone ph-check text-3xl text-success"></i>
<div class="mb-2 flex h-16 w-16 items-center justify-center rounded-full bg-success/20">
<i class="ph-duotone ph-check text-3xl text-success" aria-hidden="true"></i>
</div>
<h3 class="card-title text-lg">Vielen Dank!</h3>
<p class="text-base-content/60">Ihre Nachricht wurde erfolgreich gesendet.</p>
<h3 class="card-title text-lg">Thank you!</h3>
<p class="text-base-content/60">Your message has been sent successfully.</p>
</div>
</div>
</div>
@@ -115,11 +126,11 @@ if ($id > 0):
<?php
else:
?>
<div class="form-wrapper max-w-2xl mx-auto">
<div class="card bg-base-200 border-2 border-dashed border-base-300">
<div class="card-body items-center text-center py-8">
<i class="ph-duotone ph-plus-circle text-4xl text-base-content/30"></i>
<p class="text-sm text-base-content/50 mt-2">Wählen Sie ein Formular in den Einstellungen aus</p>
<div class="form-wrapper mx-auto w-full max-w-2xl">
<div class="card border-2 border-dashed border-base-300 bg-base-200/50">
<div class="card-body items-center py-8 text-center">
<i class="ph-duotone ph-plus-circle text-4xl text-base-content/30" aria-hidden="true"></i>
<p class="text-sm text-base-content/50 mt-2">Select a form in the settings</p>
</div>
</div>
</div>
+16
View File
@@ -20,6 +20,11 @@ return [
"type" => "style",
"location" => "header",
],
[
"src" => "/assets/dist.js",
"type" => "script",
"location" => "footer",
],
],
"tables" => [
"entries" => [
@@ -30,6 +35,17 @@ return [
],
"uniqueKeys" => [],
],
"submission_limits" => [
"columns" => [
"formId" => "int NOT NULL",
"ipHash" => "char(64) NOT NULL",
"startedAt" => "int unsigned NOT NULL",
"submissions" => "int unsigned NOT NULL",
],
"uniqueKeys" => [
"form_ip" => ["formId", "ipHash"],
],
],
"definitions" => [
"columns" => [
"name" => "varchar(255) NOT NULL",
+405 -1
View File
@@ -1,5 +1,5 @@
{
"name": "dev_plugi-ext-form",
"name": "plugi-ext-form",
"lockfileVersion": 3,
"requires": true,
"packages": {
@@ -7,6 +7,43 @@
"dependencies": {
"@tailwindcss/cli": "^4.3.5",
"tailwindcss": "^4.3.5"
},
"devDependencies": {
"rolldown": "^1.3.3"
}
},
"node_modules/@emnapi/core": {
"version": "2.0.0-beta.2",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz",
"integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/wasi-threads": "2.2.0",
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/runtime": {
"version": "2.0.0-beta.2",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz",
"integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/wasi-threads": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz",
"integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@jridgewell/gen-mapping": {
@@ -54,6 +91,38 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@napi-rs/wasm-runtime": {
"version": "1.2.6",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz",
"integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@tybys/wasm-util": "^0.10.3"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
},
"peerDependencies": {
"@emnapi/core": "^1.7.1 || 2.0.0-beta.2",
"@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2"
}
},
"node_modules/@oxc-project/types": {
"version": "0.159.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.159.0.tgz",
"integrity": "sha512-QWjWhxheluOJ82kDHNyps00UvRpQCtI34B5A/SzpgQycUD/79FuvT4I0aQIfE/bdPwKmX4QPftnywFBH6FxJhQ==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/oxc-project"
}
},
"node_modules/@parcel/watcher": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz",
@@ -328,6 +397,287 @@
"url": "https://opencollective.com/parcel"
}
},
"node_modules/@rolldown/binding-android-arm-eabi": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.3.3.tgz",
"integrity": "sha512-K1itOg1Xl50XyjLDa4qQZqaYsfiQbFbFRWXOEOupOsGr3whhm5ed4lgySd6Inohv2TB0+sdU4AxORKuS/TGang==",
"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.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.3.3.tgz",
"integrity": "sha512-re+E0E3YSJXjEFzdOvBgkVUev1Gg49ileia04qy+Djn0lIMBr7pnwVOYQ+4vc9XbLClCmMziasqXHM7KTmKNKQ==",
"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.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.3.3.tgz",
"integrity": "sha512-6pMLYsUiQJXPkUj/CG447hOBKtbe+hjWw/wbxe/mucoPKgnLSVRTzey7s0kXfqrjxhDd3gQ2hj6lgUKRumsIzw==",
"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.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.3.3.tgz",
"integrity": "sha512-Lz+TskwvhceQgwnP+0ox5ZeL7HDDXHKWVRpOqC1Eo05y6rYyfvvep0msGqC95kQTykXrmGgP6qwJB1NdgNZVhg==",
"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.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.3.3.tgz",
"integrity": "sha512-sIzqNDbA7GFDXU8k9/vcJyV1p45mCe+xHOLo9qD7gdbTbMlwB+SpnFoP7WSpC2iYdGfOX9pjBxCfViRn/Nu3Jw==",
"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.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.3.3.tgz",
"integrity": "sha512-HYysnZZ7HD3FM5RIBN6wDMoxtOjw4LS9HhRuQ57MsZt5XGpGRPxVpplvr7vUXRN+9MD8zb6vn1JRP06PXIuMYQ==",
"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.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.3.3.tgz",
"integrity": "sha512-XAyLqWSoEKVc8wsDbCIz5o2sBY6ye+0YByK9ib5QxFReoM1KHyThSHsdUODa1DKNzlEfae+p9QwK62LsVwo6Nw==",
"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.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.3.3.tgz",
"integrity": "sha512-oVyicDPj6vUVFRnuoQS7M2Ab8EkGWoq3a5ntyQqjtZoXfgVykIJqN2IAJSi9q9UyNoQUW0vbBLQSgGtlPJ40Kg==",
"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.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.3.3.tgz",
"integrity": "sha512-k7aFSWgUoi/X7jCst7UEof7pS5jc5ymD8mT/pdFE+pO1IBBI2+JU5Os4HEDqS/tYhetRggwM7MOiLP3cg1bSBQ==",
"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.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.3.3.tgz",
"integrity": "sha512-D5mxHpr1qIb1Pt5UT+Bm2p6vJ7+VxcxWcxZCYVDFzZwWRq9iLiEg4/ROsaXFQl1O8sDQZZJ55UoRWWMK64uH5w==",
"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.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.3.3.tgz",
"integrity": "sha512-nmW1O4BbNEmQI9+KTHbJgbDv0EuyZy64oBnRlMCtLJ8lQMIJ/H/iziQ0g2IUlHEhNrSebGvs9cRrlRj8oEfP+g==",
"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.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.3.3.tgz",
"integrity": "sha512-ivU4JFHK5nFzrRbzp3+vwYdLj8mFckH4oz3hEl5LH/YeThr9/m2N2vF3NvLevtHq6e0COimgrEVyYTwQhh4ODg==",
"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.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.3.3.tgz",
"integrity": "sha512-XxZoRIkNZ/7pFgvOA8QJmx3uFjMyVz7zS2/urzlaFffoOGclDvpUAMu3AHKT551E8JBKXLxIjpYxYMdF6Mz9vQ==",
"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.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.3.3.tgz",
"integrity": "sha512-bBl1MB2gF26PSPy3CiDLiv+A6JGI546WbsDR34LfKAywSGeBeQXaDanoDG6QdZDJs53M1QyJir5MTKTu1n4ptA==",
"cpu": [
"wasm32"
],
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/core": "2.0.0-beta.2",
"@emnapi/runtime": "2.0.0-beta.2",
"@napi-rs/wasm-runtime": "1.2.6"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
}
},
"node_modules/@rolldown/binding-win32-arm64-msvc": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.3.3.tgz",
"integrity": "sha512-6rZur0hyen4LPhOxWIg7az1YX+Eo8Vvauc0D6lFYGK/QCvN+1XpnB8aFe3jQc/PBUGIReJJnLX3sS8h33/5v7A==",
"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.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.3.3.tgz",
"integrity": "sha512-Ggzyuq1mN7claruAZH10aiiM1N3LRCoMP5xDXPdU514ulL0D2bksCWgFqEmEM2/pDzEP7Dq+dcv7IH452jtr1w==",
"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/@tailwindcss/cli": {
"version": "4.3.5",
"resolved": "https://registry.npmjs.org/@tailwindcss/cli/-/cli-4.3.5.tgz",
@@ -649,6 +999,17 @@
"node": ">= 20"
}
},
"node_modules/@tybys/wasm-util": {
"version": "0.10.5",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz",
"integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -998,6 +1359,41 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/rolldown": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.3.tgz",
"integrity": "sha512-ksB1g74e7haRy02OYm4lOQAlr6sK6hBpAY5R+YC30Gkv4L1COwF6M9umBAYAPxWpGow6Vr+IXtyDjH9fq7A+Zg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@oxc-project/types": "=0.159.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.3",
"@rolldown/binding-android-arm64": "1.3.3",
"@rolldown/binding-darwin-arm64": "1.3.3",
"@rolldown/binding-darwin-x64": "1.3.3",
"@rolldown/binding-freebsd-x64": "1.3.3",
"@rolldown/binding-linux-arm-gnueabihf": "1.3.3",
"@rolldown/binding-linux-arm64-gnu": "1.3.3",
"@rolldown/binding-linux-arm64-musl": "1.3.3",
"@rolldown/binding-linux-ppc64-gnu": "1.3.3",
"@rolldown/binding-linux-s390x-gnu": "1.3.3",
"@rolldown/binding-linux-x64-gnu": "1.3.3",
"@rolldown/binding-linux-x64-musl": "1.3.3",
"@rolldown/binding-openharmony-arm64": "1.3.3",
"@rolldown/binding-wasm32-wasi": "1.3.3",
"@rolldown/binding-win32-arm64-msvc": "1.3.3",
"@rolldown/binding-win32-x64-msvc": "1.3.3"
}
},
"node_modules/source-map-js": {
"version": "1.2.4",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz",
@@ -1025,6 +1421,14 @@
"type": "opencollective",
"url": "https://opencollective.com/webpack"
}
},
"node_modules/tslib": {
"version": "2.9.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz",
"integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==",
"dev": true,
"license": "0BSD",
"optional": true
}
}
}
+7 -1
View File
@@ -1,10 +1,16 @@
{
"type": "module",
"dependencies": {
"@tailwindcss/cli": "^4.3.5",
"tailwindcss": "^4.3.5"
},
"devDependencies": {
"rolldown": "^1.3.3"
},
"scripts": {
"dev": "npx -y @tailwindcss/cli -i ./assets/main.css -o ./assets/dist.css --watch",
"build": "npx -y @tailwindcss/cli -i ./assets/main.css -o ./assets/dist.css"
"build": "npm run build:js && npm run build:css",
"build:css": "npx -y @tailwindcss/cli -i ./assets/main.css -o ./assets/dist.css",
"build:js": "rolldown assets/main.js --file assets/dist.js -m"
}
}
@@ -1,11 +1,20 @@
<?php
phpb_requires_authenticated();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
return;
}
if (!function_exists('phpb_validate_csrf') || !phpb_validate_csrf()) {
http_response_code(403);
return;
}
$entriesRepository = new \Plugi\Extensions\Form\EntriesRepository();
if(
isset($_GET['id'])
isset($_POST['id'])
) {
$entriesRepository->destroy($_GET['id']);
$entriesRepository->destroy($_POST['id']);
}
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'listEntries', 'id' => $_GET['formId']]));
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'listEntries', 'id' => $_POST['formId'] ?? '']));
@@ -1,13 +1,22 @@
<?php
phpb_requires_authenticated();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
return;
}
if (!function_exists('phpb_validate_csrf') || !phpb_validate_csrf()) {
http_response_code(403);
return;
}
$formsRepository = new \Plugi\Extensions\Form\DefinitionsRepository();
$entriesRepository = new \Plugi\Extensions\Form\EntriesRepository();
if(
isset($_GET['id'])
isset($_POST['id'])
) {
$formsRepository->destroy($_GET['id']);
$entriesRepository->destroyWhere('formId', $_GET['id']);
$formsRepository->destroy($_POST['id']);
$entriesRepository->destroyWhere('formId', $_POST['id']);
}
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'listForms']));
@@ -1,6 +1,15 @@
<?php
phpb_requires_authenticated();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
return;
}
if (!function_exists('phpb_validate_csrf') || !phpb_validate_csrf()) {
http_response_code(403);
return;
}
$formsRepository = new \Plugi\Extensions\Form\DefinitionsRepository();
if(
+12 -17
View File
@@ -1,22 +1,17 @@
<?php
$formsRepository = new \Plugi\Extensions\Form\DefinitionsRepository();
$handler = new \Plugi\Extensions\Form\SubmissionHandler();
$rawData = file_get_contents(
'php://input',
false,
null,
0,
\Plugi\Extensions\Form\SubmissionHandler::MAX_REQUEST_BYTES + 1
);
$result = $handler->handle($_GET['id'] ?? null, is_string($rawData) ? $rawData : '');
$form = $formsRepository->findWithId($_GET['id']);
$formFinishers = json_decode($form['finishers'], true);
$finishers = new \Plugi\Extensions\Form\Finishers\FinishersRepository();
foreach ($formFinishers as $finisher) {
if ($finishers->finisherExists($finisher['type'])) {
$config = $finishers->getFinisherConfig($finisher['type']);
$instance = new $config['class'];
$instance->execute();
}
}
phpb_redirect('/', [], 201);
http_response_code($result['status']);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($result['body'], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
@@ -0,0 +1,581 @@
<?php
namespace FormExtensionTests {
require_once dirname(__DIR__) . '/admin/Classes/Finishers/DefaultFinisher.php';
require_once dirname(__DIR__) . '/admin/Classes/Finishers/SendEmailToAdmin.php';
require_once dirname(__DIR__) . '/admin/Classes/Finishers/SendConfirmationEmailToSubmitter.php';
require_once dirname(__DIR__) . '/admin/Classes/Finishers/SendWebhook.php';
require_once dirname(__DIR__) . '/admin/Classes/Finishers/FinishersRepository.php';
require_once dirname(__DIR__) . '/admin/Classes/SubmissionRateLimiter.php';
class TestMailer
{
public $calls = [];
public $result = true;
public function send(string $to, string $subject, string $message): bool
{
$this->calls[] = [$to, $subject, $message];
return $this->result;
}
}
class TestConfirmationFinisher extends \Plugi\Extensions\Form\Finishers\SendConfirmationEmailToSubmitter
{
protected function sendMail(string $recipient, string $subject, string $message): bool
{
$GLOBALS['confirmationEmails'][] = [$recipient, $subject, $message];
return parent::sendMail($recipient, $subject, $message);
}
}
class TestWebhookFinisher extends \Plugi\Extensions\Form\Finishers\SendWebhook
{
protected function sendRequest(string $url, string $method, ?string $bearerToken, string $payload, int $timeout): ?int
{
$GLOBALS['webhookRequests'][] = [
$url,
$method,
$bearerToken,
json_decode($payload, true),
$timeout,
];
return $GLOBALS['webhookResponseCode'] ?? null;
}
}
function startWebhookPeer(int $responseCode): array
{
$server = stream_socket_server('tcp://127.0.0.1:0', $errorCode, $errorMessage);
if (!is_resource($server)) {
throw new \RuntimeException('Could not start the local webhook test peer.');
}
$address = stream_socket_get_name($server, false);
$port = (int) substr(strrchr($address, ':'), 1);
$pid = pcntl_fork();
if ($pid === -1) {
fclose($server);
throw new \RuntimeException('Could not start the local webhook test peer process.');
}
if ($pid === 0) {
$client = stream_socket_accept($server, 5);
fclose($server);
if (!is_resource($client)) {
exit(1);
}
stream_set_timeout($client, 5);
$requestLine = fgets($client, 2048);
$headers = [];
while (($line = fgets($client, 2048)) !== false && $line !== "\r\n") {
$header = explode(':', trim($line), 2);
if (count($header) === 2) {
$headers[strtolower($header[0])] = trim($header[1]);
}
}
$contentLength = (int) ($headers['content-length'] ?? 0);
$body = '';
while (strlen($body) < $contentLength) {
$chunk = fread($client, $contentLength - strlen($body));
if (!is_string($chunk) || $chunk === '') {
break;
}
$body .= $chunk;
}
$payload = json_decode($body, true);
$passed = $requestLine === "POST /receive HTTP/1.1\r\n"
&& ($headers['content-type'] ?? '') === 'application/json'
&& ($headers['authorization'] ?? '') === 'Bearer peer-token'
&& is_array($payload)
&& ($payload['formId'] ?? null) === 8
&& ($payload['formName'] ?? null) === 'Contact form'
&& ($payload['fields']['name'] ?? null) === 'Ada'
&& strlen($body) === $contentLength;
$reason = $responseCode === 202 ? 'Accepted' : 'Service Unavailable';
fwrite($client, 'HTTP/1.1 ' . $responseCode . ' ' . $reason . "\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
fclose($client);
exit($passed ? 0 : 1);
}
fclose($server);
return [$port, $pid];
}
class FirstFinisher extends \Plugi\Extensions\Form\Finishers\DefaultFinisher
{
public function execute(): bool
{
if ($this->formId !== 7 || $this->getFormName() !== 'Contact form' || $this->getEntryFields()['name'] !== 'Ada' || ($this->options['marker'] ?? null) !== 'passed') {
throw new \RuntimeException('The submission context or action options were not passed to the finisher.');
}
$GLOBALS['formFinisherCalls'][] = 'first';
return $GLOBALS['formFinisherResults']['first'];
}
}
class SecondFinisher extends \Plugi\Extensions\Form\Finishers\DefaultFinisher
{
public function execute(): bool
{
$GLOBALS['formFinisherCalls'][] = 'second';
return $GLOBALS['formFinisherResults']['second'];
}
}
class DefinitionsRepository
{
private $form;
public function __construct($form)
{
$this->form = $form;
}
public function findWithId($id)
{
return $this->form;
}
}
class FinishersRepository
{
private $finishers = [
'first' => FirstFinisher::class,
'second' => SecondFinisher::class,
'sendConfirmationEmailToSubmitter' => TestConfirmationFinisher::class,
'sendWebhook' => TestWebhookFinisher::class,
];
public function finisherExists(string $key): bool
{
return isset($this->finishers[$key]);
}
public function getFinisherConfig(string $key): array
{
return ['class' => $this->finishers[$key]];
}
}
class RateLimitDatabase
{
public array $rows = [];
public function query(string $query, array $parameters = []): bool
{
if (str_starts_with($query, 'INSERT IGNORE')) {
$key = $parameters[0] . ':' . $parameters[1];
$this->rows[$key] ??= ['startedAt' => $parameters[2], 'submissions' => 0];
return true;
}
if (str_starts_with($query, 'UPDATE')) {
$key = $parameters[2] . ':' . $parameters[3];
$this->rows[$key] = ['startedAt' => $parameters[0], 'submissions' => $parameters[1]];
return true;
}
if (str_starts_with($query, 'DELETE')) {
return true;
}
throw new \RuntimeException('Unexpected rate limiter query.');
}
public function select(string $query, array $parameters): array
{
$key = $parameters[0] . ':' . $parameters[1];
return isset($this->rows[$key]) ? [$this->rows[$key]] : [];
}
public function transaction(callable $callback): mixed
{
return $callback();
}
}
}
namespace Plugi {
class Extensions
{
public static function getSettings(string $name): array
{
return $GLOBALS['extensionSettings'][$name] ?? [];
}
}
}
namespace {
require_once dirname(__DIR__) . '/admin/Classes/SubmissionHandler.php';
use FormExtensionTests\DefinitionsRepository as TestDefinitionsRepository;
use FormExtensionTests\FinishersRepository as TestFinishersRepository;
use FormExtensionTests\RateLimitDatabase as TestRateLimitDatabase;
use Plugi\Extensions\Form\SubmissionHandler;
if (!function_exists('phpb_instance')) {
function phpb_instance(string $name, array $params = []): ?object
{
return $name === 'mail' ? ($GLOBALS['testMailer'] ?? null) : null;
}
}
function assertSameValue($expected, $actual, string $message): void
{
if ($expected !== $actual) {
throw new \RuntimeException($message . ': expected ' . var_export($expected, true) . ', got ' . var_export($actual, true));
}
}
function makeHandler($form, $rateLimiter = null): SubmissionHandler
{
return new SubmissionHandler(new TestDefinitionsRepository($form), new TestFinishersRepository(), $rateLimiter ?? new AllowSubmissionRateLimiter());
}
class AllowSubmissionRateLimiter
{
public function consume(int $formId, string $clientIp): bool
{
return true;
}
}
class RejectSubmissionRateLimiter
{
public function consume(int $formId, string $clientIp): bool
{
return false;
}
}
$rateLimitDatabase = new TestRateLimitDatabase();
$rateLimiter = new \Plugi\Extensions\Form\SubmissionRateLimiter($rateLimitDatabase);
for ($submission = 0; $submission < 5; $submission++) {
assertSameValue(true, $rateLimiter->consume(7, '203.0.113.1'), 'Submissions within the limit must be allowed.');
}
assertSameValue(false, $rateLimiter->consume(7, '203.0.113.1'), 'Submissions over the limit must be rejected.');
assertSameValue(true, $rateLimiter->consume(8, '203.0.113.1'), 'Rate limits must be scoped to each form.');
assertSameValue(true, $rateLimiter->consume(7, '203.0.113.2'), 'Rate limits must be scoped to each client IP.');
$rateLimitKey = '7:' . hash('sha256', '203.0.113.1');
$rateLimitDatabase->rows[$rateLimitKey]['startedAt'] = time() - 601;
$rateLimitDatabase->rows[$rateLimitKey]['submissions'] = 5;
assertSameValue(true, $rateLimiter->consume(7, '203.0.113.1'), 'Expired rate limit windows must reset.');
assertSameValue(1, $rateLimitDatabase->rows[$rateLimitKey]['submissions'], 'The reset window must begin at one submission.');
function validForm(array $finishers = []): array
{
return [
'name' => 'Contact form',
'fields' => json_encode([
['name' => 'name', 'label' => 'Name', 'type' => 'text', 'required' => true],
]),
'finishers' => json_encode($finishers),
];
}
$GLOBALS['testMailer'] = new \FormExtensionTests\TestMailer();
$form = validForm([
['type' => 'first', 'options' => ['marker' => 'passed']],
['type' => 'second'],
]);
$validPayload = json_encode(['fields' => ['name' => 'Ada']]);
$GLOBALS['formFinisherCalls'] = [];
$GLOBALS['formFinisherResults'] = ['first' => true, 'second' => true];
$result = makeHandler($form)->handle(7, $validPayload);
assertSameValue(200, $result['status'], 'Successful actions must produce a successful response');
assertSameValue(true, $result['body']['success'], 'Successful actions must report success');
assertSameValue(['first', 'second'], $GLOBALS['formFinisherCalls'], 'Actions must run in configured order');
$GLOBALS['formFinisherCalls'] = [];
$result = makeHandler($form, new RejectSubmissionRateLimiter())->handle(7, $validPayload);
assertSameValue(429, $result['status'], 'Rate-limited submissions must be rejected');
assertSameValue([], $GLOBALS['formFinisherCalls'], 'Rate-limited submissions must not run actions');
$GLOBALS['formFinisherCalls'] = [];
$result = makeHandler($form)->handle(7, str_repeat('x', 65537));
assertSameValue(413, $result['status'], 'Oversized request bodies must be rejected');
assertSameValue([], $GLOBALS['formFinisherCalls'], 'Oversized requests must not run actions');
$GLOBALS['formFinisherCalls'] = [];
$oversizedField = json_encode(['fields' => ['name' => str_repeat('A', 16385)]]);
$result = makeHandler($form)->handle(7, $oversizedField);
assertSameValue(422, $result['status'], 'Oversized field values must be rejected');
assertSameValue([], $GLOBALS['formFinisherCalls'], 'Oversized fields must not run actions');
$tooManyFields = array_fill_keys(array_map('strval', range(1, 101)), 'value');
$result = makeHandler($form)->handle(7, json_encode(['fields' => $tooManyFields]));
assertSameValue(422, $result['status'], 'Submissions with too many fields must be rejected');
$submitRoute = file_get_contents(dirname(__DIR__) . '/routes/submit.php');
if (strpos($submitRoute, 'MAX_REQUEST_BYTES + 1') === false) {
throw new \RuntimeException('The submission route must read no more than the configured body limit plus one byte.');
}
$GLOBALS['formFinisherCalls'] = [];
$GLOBALS['formFinisherResults'] = ['first' => false, 'second' => true];
$result = makeHandler($form)->handle(7, $validPayload);
assertSameValue(500, $result['status'], 'A failed action must fail the submission');
assertSameValue(false, $result['body']['success'], 'A failed action must not report success');
assertSameValue(['first', 'second'], $GLOBALS['formFinisherCalls'], 'Actions must run in configured order after a failure');
assertSameValue([false, true], array_column($result['body']['actions'], 'success'), 'Each action result must be reported');
$GLOBALS['formFinisherCalls'] = [];
$result = makeHandler($form)->handle(7, '{invalid');
assertSameValue(400, $result['status'], 'Malformed JSON must be rejected');
assertSameValue([], $GLOBALS['formFinisherCalls'], 'Malformed requests must not run actions');
$result = makeHandler($form)->handle(7, json_encode(['fields' => []]));
assertSameValue(422, $result['status'], 'Missing required values must be rejected');
$invalidForm = validForm();
$invalidForm['fields'] = '{invalid';
$result = makeHandler($invalidForm)->handle(7, $validPayload);
assertSameValue(422, $result['status'], 'Malformed form configuration must be rejected');
$result = makeHandler(null)->handle(7, $validPayload);
assertSameValue(404, $result['status'], 'Missing forms must be rejected');
$unknownForm = validForm([['type' => 'unknown']]);
$result = makeHandler($unknownForm)->handle(7, $validPayload);
assertSameValue(422, $result['status'], 'Unknown actions must be rejected');
$malformedOptionsForm = validForm([['type' => 'first', 'options' => 'invalid']]);
$result = makeHandler($malformedOptionsForm)->handle(7, $validPayload);
assertSameValue(422, $result['status'], 'Malformed action options must be rejected');
$view = file_get_contents(dirname(__DIR__) . '/blocks/form-wrapper/view.php');
$frontendScript = file_get_contents(dirname(__DIR__) . '/assets/main.js');
if (strpos($view, 'data-form-wrapper') === false || preg_match('/\bx-(?:data|model|show|on|transition|text)\b/', $view) === 1) {
throw new \RuntimeException('The public form wrapper must use vanilla JavaScript hooks without Alpine directives.');
}
if (strpos($frontendScript, 'if (!response.ok || !result || !result.success)') === false || strpos($frontendScript, 'setVisible(errorMessage, true)') === false) {
throw new \RuntimeException('The frontend must check the response and expose a retryable error state.');
}
$responseCheck = strpos($frontendScript, 'if (!response.ok || !result || !result.success)');
$successState = strpos($frontendScript, 'setVisible(successMessage, true)');
if ($successState === false || $responseCheck === false || $responseCheck > $successState) {
throw new \RuntimeException('The frontend may only show its success state after a successful response.');
}
if (strpos($frontendScript, 'finally') === false || strpos($frontendScript, 'setBusy(form, false)') === false) {
throw new \RuntimeException('The frontend must restore its busy state after a submission attempt.');
}
$editor = file_get_contents(dirname(__DIR__) . '/admin/Views/EditForm.php');
foreach (['finisherDefinitions', 'getFinisherSettings', 'finisher.options[setting.name]', 'setting.type'] as $setting) {
if (strpos($editor, $setting) === false) {
throw new \RuntimeException('The action editor is missing registry-driven setting support: ' . $setting);
}
}
$finisherConfig = require dirname(__DIR__) . '/admin/Classes/Finishers/config.php';
assertSameValue(
\Plugi\Extensions\Form\Finishers\SendConfirmationEmailToSubmitter::class,
$finisherConfig['finishers']['sendConfirmationEmailToSubmitter']['class'],
'The confirmation finisher must be registered'
);
assertSameValue(
\Plugi\Extensions\Form\Finishers\SendWebhook::class,
$finisherConfig['finishers']['sendWebhook']['class'],
'The webhook finisher must be registered'
);
assertSameValue(
['url', 'method', 'bearerToken', 'timeout'],
array_column($finisherConfig['finishers']['sendWebhook']['settings'], 'name'),
'Webhook settings must be exposed to the editor'
);
assertSameValue(
['recipient', 'subject'],
array_column($finisherConfig['finishers']['sendMailToAdmin']['settings'], 'name'),
'Admin notification settings must be exposed to the editor'
);
$editorFinisherConfig = (new \Plugi\Extensions\Form\Finishers\FinishersRepository())->getEditorConfig();
assertSameValue('Send webhook', $editorFinisherConfig['sendWebhook']['label'], 'The editor registry must expose the webhook label');
assertSameValue(false, array_key_exists('class', $editorFinisherConfig['sendWebhook']), 'The editor registry must not expose runtime class names');
$confirmationContext = [
'formId' => 8,
'form' => [
'name' => 'Contact form',
'formFields' => [['name' => 'email', 'label' => 'Email', 'type' => 'email']],
],
'rawData' => json_encode(['fields' => ['email' => 'ada@example.com']]),
'submission' => ['fields' => ['email' => 'ada@example.com']],
];
$confirmationOptions = [
'recipientField' => 'email',
'subject' => 'We received your message',
'message' => 'Thanks, Ada.',
];
$GLOBALS['confirmationEmails'] = [];
$GLOBALS['testMailer']->calls = [];
$GLOBALS['testMailer']->result = true;
$confirmationFinisher = new \FormExtensionTests\TestConfirmationFinisher($confirmationContext, $confirmationOptions);
assertSameValue(true, $confirmationFinisher->execute(), 'A valid recipient should be sent a confirmation');
assertSameValue(
[['ada@example.com', 'We received your message', 'Thanks, Ada.']],
$GLOBALS['confirmationEmails'],
'The configured recipient, subject, and message must be sent'
);
assertSameValue(
[['ada@example.com', 'We received your message', 'Thanks, Ada.']],
$GLOBALS['testMailer']->calls,
'The confirmation finisher must use the configured core mailer'
);
$GLOBALS['testMailer']->result = false;
$failedConfirmationFinisher = new \FormExtensionTests\TestConfirmationFinisher($confirmationContext, $confirmationOptions);
assertSameValue(false, $failedConfirmationFinisher->execute(), 'A failed core mail send must fail the confirmation action');
assertSameValue(2, count($GLOBALS['testMailer']->calls), 'The failed confirmation must be sent through the core mailer');
$invalidRecipientContext = $confirmationContext;
$invalidRecipientContext['submission']['fields']['email'] = 'not-an-email';
$invalidRecipientFinisher = new \FormExtensionTests\TestConfirmationFinisher($invalidRecipientContext, $confirmationOptions);
assertSameValue(false, $invalidRecipientFinisher->execute(), 'An invalid recipient must fail');
assertSameValue(2, count($GLOBALS['confirmationEmails']), 'An invalid recipient must not send email');
assertSameValue(2, count($GLOBALS['testMailer']->calls), 'An invalid recipient must not call the core mailer');
$webhookContext = [
'formId' => 8,
'form' => [
'name' => 'Contact form',
'formFields' => [['name' => 'name', 'label' => 'Name', 'type' => 'text']],
],
'submission' => ['fields' => ['name' => 'Ada']],
];
$webhookOptions = [
'url' => 'https://hooks.example.test/receive',
'method' => 'POST',
'bearerToken' => 'test-secret',
'timeout' => 8,
];
$GLOBALS['webhookRequests'] = [];
$GLOBALS['webhookResponseCode'] = 204;
$webhookFinisher = new \FormExtensionTests\TestWebhookFinisher($webhookContext, $webhookOptions);
assertSameValue(true, $webhookFinisher->execute(), 'A successful webhook response must succeed');
assertSameValue(
[[
'https://hooks.example.test/receive',
'POST',
'test-secret',
['formId' => 8, 'formName' => 'Contact form', 'fields' => ['name' => 'Ada']],
8,
]],
$GLOBALS['webhookRequests'],
'The webhook must receive configured request options and the submission payload'
);
$GLOBALS['webhookResponseCode'] = 503;
$failedWebhookFinisher = new \FormExtensionTests\TestWebhookFinisher($webhookContext, $webhookOptions);
assertSameValue(false, $failedWebhookFinisher->execute(), 'A non-success webhook response must fail');
$invalidWebhookOptions = $webhookOptions;
$invalidWebhookOptions['url'] = 'file:///etc/passwd';
$invalidWebhookFinisher = new \FormExtensionTests\TestWebhookFinisher($webhookContext, $invalidWebhookOptions);
assertSameValue(false, $invalidWebhookFinisher->execute(), 'An unsupported webhook URL scheme must fail');
assertSameValue(2, count($GLOBALS['webhookRequests']), 'Invalid webhook options must not make a request');
$invalidWebhookOptions = $webhookOptions;
$invalidWebhookOptions['bearerToken'] = "token\r\nInjected: true";
$invalidWebhookFinisher = new \FormExtensionTests\TestWebhookFinisher($webhookContext, $invalidWebhookOptions);
assertSameValue(false, $invalidWebhookFinisher->execute(), 'Webhook bearer tokens must reject header injection');
assertSameValue(2, count($GLOBALS['webhookRequests']), 'Unsafe webhook credentials must not make a request');
[$webhookPort, $webhookPid] = \FormExtensionTests\startWebhookPeer(202);
$liveWebhookOptions = [
'url' => 'http://127.0.0.1:' . $webhookPort . '/receive',
'method' => 'POST',
'bearerToken' => 'peer-token',
'timeout' => 3,
];
$liveWebhookFinisher = new \Plugi\Extensions\Form\Finishers\SendWebhook($webhookContext, $liveWebhookOptions);
assertSameValue(true, $liveWebhookFinisher->execute(), 'A real 2xx webhook response must succeed');
pcntl_waitpid($webhookPid, $webhookStatus);
assertSameValue(true, pcntl_wifexited($webhookStatus) && pcntl_wexitstatus($webhookStatus) === 0, 'The webhook peer must receive the expected request');
[$webhookPort, $webhookPid] = \FormExtensionTests\startWebhookPeer(503);
$liveWebhookOptions['url'] = 'http://127.0.0.1:' . $webhookPort . '/receive';
$failedLiveWebhookFinisher = new \Plugi\Extensions\Form\Finishers\SendWebhook($webhookContext, $liveWebhookOptions);
assertSameValue(false, $failedLiveWebhookFinisher->execute(), 'A real non-2xx webhook response must fail');
pcntl_waitpid($webhookPid, $webhookStatus);
assertSameValue(true, pcntl_wifexited($webhookStatus) && pcntl_wexitstatus($webhookStatus) === 0, 'The failing-response peer must still receive the expected request');
$webhookForm = validForm([['type' => 'sendWebhook', 'options' => $webhookOptions]]);
$GLOBALS['webhookResponseCode'] = 202;
$result = makeHandler($webhookForm)->handle(8, $validPayload);
assertSameValue(true, $result['body']['success'], 'A successful webhook action must report success');
$GLOBALS['webhookResponseCode'] = 500;
$result = makeHandler($webhookForm)->handle(8, $validPayload);
assertSameValue(500, $result['status'], 'A failed webhook action must fail the submission');
assertSameValue(false, $result['body']['actions'][0]['success'], 'A failed webhook must not report action success');
$staleFieldOptions = $confirmationOptions;
$staleFieldOptions['recipientField'] = 'removed_email';
$staleFieldFinisher = new \FormExtensionTests\TestConfirmationFinisher($confirmationContext, $staleFieldOptions);
assertSameValue(false, $staleFieldFinisher->execute(), 'A stale recipient field selection must fail');
assertSameValue(2, count($GLOBALS['confirmationEmails']), 'A stale field selection must not send email');
assertSameValue(2, count($GLOBALS['testMailer']->calls), 'A stale field selection must not call the core mailer');
$GLOBALS['extensionSettings']['form'] = ['email' => ['value' => 'admin@example.com']];
$adminContext = [
'formId' => 8,
'form' => [
'name' => 'Contact form',
'formFields' => [
['name' => 'name', 'label' => 'Name', 'type' => 'text'],
['name' => 'email', 'label' => 'Email', 'type' => 'email'],
],
],
'submission' => ['fields' => ['name' => 'Ada', 'email' => 'ada@example.com']],
];
$GLOBALS['testMailer']->calls = [];
$GLOBALS['testMailer']->result = true;
$adminFinisher = new \Plugi\Extensions\Form\Finishers\SendEmailToAdmin($adminContext);
assertSameValue(true, $adminFinisher->execute(), 'A successful core mail send must succeed for admin notifications');
assertSameValue(
[['admin@example.com', 'Form submission: Contact form', "Name: Ada\nEmail: ada@example.com\n"]],
$GLOBALS['testMailer']->calls,
'The admin finisher must preserve message composition and use the core mailer'
);
$GLOBALS['testMailer']->result = false;
$failedAdminFinisher = new \Plugi\Extensions\Form\Finishers\SendEmailToAdmin($adminContext);
assertSameValue(false, $failedAdminFinisher->execute(), 'A failed core mail send must fail the admin notification action');
assertSameValue(2, count($GLOBALS['testMailer']->calls), 'The failed admin notification must be sent through the core mailer');
$GLOBALS['extensionSettings']['form']['email']['value'] = 'invalid-address';
$invalidAdminFinisher = new \Plugi\Extensions\Form\Finishers\SendEmailToAdmin($adminContext);
assertSameValue(false, $invalidAdminFinisher->execute(), 'An invalid admin recipient must fail');
assertSameValue(2, count($GLOBALS['testMailer']->calls), 'An invalid admin recipient must not call the core mailer');
$GLOBALS['testMailer']->result = true;
$configuredAdminFinisher = new \Plugi\Extensions\Form\Finishers\SendEmailToAdmin($adminContext, [
'recipient' => 'configured@example.com',
'subject' => 'New submission',
]);
assertSameValue(true, $configuredAdminFinisher->execute(), 'Per-form admin email settings must override extension defaults');
assertSameValue(
['configured@example.com', 'New submission', "Name: Ada\nEmail: ada@example.com\n"],
$GLOBALS['testMailer']->calls[2],
'The admin finisher must use its configured recipient and subject'
);
$confirmationForm = [
'name' => 'Contact form',
'fields' => json_encode([['name' => 'email', 'label' => 'Email', 'type' => 'email']]),
'finishers' => json_encode([[
'type' => 'sendConfirmationEmailToSubmitter',
'options' => $confirmationOptions,
]]),
];
$GLOBALS['confirmationEmails'] = [];
$GLOBALS['testMailer']->result = true;
$result = makeHandler($confirmationForm)->handle(8, json_encode(['fields' => ['email' => 'ada@example.com']]));
assertSameValue(true, $result['body']['success'], 'A valid confirmation action must report success');
$result = makeHandler($confirmationForm)->handle(8, json_encode(['fields' => ['email' => '']]));
assertSameValue(500, $result['status'], 'A missing optional recipient must report action failure');
assertSameValue(false, $result['body']['actions'][0]['success'], 'A missing recipient must not report action success');
echo "Submission handler checks passed.\n";
}
@@ -0,0 +1,209 @@
<?php
namespace Plugi\Extensions\Form {
class DefinitionsRepository
{
public static array $form = [];
public static array $created = [];
public static array $destroyed = [];
public function findWithId($id)
{
return self::$form;
}
public function create(array $data): null|object|array
{
self::$created[] = $data;
return null;
}
public function update($instance, array $data): void
{
}
public function destroy($id): void
{
self::$destroyed[] = $id;
}
}
class EntriesRepository
{
public static array $destroyed = [];
public static array $deleted = [];
public function destroy($id): void
{
self::$deleted[] = $id;
}
public function destroyWhere($column, $value): void
{
self::$destroyed[] = [$column, $value];
}
}
}
namespace Plugi\Extensions\Form\Finishers {
class FinishersRepository
{
public function getEditorConfig(): array
{
return [];
}
}
}
namespace {
use Plugi\Extensions\Form\DefinitionsRepository;
use Plugi\Extensions\Form\EntriesRepository;
class FormAdminSecurityRedirect extends RuntimeException
{
}
function assertFormAdminSecurity(bool $condition, string $message): void
{
if (!$condition) {
throw new RuntimeException($message);
}
}
function phpb_requires_authenticated(): void
{
if (!($GLOBALS['formAdminSecurityAuthenticated'] ?? false)) {
throw new RuntimeException('The form admin route did not require authentication.');
}
}
function phpb_validate_csrf(): bool
{
return $GLOBALS['formAdminSecurityCsrfValid'] ?? false;
}
function phpb_csrf_field(): void
{
echo '<input type="hidden" name="_csrf_token" value="test-token">';
}
function phpb_e(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
function phpb_url(string $module, array $parameters = []): string
{
return $module . '?' . http_build_query($parameters);
}
function phpb_redirect(string $url, array $flashData = [], int $statusCode = 302): void
{
throw new FormAdminSecurityRedirect();
}
function includeFormSecurityRoute(string $route): void
{
try {
require $route;
} catch (FormAdminSecurityRedirect) {
}
}
$projectRoot = dirname(__DIR__, 3);
$apacheRules = file_get_contents($projectRoot . '/.htaccess');
assertFormAdminSecurity(
is_string($apacheRules) && str_contains($apacheRules, 'Require all denied'),
'Apache must deny requests for hidden files such as the root .env file.'
);
$attack = '</script><script>window.pwned=1</script>';
DefinitionsRepository::$form = [
'id' => 7,
'name' => 'Test form',
'fields' => json_encode([['name' => $attack]]),
'finishers' => '[]',
];
$_GET = ['id' => '7'];
ob_start();
require dirname(__DIR__) . '/admin/Views/EditForm.php';
$editor = ob_get_clean();
assertFormAdminSecurity(
!str_contains($editor, $attack) && str_contains($editor, '\\u003C'),
'Stored form JSON must be escaped before it is emitted inside a script element.'
);
assertFormAdminSecurity(
str_contains($editor, 'name="_csrf_token"'),
'Form saves must submit a CSRF token.'
);
$GLOBALS['formAdminSecurityAuthenticated'] = true;
$GLOBALS['formAdminSecurityCsrfValid'] = false;
$saveRoute = dirname(__DIR__) . '/routes/saveForm.php';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_POST = [];
http_response_code(200);
includeFormSecurityRoute($saveRoute);
assertFormAdminSecurity(http_response_code() === 405, 'Form saves must reject non-POST requests.');
assertFormAdminSecurity(DefinitionsRepository::$created === [], 'A GET request must not save a form.');
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = ['name' => 'Rejected form', 'fields' => '[]', 'finishers' => '[]'];
http_response_code(200);
includeFormSecurityRoute($saveRoute);
assertFormAdminSecurity(http_response_code() === 403, 'Form saves must reject invalid CSRF tokens.');
assertFormAdminSecurity(DefinitionsRepository::$created === [], 'An invalid CSRF token must not save a form.');
$GLOBALS['formAdminSecurityCsrfValid'] = true;
$_POST['_csrf_token'] = 'test-token';
includeFormSecurityRoute($saveRoute);
assertFormAdminSecurity(count(DefinitionsRepository::$created) === 1, 'A valid POST should save a form.');
$deleteRoute = dirname(__DIR__) . '/routes/deleteForm.php';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_GET = ['id' => '7'];
$_POST = [];
http_response_code(200);
includeFormSecurityRoute($deleteRoute);
assertFormAdminSecurity(http_response_code() === 405, 'Form deletion must reject non-POST requests.');
assertFormAdminSecurity(DefinitionsRepository::$destroyed === [], 'A GET request must not delete a form.');
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = ['id' => '7'];
$GLOBALS['formAdminSecurityCsrfValid'] = false;
http_response_code(200);
includeFormSecurityRoute($deleteRoute);
assertFormAdminSecurity(http_response_code() === 403, 'Form deletion must reject invalid CSRF tokens.');
assertFormAdminSecurity(DefinitionsRepository::$destroyed === [], 'An invalid CSRF token must not delete a form.');
$_POST = ['id' => '7', '_csrf_token' => 'test-token'];
$GLOBALS['formAdminSecurityCsrfValid'] = true;
includeFormSecurityRoute($deleteRoute);
assertFormAdminSecurity(DefinitionsRepository::$destroyed === ['7'], 'A valid POST should delete the form.');
assertFormAdminSecurity(EntriesRepository::$destroyed === [['formId', '7']], 'Deleting a form should still delete its entries.');
$deleteEntryRoute = dirname(__DIR__) . '/routes/deleteEntry.php';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_GET = ['id' => '12', 'formId' => '7'];
$_POST = [];
http_response_code(200);
includeFormSecurityRoute($deleteEntryRoute);
assertFormAdminSecurity(http_response_code() === 405, 'Entry deletion must reject non-POST requests.');
assertFormAdminSecurity(EntriesRepository::$deleted === [], 'A GET request must not delete an entry.');
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = ['id' => '12', 'formId' => '7'];
$GLOBALS['formAdminSecurityCsrfValid'] = false;
http_response_code(200);
includeFormSecurityRoute($deleteEntryRoute);
assertFormAdminSecurity(http_response_code() === 403, 'Entry deletion must reject invalid CSRF tokens.');
assertFormAdminSecurity(EntriesRepository::$deleted === [], 'An invalid CSRF token must not delete an entry.');
$_POST['_csrf_token'] = 'test-token';
$GLOBALS['formAdminSecurityCsrfValid'] = true;
includeFormSecurityRoute($deleteEntryRoute);
assertFormAdminSecurity(EntriesRepository::$deleted === ['12'], 'A valid POST should delete an entry.');
fwrite(STDOUT, "PASS: form admin actions require POST and CSRF, and stored JSON is script-safe.\n");
}
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2023 Paul Spenke
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,26 @@
<?php
$snippet = \Plugi\Setting::get('ext--tracking--head') ?? '';
?>
<section class="card border border-base-300/60 bg-base-100 shadow-sm" aria-labelledby="tracking-settings-title">
<div class="card-body gap-5 p-4 sm:p-6 lg:p-8">
<div>
<h2 class="card-title text-xl" id="tracking-settings-title">Tracking snippet</h2>
<p class="mt-1 text-sm text-base-content/60">Add one HTML or JavaScript snippet to the public page head.</p>
</div>
<div class="alert alert-warning" role="alert">
<i class="ph ph-warning-circle" aria-hidden="true"></i>
<span>Saved code is inserted as-is and executes on every public page. Only save code you trust.</span>
</div>
<form method="post" action="<?= phpb_e(phpb_full_url('/ext--tracking/save')) ?>" class="space-y-4">
<?php phpb_csrf_field(); ?>
<div class="form-control w-full">
<label class="label" for="tracking-snippet">
<span class="label-text">HTML / JavaScript</span>
</label>
<textarea id="tracking-snippet" name="snippet" rows="14" spellcheck="false" class="textarea textarea-bordered w-full font-mono"><?= phpb_e($snippet) ?></textarea>
</div>
<button type="submit" class="btn btn-primary">Save snippet</button>
</form>
</div>
</section>
+9
View File
@@ -0,0 +1,9 @@
<?php
return [
'title' => 'Tracking',
'author' => 'Paul Spenke',
'identifier' => 'tracking',
'licence' => 'MIT',
'version' => '1.0.0',
];
@@ -0,0 +1,16 @@
<?php
use Plugi\Extensions;
use Plugi\Setting;
Extensions::addRoutes([
'/ext--tracking/save' => __DIR__ . '/routes/save.php',
]);
Extensions::registerBackend('tracking', [
'title' => 'Tracking',
'include' => __DIR__ . '/admin/tracking.php',
'icon' => '<i class="ph ph-code"></i>',
]);
Extensions::registerHtmlBlock(static fn (): string => Setting::get('ext--tracking--head') ?? '', 'head');
@@ -0,0 +1,22 @@
<?php
phpb_requires_authenticated();
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !phpb_validate_csrf()) {
http_response_code(403);
exit('Forbidden');
}
if (!isset($_POST['snippet']) || !is_string($_POST['snippet'])) {
http_response_code(400);
exit('Invalid snippet');
}
$saved = (new \Plugi\Repositories\SettingRepository())->updateSettings([
'ext--tracking--head' => $_POST['snippet'],
]);
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--tracking']), [
'message-type' => $saved ? 'success' : 'error',
'message' => $saved ? 'Tracking snippet saved.' : 'Tracking snippet could not be saved.',
]);
@@ -0,0 +1,185 @@
<?php
require_once __DIR__ . '/../../../plugi-core/src/Contracts/SettingRepositoryContract.php';
require_once __DIR__ . '/../../../plugi-core/src/Core/DB.php';
require_once __DIR__ . '/../../../plugi-core/src/Extensions.php';
require_once __DIR__ . '/../../../plugi-core/src/Repositories/BaseRepository.php';
require_once __DIR__ . '/../../../plugi-core/src/Repositories/SettingRepository.php';
require_once __DIR__ . '/../../../plugi-core/src/Contracts/SettingContract.php';
require_once __DIR__ . '/../../../plugi-core/src/Setting.php';
function phpb_remove_non_alpha_numeric(string $value): string
{
return preg_replace('/\W*/', '', $value);
}
class TrackingTestDatabase extends \Plugi\Core\DB
{
public function __construct()
{
$this->pdo = new PDO('sqlite::memory:');
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->exec('CREATE TABLE settings (id INTEGER PRIMARY KEY AUTOINCREMENT, setting TEXT NOT NULL UNIQUE, value TEXT NOT NULL, is_array INTEGER NOT NULL DEFAULT 0)');
$this->databaseName = 'tracking_test';
}
}
class TrackingTestRedirect extends RuntimeException
{
public function __construct(public string $url, public array $flashData)
{
parent::__construct('Redirect requested.');
}
}
class TrackingTestAuthenticationRequired extends RuntimeException
{
}
function phpb_requires_authenticated(): void
{
if (!($GLOBALS['trackingTestAuthenticated'] ?? false)) {
throw new TrackingTestAuthenticationRequired();
}
}
function phpb_validate_csrf(): bool
{
return $GLOBALS['trackingTestCsrfValid'] ?? false;
}
function phpb_e(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
function phpb_csrf_field(): void
{
echo '<input type="hidden" name="_token" value="test">';
}
function phpb_full_url(string $path): string
{
return '/plugi' . $path;
}
function phpb_url(string $module, array $parameters = []): string
{
return $module . '?' . http_build_query($parameters);
}
function phpb_redirect(string $url, array $flashData = [], int $statusCode = 302): void
{
throw new TrackingTestRedirect($url, $flashData);
}
require __DIR__ . '/../extension.php';
if (realpath(\Plugi\Extensions::getRoute('/ext--tracking/save')) !== realpath(__DIR__ . '/../routes/save.php')) {
throw new RuntimeException('The Tracking save route should be registered.');
}
if (realpath(\Plugi\Extensions::getBackends()['ext--tracking']['include'] ?? '') !== realpath(__DIR__ . '/../admin/tracking.php')) {
throw new RuntimeException('The Tracking Website Manager backend should be registered.');
}
$_ENV['DATABASE_PREFIX'] = '';
$phpb_db = new TrackingTestDatabase();
ob_start();
require __DIR__ . '/../admin/tracking.php';
$trackingEditor = ob_get_clean();
if (!str_contains($trackingEditor, 'action="/plugi/ext--tracking/save"')) {
throw new RuntimeException('The Tracking editor should post to its registered extension route.');
}
if (($argv[1] ?? null) === 'csrf-rejection') {
$snippet = '<script>window.tracking = "saved";</script>';
(new \Plugi\Repositories\SettingRepository())->updateSettings([
'ext--tracking--head' => $snippet,
]);
$GLOBALS['trackingTestAuthenticated'] = true;
$GLOBALS['trackingTestCsrfValid'] = false;
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = ['snippet' => '<script>window.tracking = "invalid-csrf";</script>'];
register_shutdown_function(static function () use ($phpb_db, $snippet): void {
if (http_response_code() !== 403) {
fwrite(STDERR, "Invalid CSRF should return HTTP 403.\n");
exit(1);
}
$saved = $phpb_db->select('SELECT value FROM settings WHERE setting = ?', ['ext--tracking--head']);
if (($saved[0]['value'] ?? null) !== $snippet) {
fwrite(STDERR, "Invalid CSRF must not change the saved snippet.\n");
exit(1);
}
fwrite(STDOUT, "PASS: authenticated invalid-CSRF requests are rejected without changing the saved snippet.\n");
});
require __DIR__ . '/../routes/save.php';
throw new RuntimeException('Authenticated requests with invalid CSRF should be rejected.');
}
if (\Plugi\Extensions::getHtmlBlocks('head') !== '') {
throw new RuntimeException('An unset tracking snippet should add no head output.');
}
$GLOBALS['trackingTestAuthenticated'] = true;
$GLOBALS['trackingTestCsrfValid'] = true;
$_SERVER['REQUEST_METHOD'] = 'POST';
$snippet = "<script>window.tracking = 'saved';</script>";
$_POST = ['snippet' => $snippet];
try {
require __DIR__ . '/../routes/save.php';
} catch (TrackingTestRedirect $redirect) {
if ($redirect->url !== 'website_manager?tab=ext--tracking' || $redirect->flashData['message-type'] !== 'success') {
throw new RuntimeException('Saving should redirect back to the Tracking editor with success feedback.');
}
}
$saved = $phpb_db->select('SELECT value FROM settings WHERE setting = ?', ['ext--tracking--head']);
if (($saved[0]['value'] ?? null) !== $snippet) {
throw new RuntimeException('The submitted snippet should be persisted unchanged.');
}
$settingsProperty = new ReflectionProperty(\Plugi\Setting::class, 'settings');
$settingsProperty->setValue(null, null);
if (\Plugi\Extensions::getHtmlBlocks('head') !== $snippet) {
throw new RuntimeException('The saved tracking snippet should be emitted unchanged in head output.');
}
$GLOBALS['trackingTestAuthenticated'] = false;
$_POST['snippet'] = '<script>window.tracking = "unauthorized";</script>';
try {
require __DIR__ . '/../routes/save.php';
throw new RuntimeException('Unauthenticated requests should be rejected.');
} catch (TrackingTestAuthenticationRequired) {
}
$saved = $phpb_db->select('SELECT value FROM settings WHERE setting = ?', ['ext--tracking--head']);
if (($saved[0]['value'] ?? null) !== $snippet) {
throw new RuntimeException('Unauthenticated requests must not change the saved snippet.');
}
$process = proc_open([PHP_BINARY, __FILE__, 'csrf-rejection'], [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
], $pipes);
if (!is_resource($process)) {
throw new RuntimeException('Could not start the invalid-CSRF route test.');
}
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
$error = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$status = proc_close($process);
if ($status !== 0 || !str_contains($output, 'PASS: authenticated invalid-CSRF requests are rejected')) {
throw new RuntimeException(sprintf('The invalid-CSRF route test failed (status %d): %s%s', $status, $output, $error));
}
fwrite(STDOUT, "PASS: tracking snippets are saved unchanged; authentication and CSRF are required.\n");
+1 -1
View File
@@ -1,7 +1,7 @@
<?php
require_once __DIR__.'/plugi-core/src/Core/EnvLoader.php';
(new Plugi\Core\EnvLoader())->load();
(new Plugi\Core\EnvLoader(__DIR__ . '/.env'))->load();
if ($_ENV['STAGE'] !== 'production') {
ini_set('display_errors', 1);
+24 -7
View File
@@ -163,9 +163,12 @@ async function buildWebsiteManagerJs() {
);
}
function runTailwindCli({ watch = false } = {}) {
const input = path.resolve(__dirname, 'src/Modules/WebsiteManager/resources/assets/css/style.css');
const output = path.join(DIST_DIR, 'WebsiteManager.css');
function runTailwindCli({
watch = false,
input = path.resolve(__dirname, 'src/Modules/WebsiteManager/resources/assets/css/style.css'),
output = path.join(DIST_DIR, 'WebsiteManager.css'),
label = 'WebsiteManager.css',
} = {}) {
const tailwindBin = path.resolve(__dirname, 'node_modules/.bin/tailwindcss');
const args = ['-i', input, '-o', output];
@@ -194,10 +197,10 @@ function runTailwindCli({ watch = false } = {}) {
if (code === 0) {
const duration = (performance.now() - start).toFixed(1);
const size = (fs.statSync(output).size / 1024).toFixed(1);
console.log(` \x1b[32m✓\x1b[0m CSS dist/WebsiteManager.css (${size} kB, ${duration}ms)`);
console.log(` \x1b[32m✓\x1b[0m CSS dist/${label} (${size} kB, ${duration}ms)`);
resolve();
} else {
console.error(`\x1b[31mError compiling Tailwind CSS:\x1b[0m\n${stderr}`);
console.error(`\x1b[31mError compiling ${label}:\x1b[0m\n${stderr}`);
reject(new Error(`Tailwind CLI exited with code ${code}`));
}
});
@@ -215,6 +218,12 @@ async function buildAll() {
await Promise.all([
buildWebsiteManagerJs(),
runTailwindCli({ watch: false }),
runTailwindCli({
watch: false,
input: path.resolve(__dirname, 'src/Modules/WebsiteManager/resources/assets/css/admin.css'),
output: path.join(DIST_DIR, 'Admin.css'),
label: 'Admin.css',
}),
buildGrapesHead(),
buildGrapesBody(),
buildPageInjectionJs(),
@@ -226,7 +235,15 @@ async function buildAll() {
}
function startWatch() {
const tailwindProcess = runTailwindCli({ watch: true });
const tailwindProcesses = [
runTailwindCli({ watch: true }),
runTailwindCli({
watch: true,
input: path.resolve(__dirname, 'src/Modules/WebsiteManager/resources/assets/css/admin.css'),
output: path.join(DIST_DIR, 'Admin.css'),
label: 'Admin.css',
}),
];
const srcDir = path.resolve(__dirname, 'src');
console.log(`\x1b[36mWatching for changes in ${srcDir}...\x1b[0m\n`);
@@ -284,7 +301,7 @@ function startWatch() {
const cleanup = () => {
console.log('\nStopping watchers...');
if (tailwindProcess) tailwindProcess.kill();
tailwindProcesses.forEach((tailwindProcess) => tailwindProcess?.kill());
watcher.close();
process.exit(0);
};
+5
View File
@@ -16,6 +16,7 @@ return [
'name' => 'varchar(255)',
'layout' => 'varchar(255)',
'data' => 'longtext',
'draft_data' => 'longtext NULL',
'type' => 'varchar(63)',
'status' => 'varchar(63)',
'parent_id' => 'int',
@@ -45,6 +46,8 @@ return [
'updated_at' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
'created_at' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP',
],
'primaryKey' => 'id',
'autoIncrement' => 'id',
'uniqueKeys' => [
'page_id' => ['page_id','locale']
],
@@ -55,6 +58,8 @@ return [
'original_file' => 'varchar(512)',
'mime_type' => 'varchar(50)',
'server_file' => 'varchar(512)',
'alt_text' => "varchar(1000) NOT NULL DEFAULT ''",
'folder' => "varchar(255) NOT NULL DEFAULT ''",
],
'uniqueKeys' => [
'public_id' => ['public_id'],
+2
View File
File diff suppressed because one or more lines are too long
+2 -2
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -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":"AAMA,eACE,uBACA,SACA,gBAGF,EACE,mCACA,gCACA,2BAGF,kCACE,cAGF,gBACE,eAGF,YACE,gBAGF,OACE,qBACA,YACA,WACA,gBAEA,qBACE,mBAIJ,cACE,kBACA,YACA,WACA,sBACA,cACA,sCAEA,qBACE,kBACA,UAGF,sBACE,kBACA,QACA,SACA,gCACA,YACA,aAEA,4BACE,eACA,eACA,gBACA,kBACA,cAGJ,sBACE,uBACA,wBACA,yBACA,6BACA,kBACA,oCAEF,kBACE,+BAIJ,sBACE,gBAGF,eACE,YACA,MACA,yBAEF,aACE,uBAGF,cACE,UAEA,8BACE,uBAGJ,mDAGE,aAEF,eACE,UAEF,YACE,yBACA,mBACA,cAEF,eACE,cAEF,gBACE,cAEF,wBACE,cAEF,iBACE,WACA,wBACA,qBACA,gBAEF,oBACE,UACA,WAEF,0BACE,8BAEF,0BACE,oCACA,kBAEA,gCACE,oCAMJ,cACE,SAEA,0BACE,aACA,eACA,4BACA,wBACA,qBACA,gBACA,mBACA,cACA,gCACA,eAEA,wCACE,aACA,yBACA,gCACA,iCACA,wBACA,qBACA,gBACA,WACA,gCAIN,gBACE,QAEF,sCAEE,OACA,wBACA,qBACA,gBACA,MA1Lc,MA2Ld,iBACA,gBACA,cACA,eACA,eACA,gBAEF,wBACE,iBACA,mBACA,yBACA,gBAEA,0CACE,gBAGF,4BACE,YACA,gBAGF,gCACE,mBACA,YAGJ,iCAEE,KAxNc,MA2Nd,4BACE,2BAEF,6BACE,4BAEF,8BACE,4BAOJ,cACE,yBAGA,6DAEE,WAGJ,WACE,yBACA,gBACA,YAEA,uDAGE,YAGF,0BACE,6BAOJ,gBACE,kBACA,gBACA,MAxQc,MAyQd,eACA,mBACA,YACA,YACA,aACA,mBAEA,mCACE,iBAEA,0CACE,mBACA,cACA,yBACA,kBACA,gBACA,eACA,aACA,eAEA,gDACE,qBAKR,gBACE,kBACA,OACA,MACA,YACA,cACA,mBACA,gBACA,YACA,eACA,YACA,WACA,aACA,mBACA,uBAMF,cACE,eACA,mBACA,qBACA,gBACA,YACA,iBAEA,0BACE,kBACA,SACA,SACA,eACA,cAGF,oBACE,mBACA,4BACA,gBACA,YAEA,iCACE,cAKN,WACE,YACA,gBACA,mBACA,WACA,uBAEA,cACE,YAGF,iBACE,yBAGF,wBACE,YACA,gBACA,kBACA,WAEA,4BACE,WAIN,cACE,mBACA,YAEF,sBACE,mBACA,oBAEF,iBACE,gBACA,YACA,aAEA,mBACE,iBACA,gBAGJ,oBACE,mBAEF,6BACE,8BACA,mBAEF,eACE,8BAMF,4BACE,8BAEF,yCACE,oCAEF,wCACE,wDAEF,6HAKE,8BACA,2CACA,iBACA,eACA,mBAEF,sHAGE,8BAEF,gBACE,gBACA,oBAEF,iBACE,aAEF,eACE,iBAMF,2BACE,uCAMF,eACE,cAEF,gBACE,mBAEF,oDAEE,WAEF,oBACE,uBACA,sBAEF,kBACE,mBACA,eACA,mBAEF,yDAEE,kBAEF,+BACE,WAEF,8BACE,iBACA,oBAEF,kCACE,gBAEF,iCACE,mBAEF,eACE,oBAEF,gCACE,gBACA,UAEA,0DACE,kBAEA,gFACE,kBACA,QACA,MACA,gBACA,yBACA,qBACA,cACA,gBAGF,8DACE,eACA,iBAQN,wBACE,kBACA,OACA,SACA,OAjgB8B,KAkgB9B,MAngBc,MAogBd,SACA,UACA,mBACA,gBACA,aAEA,yDAEE,OACA,oBACA,mBACA,uBACA,YACA,8BACA,gBACA,cACA,eACA,cACA,qBACA,YACA,8BAEA,qEACE,mBACA,WAEF,iFACE,iBAIJ,uCACE,mBACA,sBAEA,iDACE,aAIJ,uCACE,mBAEF,yCACE,mBChjBJ,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,iBHigBJ,qBACE,cACA,eAEA,gCACE,yBACA,yBACA,WACA,iBACA,kBACA,aACA,eAEA,sCACE,qBAIJ,sCACE,gBACA,wRACA,4BACA,sCACA,qBACA,mBAGF,0BACE,iBACA,kBACA,eACA,eACA,YACA,6CIxlBF,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,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"}
+1 -1
View File
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 2.8 MiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
+4505 -3647
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 1.4 MiB

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
+8316 -6200
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 1.0 MiB

After

Width:  |  Height:  |  Size: 2.6 MiB

Binary file not shown.
Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More