Compare commits

..
13 Commits
Author SHA1 Message Date
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 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 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
64 changed files with 2776 additions and 566 deletions
+2 -2
View File
@@ -1,10 +1,10 @@
FROM php:8.2-apache-bullseye
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.2-mysql; \
php8.4-mysql; \
apt-get clean; \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*
+22
View File
@@ -149,6 +149,28 @@ return [
'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' => '',
'port' => 587,
'encryption' => 'tls',
'username' => '',
'password' => '',
'from_address' => '',
'from_name' => '',
'timeout' => 10,
],
/*
|--------------------------------------------------------------------------
| Class replacements
-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,222 @@
<?php
namespace Plugi\Extensions\Form;
use Plugi\Extensions\Form\Finishers\DefaultFinisher;
use Plugi\Extensions\Form\Finishers\FinishersRepository;
class SubmissionHandler
{
private $formsRepository;
private $finishersRepository;
public function __construct($formsRepository = null, $finishersRepository = null)
{
$this->formsRepository = $formsRepository ?? new DefinitionsRepository();
$this->finishersRepository = $finishersRepository ?? new FinishersRepository();
}
public function handle($formId, string $rawData): array
{
$formId = filter_var($formId, FILTER_VALIDATE_INT);
if ($formId === false || $formId < 1) {
return $this->failure(400, ['A valid form id is required.']);
}
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'];
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.'];
}
}
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);
}
}
@@ -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' => "[]",
];
@@ -22,8 +25,8 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
<i class="ph-duotone ph-arrow-left text-xl"></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>
<h2 class="text-xl font-bold"><?= $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>
@@ -31,19 +34,19 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
<script>
const fields = <?= $form["fields"] ?>;
const finishers = <?= $form["finishers"] ?>;
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="{
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 +55,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;
@@ -84,14 +108,14 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
<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>
<h3 class="card-title text-lg">Basics</h3>
</div>
<div class="form-control">
<label class="label">
<span class="label-text font-medium">Formularname</span>
<span class="label-text font-medium">Form name</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 type="text" name="name" value="<?= $form['name'] ?>" placeholder="e.g. Contact form" class="input input-bordered w-full" required />
<span class="label-text-alt text-base-content/60">A unique name for your form.</span>
</div>
</div>
</div>
@@ -100,16 +124,16 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
<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>
<h3 class="card-title text-lg">Form fields</h3>
</div>
<p class="text-sm text-base-content/60 mb-4">Definiere die Felder, die Nutzer ausfüllen können.</p>
<p class="text-sm text-base-content/60 mb-4">Define the fields users can fill out.</p>
<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>
<p class="text-sm text-base-content/50 mt-2">No fields added yet</p>
<a href="javascript:void(0)" @click="addField()" class="btn btn-sm btn-primary mt-2">Add your first field</a>
</div>
<div x-show="fields.length > 0" class="space-y-3">
@@ -129,7 +153,7 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
>
<div class="flex items-center gap-2 mb-2">
<!-- 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">
<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">
<i class="ph-duotone ph-dots-six-vertical text-lg"></i>
</button>
<span class="text-xs font-mono text-base-content/40 w-6">#[<span x-text="index + 1"></span>]</span>
@@ -137,18 +161,18 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
<input
type="text"
x-model="field.name"
placeholder="Feldname"
placeholder="Field 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">
<input
type="text"
x-model="field.label"
placeholder="Beschriftung"
placeholder="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>
@@ -165,16 +189,16 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
<select x-model="field.type" class="select select-bordered select-sm flex-1">
<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>
<span class="label-text text-sm">Required</span>
<input type="checkbox" x-model="field.required" class="checkbox checkbox-sm checkbox-primary" />
</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">
<i class="ph-duotone ph-trash"></i>
</button>
</div>
@@ -183,16 +207,16 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
<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
Add
</a>
</div>
<div class="space-y-1">
<template x-for="(option, optIndex) in field.options">
<div class="flex items-center gap-2">
<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 flex-1" />
<input type="text" x-model="option.value" placeholder="Value" 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="Remove">
<i class="ph-duotone ph-x"></i>
</button>
</div>
@@ -206,7 +230,7 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
<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
Add field
</a>
</div>
</div>
@@ -216,37 +240,70 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
<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>
<h3 class="card-title text-lg">Actions</h3>
</div>
<p class="text-sm text-base-content/60 mb-4">Was soll passieren, wenn ein Formular abgeschickt wird?</p>
<p class="text-sm text-base-content/60 mb-4">What should happen when a form is submitted?</p>
<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>
<p class="text-sm text-base-content/50 mt-2">No actions added yet</p>
<a href="javascript:void(0)" @click="addFinisher()" class="btn btn-sm btn-primary mt-2">Add your first action</a>
</div>
<div x-show="finishers.length > 0" class="space-y-2">
<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="p-3 border border-base-300 rounded-lg bg-base-200/50 space-y-3">
<div class="flex items-center gap-3">
<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 flex-1">
<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">
<i class="ph-duotone ph-trash"></i>
</button>
</div>
<div x-show="getFinisherSettings(finisher.type).length > 0" class="space-y-3 pl-8">
<template x-for="setting in getFinisherSettings(finisher.type)" :key="setting.name">
<div class="form-control">
<label class="label"><span class="label-text" x-text="setting.label"></span></label>
<template x-if="setting.type === 'emailField'">
<select 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 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 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 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="label-text-alt text-warning">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">
<a href="javascript:void(0)" @click="addFinisher()" class="btn btn-outline btn-sm btn-primary">
<i class="ph-duotone ph-plus"></i>
Aktion hinzufügen
Add action
</a>
</div>
</div>
@@ -254,11 +311,11 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
<div class="flex justify-end gap-2">
<a href="?tab=ext--form" class="btn btn-ghost btn-sm">
Abbrechen
Cancel
</a>
<button type="submit" class="btn btn-primary btn-sm">
<i class="ph-duotone ph-floppy-disk"></i>
Speichern
Save
</button>
</div>
</form>
@@ -2,9 +2,9 @@
<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>
<h3 class="card-title text-lg">Settings</h3>
</div>
<p class="text-sm text-base-content/60 mb-4">Konfiguriere die globalen Einstellungen für das Formulare-Extension.</p>
<p class="text-sm text-base-content/60 mb-4">Configure the global settings for the Form extension.</p>
<div class="space-y-4">
<?php
foreach (\Plugi\Extensions::getSettings('form') as $setting) {
@@ -20,7 +20,7 @@ $entries = $entriesRepository->findWhere('formId', $id);
</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>
<p class="text-sm text-base-content/60"><?= count($entries) ?> submission<?= count($entries) !== 1 ? 's' : '' ?> for this form</p>
</div>
</div>
</div>
@@ -29,8 +29,8 @@ $entries = $entriesRepository->findWhere('formId', $id);
<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>
<h3 class="card-title text-lg mt-4">No submissions yet</h3>
<p class="text-base-content/60 mt-1">Submissions will appear here when someone fills out the form.</p>
</div>
</div>
<?php else: ?>
@@ -41,7 +41,7 @@ $entries = $entriesRepository->findWhere('formId', $id);
<thead>
<tr class="bg-base-200/50">
<th class="w-16">ID</th>
<th class="w-40">Erstellt</th>
<th class="w-40">Created</th>
<?php foreach ($fields as $field): ?>
<th><?= phpb_e($field['label']) ?></th>
<?php endforeach; ?>
@@ -8,12 +8,12 @@ $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>
<h2 class="text-xl font-bold">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 btn-sm">
<i class="ph-duotone ph-plus"></i>
Neues Formular
New form
</a>
</div>
@@ -21,11 +21,11 @@ $forms = $formsRepository->getAll();
<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>
<h3 class="card-title text-lg mt-4">No forms yet</h3>
<p class="text-base-content/60 mt-1">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-4">
<i class="ph-duotone ph-plus"></i>
Erstes Formular erstellen
Create your first form
</a>
</div>
</div>
@@ -50,7 +50,7 @@ $forms = $formsRepository->getAll();
</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">
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'listEntries', 'id' => $form['id']]) ?>" class="btn btn-ghost btn-sm btn-circle" title="View entries">
<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') ?>">
+2 -2
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,
@@ -18,7 +18,7 @@ return [
"settings" => [
"formId" => [
"type" => "select",
"label" => "Formular",
"label" => "Form",
"value" => 0,
"options" => $formOptions,
],
@@ -8,16 +8,26 @@ if ($id > 0):
?>
<div class="max-w-2xl mx-auto">
<div x-data="{data: {fields : {}}, status: 'idle', submitted: false}">
<div x-data="{data: {fields : {}}, status: 'idle', submitted: false, errorMessage: ''}">
<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';
errorMessage = '';
try {
const response = await fetch('/ext--form/submit?id=<?= $id ?>', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
});
const result = await response.json();
if (!response.ok || !result.success) {
throw new Error((result.errors || []).join(' ') || 'Your submission could not be completed. Please try again.');
}
submitted = true;
})
} catch (error) {
errorMessage = error.message || 'Your submission could not be completed. Please try again.';
} finally {
status = 'idle';
}
">
<?php foreach ($fields as $field):
@@ -43,7 +53,7 @@ if ($id > 0):
<select x-model="data.fields.<?= $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[
"value"
@@ -92,22 +102,23 @@ if ($id > 0):
<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
Submit
</span>
<span x-show="status === 'busy'">
<span class="loading loading-spinner loading-sm"></span>
Wird gesendet...
Sending...
</span>
</button>
</div>
</form>
<div x-show="errorMessage" x-text="errorMessage" class="alert alert-error mt-4" role="alert"></div>
<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 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>
<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>
@@ -119,7 +130,7 @@ else:
<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>
<p class="text-sm text-base-content/50 mt-2">Select a form in the settings</p>
</div>
</div>
</div>
+5 -17
View File
@@ -1,22 +1,10 @@
<?php
$formsRepository = new \Plugi\Extensions\Form\DefinitionsRepository();
$handler = new \Plugi\Extensions\Form\SubmissionHandler();
$result = $handler->handle($_GET['id'] ?? null, file_get_contents('php://input') ?: '');
$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,481 @@
<?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';
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]];
}
}
}
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 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): SubmissionHandler
{
return new SubmissionHandler(new TestDefinitionsRepository($form), new TestFinishersRepository());
}
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'] = [];
$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');
if (strpos($view, '!response.ok || !result.success') === false || strpos($view, 'x-show="errorMessage"') === false) {
throw new \RuntimeException('The frontend must check the response and expose a retryable error state.');
}
if (preg_match('/if \(!response\.ok \|\| !result\.success\).*?submitted = true;/s', $view) !== 1) {
throw new \RuntimeException('The frontend may only show its success state after a successful response.');
}
$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";
}
-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 -1
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2
View File
@@ -30,6 +30,7 @@ return [
'theme' => 'Design',
'visible-in-page-overview' => 'In Seitenübersicht anzeigen',
'page-created' => 'Seite erstellt',
'page-create-failed' => 'Die Seite konnte nicht erstellt werden. Prüfen Sie Pflichtfelder, übersetzte Werte, Routen und die Datenbankverbindung und versuchen Sie es erneut.',
'page-updated' => 'Seite aktualisiert',
'page-deleted' => 'Seite gelöscht',
'page-type' => 'Seitentyp',
@@ -149,5 +150,6 @@ return [
'es' => 'Spanisch',
'it' => 'Italienisch',
'fr' => 'Französisch',
'sv' => 'Schwedisch',
],
];
+2
View File
@@ -30,6 +30,7 @@ return [
'theme' => 'Theme',
'visible-in-page-overview' => 'visible in page overview',
'page-created' => 'Page successfully created',
'page-create-failed' => 'Page could not be created. Check required fields, localized values, routes, and the database connection, then try again.',
'page-updated' => 'Page successfully updated',
'page-deleted' => 'Page removed',
'page-type' => 'Page type',
@@ -149,5 +150,6 @@ return [
'it' => 'Italian',
'fr' => 'French',
'de' => 'German',
'sv' => 'Swedish',
],
];
-148
View File
@@ -1,148 +0,0 @@
<?php
return [
'auth' => [
'title' => 'Plugi Page Builder',
'username' => 'Usuario',
'password' => 'Contraseña',
'login-button' => 'Entrar',
'invalid-credentials' => 'Usuario o contraseña Inválidos',
],
'website-manager' => [
'title' => 'Plugi Page Builder',
'logout' => 'Salir',
'pages' => 'Páginas',
'menus' => 'Menús',
'name' => 'Nombre',
'page-title' => 'Título de la página del menú',
'page-meta-title' => 'Metatítulo de la página',
'page-meta-description' => 'Meta descripción de la página',
'route' => 'URL',
'layout' => 'Diseño',
'actions' => 'Acciones',
'view' => 'Ver',
'edit' => 'Editar',
'remove' => 'Borrar',
'add-new-page' => 'Nueva página',
'edit-page' => 'Editar página',
'back' => 'Volver',
'save-changes' => 'Guardar cambios',
'theme' => 'Tema',
'visible-in-page-overview' => 'visible en vista de página',
'page-created' => 'Página creada correctamente',
'page-updated' => 'Página acyualizada correctamente',
'page-deleted' => 'Página eliminada',
'files' => 'Files',
'settings' => 'Ajustes',
'info' => 'Info',
'required' => 'Required',
'website-languages' => 'Idiomas del sitio',
'languages-selector-placeholder' => 'Selecciona uno o más idiomas',
'save-settings' => 'Guardar ajustes',
'settings-updated' => 'Ajustes actualizados correctamente',
'admin-language' => 'Admin Language',
'selected-theme' => 'Selected theme',
'save-menus' => 'Save menus',
'create-menu' => 'Create menu',
'delete-menu' => 'Delete menu:',
'menus-updated' => 'Menus updated',
'db-updated' => 'Database updated',
'pagebuilder-block-images' => 'Listado de bloques',
'render-thumbs' => 'Mostrar Miniaturas',
'check-database' => 'Check database'
],
'pagebuilder' => [
'filter-placeholder' => 'Filtrar',
'loading-text' => 'Cargando Webuilder..',
'style-no-element-selected' => 'Selecciona un elemento para modificar su estilo.',
'trait-no-element-selected' => 'Selecciona un elemento para modificar sus atributos.',
'trait-settings' => 'Ajustes',
'default-category' => 'General',
'view-blocks' => 'Bloques',
'view-settings' => 'Ajustes',
'view-style-manager' => 'Gestor de Estilos',
'save-page' => 'Guardar',
'view-page' => 'Ver',
'go-back' => 'Volver',
'page' => 'Página',
'page-content' => 'Contenidos de la Página',
'toastr-changes-saved' => 'Cambios guardados',
'toastr-saving-failed' => 'Error al guardar los cambios',
'toastr-component-update-failed' => 'Error al cargar componente',
'toastr-switching-language-failed' => 'Error al cambiar de idioma',
'yes' => 'Si',
'no' => 'No',
'trait-manager' => [
'link' => [
'text' => 'Texto',
'target' => '¿Abrir en otra pestaña?',
'tooltip' => 'Información'
],
'no-settings' => 'Este bloque no tiene ajustes.'
],
'selector-manager' => [
'label' => 'clases CSS',
'states-label' => 'Diseño para',
'selected-label' => 'Seleccinado',
'state-hover' => 'Elemento hover',
'state-active' => 'Elemento click',
'state-nth' => 'Elemento par/impar',
],
'style-manager' => [
'sectors' => [
'position' => 'Posición',
'background' => 'Fondo',
'advanced' => 'Avanzado',
],
'properties' => [
'position' => [
'width' => 'Ancho',
'min-width' => 'Mínimo',
'max-width' => 'Máximo',
'height' => 'Alto',
'min-height' => 'Mínimo',
'max-height' => 'Máximo',
'padding' => [
'name' => 'Relleno',
'properties' => [
'padding-top' => 'Padding arriba',
'padding-right' => 'Padding derecho',
'padding-bottom' => 'Padding abajo',
'padding-left' => 'Padding izquierdo'
]
],
'margin' => [
'name' => 'Margen',
'properties' => [
'margin-top' => 'Margen arriba',
'margin-right' => 'Margen derecho',
'margin-bottom' => 'Margen abajo',
'margin-left' => 'Margen izquierdo'
]
],
'text-align' => [
'name' => 'Alineación Texto'
]
],
'background' => [
'background-color' => 'Color de Fondo',
'background' => 'Fondo',
]
]
],
'asset-manager' => [
'modal-title' => 'Seleciona Imágen',
'drop-files' => 'Arrastra aquí los archivos o click para subirlos',
'add-image' => 'Añadir Imágenge',
],
],
'languages' => [
'es' => 'Español',
'en' => 'Inglés',
'nl' => 'Holandés',
'it' => 'Italiano',
'fr' => 'Francés',
'de' => 'Alemán',
],
];
-148
View File
@@ -1,148 +0,0 @@
<?php
return [
'auth' => [
'title' => 'Plugi Page Builder',
'username' => 'Gebruikersnaam',
'password' => 'Wachtwoord',
'login-button' => 'Inloggen',
'invalid-credentials' => 'Ingevulde logingegevens zijn onjuist',
],
'website-manager' => [
'title' => 'Plugi Page Builder',
'logout' => 'Uitloggen',
'pages' => 'Pagina\'s',
'menus' => 'Menus',
'name' => 'Naam',
'page-title' => 'Page menu titel',
'page-meta-title' => 'Pagina (meta) titel',
'page-meta-description' => 'Pagina meta omschrijving',
'route' => 'URL',
'layout' => 'Paginaopbouw',
'actions' => 'Acties',
'view' => 'Bekijk',
'edit' => 'Wijzig',
'remove' => 'Verwijder',
'add-new-page' => 'Pagina toevoegen',
'edit-page' => 'Pagina wijzigen',
'back' => 'Terug',
'save-changes' => 'Wijzigingen opslaan',
'theme' => 'Thema',
'visible-in-page-overview' => 'zichtbaar in pagina overzicht',
'page-created' => 'Nieuwe pagina aangemaakt',
'page-updated' => 'Pagina wijziging opgeslagen',
'page-deleted' => 'Pagina verwijderd',
'files' => 'Files',
'settings' => 'Instellingen',
'info' => 'Info',
'required' => 'Required',
'website-languages' => 'Website talen',
'languages-selector-placeholder' => 'Selecteer één of meerdere talen',
'admin-language' => 'Admin Language',
'selected-theme' => 'Selected theme',
'save-settings' => 'Instellingen opslaan',
'settings-updated' => 'Instellingen opgeslagen',
'save-menus' => 'Save menus',
'create-menu' => 'Create menu',
'delete-menu' => 'Delete menu:',
'menus-updated' => 'Menus updated',
'db-updated' => 'Database updated',
'pagebuilder-block-images' => 'Pagebuilder blok afbeeldingen',
'render-thumbs' => 'Blok afbeeldingen genereren',
'check-database' => 'Check database'
],
'pagebuilder' => [
'filter-placeholder' => 'Filter',
'loading-text' => 'Bewerkmodus laden..',
'style-no-element-selected' => 'Selecteer een element om de opmaak aan te passen.',
'trait-no-element-selected' => 'Selecteer een element om de eigenschappen aan te passen.',
'trait-settings' => 'Instellingen',
'default-category' => 'Algemeen',
'view-blocks' => 'Blokken',
'view-settings' => 'Instellingen',
'view-style-manager' => 'Opmaak',
'save-page' => 'Opslaan',
'view-page' => 'Bekijk',
'go-back' => 'Terug',
'page' => 'Pagina',
'page-content' => 'Pagina inhoud',
'toastr-changes-saved' => 'Wijzigingen opgeslagen',
'toastr-saving-failed' => 'Fout opgetreden bij opslaan van wijzigingen',
'toastr-component-update-failed' => 'Fout opgetreden bij het vernieuwen van het blok',
'toastr-switching-language-failed' => 'Fout opgetreden bij het wisselen van taal',
'yes' => 'Ja',
'no' => 'Nee',
'trait-manager' => [
'link' => [
'text' => 'Tekst',
'target' => 'Open in nieuw tabblad?',
'tooltip' => 'knopinfo'
],
'no-settings' => 'Dit blok heeft geen instellingen.'
],
'selector-manager' => [
'label' => 'CSS klasses',
'states-label' => 'Opmaak voor',
'selected-label' => 'Geselecteerd',
'state-hover' => 'Muis over element',
'state-active' => 'Muisklik op element',
'state-nth' => 'Even/oneven elementen',
],
'style-manager' => [
'sectors' => [
'position' => 'Positie',
'background' => 'Achtergrond',
'advanced' => 'Geavanceerd',
],
'properties' => [
'position' => [
'width' => 'Breedte',
'min-width' => 'Minimale breedte',
'max-width' => 'Maximale breedte',
'height' => 'Hoogte',
'min-height' => 'Minimale hoogte',
'max-height' => 'Maximale hoogte',
'padding' => [
'name' => 'Ruimte binnenkant (padding)',
'properties' => [
'padding-top' => 'Binnenrand boven',
'padding-right' => 'Binnenrand rechts',
'padding-bottom' => 'Binnenrand onder',
'padding-left' => 'Binnenrand links'
]
],
'margin' => [
'name' => 'Ruimte buitenkant (marge)',
'properties' => [
'margin-top' => 'Buitenrand boven',
'margin-right' => 'Buitenrand rechts',
'margin-bottom' => 'Buitenrand onder',
'margin-left' => 'Buitenrand links'
]
],
'text-align' => [
'name' => 'Uitlijning'
]
],
'background' => [
'background-color' => 'Achtergrond kleur',
'background' => 'Achtergrond',
]
]
],
'asset-manager' => [
'modal-title' => 'Selecteer afbeelding',
'drop-files' => 'Klik hier of sleep bestanden hierheen',
'add-image' => 'Afbeelding toevoegen',
],
],
'languages' => [
'nl' => 'Nederlands',
'en' => 'Engels',
'es' => 'Spaans',
'it' => 'Italiaans',
'fr' => 'Frans',
'de' => 'Duits',
],
];
+154
View File
@@ -0,0 +1,154 @@
<?php
return [
'auth' => [
'title' => 'Plugi Page Builder',
'username' => 'Användarnamn',
'password' => 'Lösenord',
'login-button' => 'Logga in',
'invalid-credentials' => 'Ogiltigt användarnamn eller lösenord',
],
'website-manager' => [
'title' => 'Plugi Page Builder',
'logout' => 'Logga ut',
'pages' => 'Sidor',
'menus' => 'Menyer',
'name' => 'Namn',
'page-title' => 'Sidans menytitel',
'page-meta-title' => 'Sidans metatitel',
'page-meta-description' => 'Sidans metabeskrivning',
'route' => 'URL',
'layout' => 'Layout',
'actions' => 'Åtgärder',
'view' => 'Visa',
'edit' => 'Redigera',
'remove' => 'Ta bort',
'add-new-page' => 'Lägg till ny sida',
'edit-page' => 'Redigera sida',
'back' => 'Tillbaka',
'save-changes' => 'Spara ändringar',
'theme' => 'Tema',
'visible-in-page-overview' => 'synlig i sidöversikten',
'page-created' => 'Sidan har skapats',
'page-updated' => 'Sidan har uppdaterats',
'page-deleted' => 'Sidan har tagits bort',
'page-type' => 'Sidtyp',
'page-types' => [
'static' => 'Statisk sida',
'redirect' => 'Omdirigering',
],
'target-redirect' => 'Mål för omdirigering',
'files' => 'Filer',
'settings' => 'Inställningar',
'info' => 'Info',
'required' => 'Obligatoriskt',
'website-languages' => 'Webbplatsspråk',
'languages-selector-placeholder' => 'Välj ett eller flera språk',
'admin-language' => 'Administratörsspråk',
'selected-theme' => 'Valt tema',
'save-settings' => 'Spara inställningar',
'settings-updated' => 'Inställningarna har uppdaterats',
'save-menus' => 'Spara menyer',
'create-menu' => 'Skapa meny',
'delete-menu' => 'Ta bort meny:',
'menus-updated' => 'Menyerna har uppdaterats',
'db-updated' => 'Databasen har uppdaterats',
'pagebuilder-block-images' => 'Sidbyggarens blockminiatyrer',
'render-thumbs' => 'Skapa miniatyrbilder',
'check-database' => 'Kontrollera databasen',
],
'pagebuilder' => [
'filter-placeholder' => 'Filtrera',
'loading-text' => 'Laddar sidbyggaren...',
'style-no-element-selected' => 'Välj ett element för att ändra stilen.',
'trait-no-element-selected' => 'Välj ett element för att ändra dess attribut.',
'trait-settings' => 'Inställningar',
'default-category' => 'Allmänt',
'view-blocks' => 'Block',
'view-settings' => 'Inställningar',
'view-style-manager' => 'Stilhanterare',
'save-page' => 'Spara',
'view-page' => 'Visa',
'go-back' => 'Tillbaka',
'page' => 'Sida',
'page-content' => 'Sidinnehåll',
'toastr-changes-saved' => 'Ändringarna har sparats',
'toastr-saving-failed' => 'Det gick inte att spara ändringarna',
'toastr-component-update-failed' => 'Det gick inte att läsa in komponenten igen',
'toastr-switching-language-failed' => 'Det gick inte att byta språk',
'yes' => 'Ja',
'no' => 'Nej',
'trait-manager' => [
'link' => [
'text' => 'Text',
'target' => 'Öppna i en ny flik?',
'tooltip' => 'Verktygstips',
],
'no-settings' => 'Det här blocket har inga inställningar.',
],
'selector-manager' => [
'label' => 'CSS-klasser',
'states-label' => 'Layout för',
'selected-label' => 'Markerad',
'state-hover' => 'När elementet hovras',
'state-active' => 'När elementet klickas',
'state-nth' => 'Jämnt/udda element',
],
'style-manager' => [
'sectors' => [
'position' => 'Position',
'background' => 'Bakgrund',
'advanced' => 'Avancerat',
],
'properties' => [
'position' => [
'width' => 'Bredd',
'min-width' => 'Minsta bredd',
'max-width' => 'Största bredd',
'height' => 'Höjd',
'min-height' => 'Minsta höjd',
'max-height' => 'Största höjd',
'padding' => [
'name' => 'Utfyllnad',
'properties' => [
'padding-top' => 'Utfyllnad upptill',
'padding-right' => 'Utfyllnad till höger',
'padding-bottom' => 'Utfyllnad nedtill',
'padding-left' => 'Utfyllnad till vänster',
],
],
'margin' => [
'name' => 'Marginal',
'properties' => [
'margin-top' => 'Marginal upptill',
'margin-right' => 'Marginal till höger',
'margin-bottom' => 'Marginal nedtill',
'margin-left' => 'Marginal till vänster',
],
],
'text-align' => [
'name' => 'Textjustering',
],
],
'background' => [
'background-color' => 'Bakgrundsfärg',
'background' => 'Bakgrund',
],
],
],
'asset-manager' => [
'modal-title' => 'Välj bild',
'drop-files' => 'Släpp filer här eller klicka för att ladda upp',
'add-image' => 'Lägg till bild',
],
],
'languages' => [
'en' => 'Engelska',
'nl' => 'Nederländska',
'es' => 'Spanska',
'it' => 'Italienska',
'fr' => 'Franska',
'de' => 'Tyska',
'sv' => 'Svenska',
],
];
@@ -11,7 +11,7 @@ interface PageBuilderContract
* @param $action
* @param PageContract|null $page
*/
public function handleRequest($route, $action, PageContract $page = null);
public function handleRequest($route, $action, ?PageContract $page = null);
/**
* Render the given page inside the PageBuilder.
@@ -27,7 +27,7 @@ interface PageBuilderContract
* @param null $language
* @return string
*/
public function renderPage(PageContract $page, $language = null): string;
public function renderPage(PageContract $page, ?string $language = null): string;
/**
* Update the given page with the given data (an array of html blocks)
@@ -44,7 +44,7 @@ interface PageBuilderContract
* @param string|null $css
* @return string
*/
public function customStyle(string $css = null);
public function customStyle(?string $css = null);
/**
* Get or set custom scripts for customizing behaviour of the page builder.
@@ -53,7 +53,7 @@ interface PageBuilderContract
* @param string|null $scripts
* @return string
*/
public function customScripts(string $location, string $scripts = null);
public function customScripts(string $location, ?string $scripts = null);
/**
* Set a theme for the page builder.
+2 -2
View File
@@ -61,7 +61,7 @@ interface PageContract
* @param string|null $locale
* @return mixed|string|null
*/
public function getTranslation(string $setting, $locale = null);
public function getTranslation(string $setting, ?string $locale = null);
/**
* Return the translated settings of this page.
@@ -76,7 +76,7 @@ interface PageContract
* @param string|null $locale
* @return mixed
*/
public function getRoute($locale = null);
public function getRoute(?string $locale = null);
/**
* Get the value of the given property of this Page.
@@ -22,7 +22,7 @@ interface WebsiteManagerContract
*
* @param PageContract $page
*/
public function renderPageSettings(PageContract $page = null);
public function renderPageSettings(?PageContract $page = null);
/**
* Render the website manager menu settings (add/edit menu form).
+97
View File
@@ -0,0 +1,97 @@
<?php
namespace Plugi\Core;
class Csrf
{
/**
* Session key for storing CSRF tokens.
*/
private const SESSION_KEY = 'phpb_csrf_tokens';
/**
* Generate a new CSRF token and store it in the session.
*
* @return string The generated token
*/
public static function generateToken(): string
{
if (session_status() === PHP_SESSION_NONE) {
throw new \RuntimeException('Session must be started before generating CSRF tokens.');
}
if (!isset($_SESSION[self::SESSION_KEY])) {
$_SESSION[self::SESSION_KEY] = [];
}
$token = bin2hex(random_bytes(32));
$_SESSION[self::SESSION_KEY][$token] = time();
self::cleanupExpiredTokens();
return $token;
}
/**
* Validate a CSRF token against the session-stored tokens.
*
* @param string $token The token to validate
* @return bool True if the token is valid, false otherwise
*/
public static function validateToken(string $token): bool
{
if (empty($token) || !isset($_SESSION[self::SESSION_KEY])) {
return false;
}
// Use hash_equals for timing-safe comparison
foreach ($_SESSION[self::SESSION_KEY] as $storedToken => $timestamp) {
if (hash_equals($storedToken, $token)) {
// Do not remove the token — it is reusable for AJAX requests.
// Tokens expire after 1 hour via cleanupExpiredTokens().
return true;
}
}
return false;
}
/**
* Get the current CSRF token for use in forms.
* Generates a new one if none exists.
*
* @return string The CSRF token
*/
public static function getToken(): string
{
if (session_status() === PHP_SESSION_NONE) {
return '';
}
if (!isset($_SESSION[self::SESSION_KEY]) || empty($_SESSION[self::SESSION_KEY])) {
return self::generateToken();
}
// Return the most recent token
$keys = array_keys($_SESSION[self::SESSION_KEY]);
return end($keys);
}
/**
* Remove expired tokens from the session.
* Tokens expire after 1 hour by default.
*/
private static function cleanupExpiredTokens(): void
{
if (!isset($_SESSION[self::SESSION_KEY])) {
return;
}
$now = time();
$maxAge = 3600; // 1 hour
foreach ($_SESSION[self::SESSION_KEY] as $token => $timestamp) {
if ($now - $timestamp > $maxAge) {
unset($_SESSION[self::SESSION_KEY][$token]);
}
}
}
}
+59 -12
View File
@@ -22,19 +22,28 @@ class DB
*/
protected PDO $pdo;
/**
* @var string $databaseName
*/
protected string $databaseName;
/**
* DB constructor.
*
*/
public function __construct()
{
// Validate database charset against a whitelist to prevent SQL injection
$allowedCharsets = ['utf8mb4', 'utf8', 'latin1', 'ascii', 'utf8mb3'];
$charset = in_array($_ENV['DATABASE_CHARSET'], $allowedCharsets, true) ? $_ENV['DATABASE_CHARSET'] : 'utf8mb4';
$this->pdo = new PDO(
$_ENV['DATABASE_DRIVER'] . ':host=' . $_ENV['DATABASE_HOST'] . ';dbname=' . $_ENV['DATABASE_DATABASE'] . ";options='--client_encoding=" . $_ENV['DATABASE_CHARSET'] . "'",
$_ENV['DATABASE_DRIVER'] . ':host=' . $_ENV['DATABASE_HOST'] . ';dbname=' . $_ENV['DATABASE_DATABASE'] . ";options='--client_encoding=" . $charset . "'",
$_ENV['DATABASE_USERNAME'],
$_ENV['DATABASE_PASSWORD'],
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
$this->pdo->exec("set names " . $_ENV['DATABASE_CHARSET']);
$this->pdo->exec("set names " . $charset);
$this->databaseName = $_ENV['DATABASE_DATABASE'];
}
/**
@@ -57,14 +66,19 @@ class DB
public function all(string $table, array|string $columns = '*'): array
{
try {
// Sanitize table name to prevent SQL injection
$sanitizedTable = phpb_remove_non_alpha_numeric($table);
if (empty($sanitizedTable)) {
throw new PDOException('Invalid table name.');
}
if (is_array($columns)) {
foreach ($columns as &$column) {
$column = preg_replace('/[^a-zA-Z_]*/', '', $column);
}
$columns = implode(',', $columns);
$stmt = $this->pdo->prepare("SELECT $columns FROM $table");
$stmt = $this->pdo->prepare("SELECT $columns FROM $sanitizedTable");
} else {
$stmt = $this->pdo->prepare("SELECT * FROM $table");
$stmt = $this->pdo->prepare("SELECT * FROM $sanitizedTable");
}
$stmt->execute();
return $stmt->fetchAll();
@@ -86,7 +100,8 @@ class DB
*/
public function findWithId(string $table, $id)
{
$stmt = $this->pdo->prepare("SELECT * FROM {$table} WHERE id = ?");
$sanitizedTable = phpb_remove_non_alpha_numeric($table);
$stmt = $this->pdo->prepare("SELECT * FROM {$sanitizedTable} WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetchAll();
}
@@ -118,6 +133,29 @@ class DB
return $stmt->execute($parameters);
}
/**
* Run the callback inside a database transaction, rolling back false results and exceptions.
*/
public function transaction(callable $callback): mixed
{
$this->pdo->beginTransaction();
try {
$result = $callback();
if ($result === false) {
$this->pdo->rollBack();
return false;
}
$this->pdo->commit();
return $result;
} catch (\Throwable $exception) {
if ($this->pdo->inTransaction()) {
$this->pdo->rollBack();
}
throw $exception;
}
}
function tableExists(string $table): bool
{
$tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table);
@@ -152,13 +190,13 @@ class DB
// check if table with the name $table exists. if not, execute $query.'
try {
$keys = $this->select(
"SELECT CONSTRAINT_NAME FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME = ? AND TABLE_SCHEMA = 'plugi' AND TABLE_NAME = ? AND CONSTRAINT_TYPE = 'UNIQUE'",
[$key, $tableName]
"SELECT CONSTRAINT_NAME FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME = ? AND TABLE_SCHEMA = ? AND TABLE_NAME = ? AND CONSTRAINT_TYPE = 'UNIQUE'",
[$key, $this->databaseName, $tableName]
);
if (count($keys) === 1) return true;
return false;
} catch (Exception $e) {
print_r($e->getMessage());
// Do not expose database error details to the user
return false;
}
}
@@ -176,7 +214,7 @@ class DB
}
public function getDBDefinitionHash() {
return sha1(json_encode($this->getDBDefinition()));
return hash('sha256', json_encode($this->getDBDefinition()));
}
public function diffDB() {
@@ -207,15 +245,24 @@ class DB
foreach ($diff as $table => $tableDiff) {
$tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table);
if($tableDiff === false){
$this->query("CREATE TABLE {$tableName} (`id` int NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3");
$this->query("CREATE TABLE {$tableName} (`id` int NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
$this->query("ALTER TABLE {$tableName} ADD PRIMARY KEY (`id`)");
$this->query("ALTER TABLE {$tableName} MODIFY `id` int NOT NULL AUTO_INCREMENT");
} elseif (is_array($tableDiff)) {
foreach ($tableDiff['columns'] as $column => $columnDefinition) {
$this->query("ALTER TABLE {$tableName} ADD {$column} {$columnDefinition}");
// Validate column name to prevent SQL injection
$sanitizedColumn = phpb_remove_non_alpha_numeric($column);
if (empty($sanitizedColumn)) continue;
// Validate column definition against a safe pattern
if (!preg_match('/^[A-Z\s(),0-9_`]+$/', $columnDefinition)) continue;
$this->query("ALTER TABLE {$tableName} ADD {$sanitizedColumn} {$columnDefinition}");
}
foreach ($tableDiff['uniqueKeys'] as $key => $keyDefinition) {
$this->query("ALTER TABLE {$tableName} ADD UNIQUE KEY {$key} ($keyDefinition)");
// Validate key name and definition
$sanitizedKey = phpb_remove_non_alpha_numeric($key);
if (empty($sanitizedKey)) continue;
if (!preg_match('/^[A-Z,`\s_]+$/', $keyDefinition)) continue;
$this->query("ALTER TABLE {$tableName} ADD UNIQUE KEY {$sanitizedKey} ($keyDefinition)");
}
}
}
+1 -1
View File
@@ -33,7 +33,7 @@ class EnvLoader
continue;
}
list($name, $value) = explode('=', $line, 2);
[$name, $value] = explode('=', $line, 2);
$name = trim($name);
$value = trim($value);
+298
View File
@@ -0,0 +1,298 @@
<?php
namespace Plugi\Core;
class Mailer
{
private array $config;
public function __construct(?array $config = null)
{
if ($config === null) {
$configuredMail = function_exists('phpb_config') ? phpb_config('mail') : null;
$config = is_array($configuredMail) ? $configuredMail : [];
}
$this->config = $config;
}
public function send(string $to, string $subject, string $message): bool
{
$settings = $this->validatedSettings();
if ($settings === null || !$this->isValidEmail($to) || !$this->isSafeHeader($subject) || strlen($subject) > 500) {
return false;
}
$socket = $this->connect($settings);
if (!is_resource($socket)) {
return false;
}
try {
if ($this->readResponse($socket) !== 220) {
return false;
}
if ($this->sendCommand($socket, 'EHLO localhost') !== 250) {
return false;
}
if ($settings['encryption'] === 'tls') {
if ($this->sendCommand($socket, 'STARTTLS') !== 220) {
return false;
}
if (@stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT) !== true) {
return false;
}
if ($this->sendCommand($socket, 'EHLO localhost') !== 250) {
return false;
}
}
if ($settings['username'] !== '') {
if (!$this->authenticate($socket, $settings['username'], $settings['password'])) {
return false;
}
}
if ($this->sendCommand($socket, 'MAIL FROM:<' . $settings['from_address'] . '>') !== 250) {
return false;
}
if (!in_array($this->sendCommand($socket, 'RCPT TO:<' . $to . '>'), [250, 251], true)) {
return false;
}
if ($this->sendCommand($socket, 'DATA') !== 354) {
return false;
}
$messageData = $this->buildMessage($settings, $to, $subject, $message);
if (!$this->write($socket, $messageData)) {
return false;
}
$delivered = $this->readResponse($socket) === 250;
$this->sendCommand($socket, 'QUIT');
return $delivered;
} catch (\Throwable $exception) {
return false;
} finally {
fclose($socket);
}
}
private function validatedSettings(): ?array
{
if (($this->config['transport'] ?? null) !== 'smtp') {
return null;
}
$host = $this->config['host'] ?? null;
if (!is_string($host) || $host === '' || !$this->isValidHost($host)) {
return null;
}
$port = filter_var($this->config['port'] ?? null, FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1, 'max_range' => 65535],
]);
if ($port === false) {
return null;
}
$encryption = $this->config['encryption'] ?? null;
if (!is_string($encryption) || !in_array($encryption, ['tls', 'ssl', 'none'], true)) {
return null;
}
$timeout = $this->config['timeout'] ?? null;
if ((!is_int($timeout) && !is_float($timeout) && !(is_string($timeout) && is_numeric($timeout))) || !is_finite((float) $timeout) || (float) $timeout <= 0 || (float) $timeout > 300) {
return null;
}
$fromAddress = $this->config['from_address'] ?? null;
if (!is_string($fromAddress) || !$this->isValidEmail($fromAddress)) {
return null;
}
$fromName = $this->config['from_name'] ?? '';
if (!is_string($fromName) || !$this->isSafeHeader($fromName) || strlen($fromName) > 500) {
return null;
}
$username = $this->config['username'] ?? '';
$password = $this->config['password'] ?? '';
if (!is_string($username) || !is_string($password) || (($username === '') !== ($password === '')) || strlen($username) > 250 || strlen($password) > 250) {
return null;
}
if ($username !== '' && strlen(base64_encode("\0" . $username . "\0" . $password)) > 500) {
return null;
}
return [
'host' => $host,
'port' => (int) $port,
'encryption' => $encryption,
'timeout' => (float) $timeout,
'username' => $username,
'password' => $password,
'from_address' => $fromAddress,
'from_name' => $fromName,
];
}
private function isValidHost(string $host): bool
{
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;
}
private function isValidEmail(string $address): bool
{
return filter_var($address, FILTER_VALIDATE_EMAIL) !== false && preg_match('/[\r\n\x00-\x1F\x7F]/', $address) !== 1;
}
private function isSafeHeader(string $value): bool
{
return preg_match('/[\r\n\x00-\x1F\x7F]/', $value) !== 1 && preg_match('//u', $value) === 1;
}
private function connect(array $settings)
{
$host = $settings['host'];
$socketHost = filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false ? '[' . $host . ']' : $host;
$scheme = $settings['encryption'] === 'ssl' ? 'ssl' : 'tcp';
$target = $scheme . '://' . $socketHost . ':' . $settings['port'];
$context = stream_context_create([
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
'peer_name' => $host,
'SNI_enabled' => true,
],
]);
$errno = 0;
$error = '';
$socket = @stream_socket_client(
$target,
$errno,
$error,
$settings['timeout'],
STREAM_CLIENT_CONNECT,
$context
);
if (is_resource($socket)) {
$seconds = (int) floor($settings['timeout']);
$microseconds = (int) ceil(($settings['timeout'] - $seconds) * 1000000);
if ($microseconds === 1000000) {
$seconds++;
$microseconds = 0;
}
stream_set_timeout($socket, $seconds, $microseconds);
}
return $socket;
}
private function authenticate($socket, string $username, string $password): bool
{
$response = $this->sendCommand($socket, 'AUTH PLAIN');
if ($response === 235) {
return true;
}
if ($response !== 334) {
return false;
}
$credentials = base64_encode("\0" . $username . "\0" . $password);
return $this->writeLine($socket, $credentials) && $this->readResponse($socket) === 235;
}
private function sendCommand($socket, string $command): ?int
{
if (!$this->writeLine($socket, $command)) {
return null;
}
return $this->readResponse($socket);
}
private function writeLine($socket, string $line): bool
{
if (strlen($line) > 510 || preg_match('/[\r\n\x00-\x1F\x7F]/', $line) === 1) {
return false;
}
return $this->write($socket, $line . "\r\n");
}
private function write($socket, string $data): bool
{
$length = strlen($data);
$written = 0;
while ($written < $length) {
$count = @fwrite($socket, substr($data, $written));
if ($count === false || $count === 0) {
return false;
}
$written += $count;
}
return true;
}
private function readResponse($socket): ?int
{
$responseCode = null;
for ($lineNumber = 0; $lineNumber < 100; $lineNumber++) {
$line = @fgets($socket, 515);
if (!is_string($line) || !str_ends_with($line, "\r\n") || strlen($line) > 512 || preg_match('/\A([0-9]{3})([ -])/', $line, $matches) !== 1) {
return null;
}
$code = (int) $matches[1];
if ($responseCode !== null && $responseCode !== $code) {
return null;
}
$responseCode = $code;
if ($matches[2] === ' ') {
return $responseCode;
}
}
return null;
}
private function buildMessage(array $settings, string $to, string $subject, string $message): string
{
$from = $settings['from_name'] === ''
? '<' . $settings['from_address'] . '>'
: $this->encodeHeader($settings['from_name']) . ' <' . $settings['from_address'] . '>';
$headers = [
'From: ' . $from,
'To: ' . $to,
'Subject: ' . $this->encodeHeader($subject),
'MIME-Version: 1.0',
'Content-Type: text/plain; charset=UTF-8',
'Content-Transfer-Encoding: quoted-printable',
];
$normalizedMessage = str_replace(["\r\n", "\r"], "\n", $message);
$encodedMessage = str_replace(["\r\n", "\r"], "\n", quoted_printable_encode(str_replace("\n", "\r\n", $normalizedMessage)));
$messageLines = explode("\n", $encodedMessage);
foreach ($messageLines as &$line) {
if (str_starts_with($line, '.')) {
$line = '.' . $line;
}
}
unset($line);
return implode("\r\n", $headers) . "\r\n\r\n" . implode("\r\n", $messageLines) . "\r\n.\r\n";
}
private function encodeHeader(string $value): string
{
return '=?UTF-8?B?' . base64_encode($value) . '?=';
}
}
+32 -1
View File
@@ -427,7 +427,7 @@ if (! function_exists('phpb_field_value')) {
/**
* Return the posted value or the attribute value of the given instance, or null if no value was found.
*/
function phpb_field_value(string $attribute, object $instance = null): ?string
function phpb_field_value(string $attribute, ?object $instance = null): ?string
{
if (isset($_POST[$attribute])) {
return phpb_encode_or_null($_POST[$attribute]);
@@ -588,6 +588,7 @@ if (! function_exists('phpb_render_setting')) {
</label>
</div>
EOL;
break;
case 'text':
echo <<<EOL
@@ -660,6 +661,36 @@ if (! function_exists('phpb_registered_assets')) {
}
}
if (! function_exists('phpb_csrf_field')) {
/**
* Render a hidden CSRF token input field for forms.
*/
function phpb_csrf_field(): void
{
if (class_exists('\Plugi\Core\Csrf')) {
$token = \Plugi\Core\Csrf::getToken();
echo '<input type="hidden" name="_csrf_token" value="' . phpb_e($token) . '">';
}
}
}
if (! function_exists('phpb_validate_csrf')) {
/**
* Validate the CSRF token from the current POST request.
*
* @return bool True if valid, false otherwise
*/
function phpb_validate_csrf(): bool
{
if (!class_exists('\Plugi\Core\Csrf')) {
return true;
}
$token = $_POST['_csrf_token'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
return \Plugi\Core\Csrf::validateToken($token);
}
}
if (! function_exists('phpb_array_merge_deep_array')) {
/**
* Deep merging
+1 -1
View File
@@ -171,7 +171,7 @@ class Extensions
/**
* Get all settings.
*/
public static function getSettings($ext = null) : array {
public static function getSettings(?string $ext = null) : array {
$settingIns = phpb_instance('setting');
$hydrSettings = [];
foreach (self::$settings as $setting) {
+28 -1
View File
@@ -15,7 +15,13 @@ class Auth implements AuthContract
{
if (phpb_in_module('auth')) {
if ($action === 'login' && isset($_POST['username']) && isset($_POST['password'])) {
if ($_POST['username'] === $_ENV['USERNAME'] && $_POST['password'] === $_ENV['PASSWORD']) {
$usernameValid = hash_equals($_ENV['USERNAME'] ?? '', $_POST['username']);
$passwordValid = $usernameValid && $this->verifyPassword($_POST['password']);
if ($usernameValid && $passwordValid) {
// Regenerate session ID to prevent session fixation
if (session_status() === PHP_SESSION_ACTIVE) {
session_regenerate_id(true);
}
$_SESSION['phpb_logged_in'] = true;
phpb_redirect(phpb_url('website_manager'));
} else {
@@ -31,6 +37,27 @@ class Auth implements AuthContract
}
}
/**
* Verify the submitted password against the stored hash.
*
* Supports both hashed passwords (PASSWORD_HASH env var) and legacy plaintext (PASSWORD env var).
*
* @param string $password The plaintext password to verify
* @return bool
*/
protected function verifyPassword($password)
{
// Prefer hashed password if available
if (isset($_ENV['PASSWORD_HASH']) && !empty($_ENV['PASSWORD_HASH'])) {
return password_verify($password, $_ENV['PASSWORD_HASH']);
}
// Fallback to plaintext for backward compatibility (deprecated)
if (isset($_ENV['PASSWORD']) && !empty($_ENV['PASSWORD'])) {
return hash_equals($_ENV['PASSWORD'], $password);
}
return false;
}
/**
* Return whether the current request has an authenticated session.
*
@@ -3,6 +3,7 @@
</div>
<form class="login-form mt-3 flex flex-col gap-3 items-center" method="post" action="<?= phpb_url('auth', ['action' => 'login']) ?>">
<?php phpb_csrf_field(); ?>
<?php
if (phpb_flash('message')):
?>
@@ -35,7 +35,7 @@ class BaseModel
* @param PageContract|null $page
* @param bool $forPageBuilder
*/
public function __construct(ThemeBlock $block, $data = [], PageContract $page = null, $forPageBuilder = false)
public function __construct(ThemeBlock $block, $data = [], ?PageContract $page = null, $forPageBuilder = false)
{
$this->block = $block;
$this->data = is_array($data) ? $data : [];
@@ -68,7 +68,7 @@ class BlockRenderer
* @param null $id id of the specific block instance
* @return string
*/
public function renderWithSlug(string $blockSlug, $blockData = null, $id = null)
public function renderWithSlug(string $blockSlug, ?array $blockData = null, ?string $id = null)
{
$block = ($path = Extensions::getBlock($blockSlug))
? new ThemeBlock($this->theme, $path, true, $blockSlug)
@@ -85,7 +85,7 @@ class BlockRenderer
* @param null $id id of the specific block instance
* @return string
*/
public function render(ThemeBlock $themeBlock, $blockData = null, $id = null)
public function render(ThemeBlock $themeBlock, ?array $blockData = null, ?string $id = null)
{
$blockData = $blockData ?? [];
@@ -59,7 +59,7 @@ class PageBuilder implements PageBuilderContract
* @return bool
* @throws Exception
*/
public function handleRequest($route, $action, PageContract $page = null)
public function handleRequest($route, $action, ?PageContract $page = null)
{
phpb_set_in_editmode();
@@ -377,7 +377,7 @@ class PageBuilder implements PageBuilderContract
* @param string|null $css
* @return string
*/
public function customStyle(string $css = null)
public function customStyle(?string $css = null)
{
if (! is_null($css)) {
$this->css = $css;
@@ -392,7 +392,7 @@ class PageBuilder implements PageBuilderContract
* @param string|null $scripts
* @return string
*/
public function customScripts(string $location, string $scripts = null)
public function customScripts(string $location, ?string $scripts = null)
{
if (! is_null($scripts)) {
$this->scripts[$location] = $scripts;
@@ -126,7 +126,7 @@ class PageRenderer
* @param bool $canBeCached
* @param string|null $cacheLifetime
*/
public static function setCanBeCached(bool $canBeCached, $cacheLifetime = null)
public static function setCanBeCached(bool $canBeCached, ?int $cacheLifetime = null)
{
if (! $canBeCached || ($cacheLifetime && intval($cacheLifetime) <= 0)) {
static::$canBeCached = false;
@@ -279,7 +279,7 @@ class PageRenderer
* @return string
* @throws Exception
*/
public function parseShortcodes(string $htmlWithShortcodes, $context = null)
public function parseShortcodes(string $htmlWithShortcodes, ?array $context = null)
{
$context = $context ?? $this->pageBlocksData;
return $this->shortcodeParser->doShortcodes($htmlWithShortcodes, $context);
@@ -225,17 +225,17 @@ class ShortcodeParser
// as long as there are attributes in the attributes string, add them to $attributes
$attributes = [];
while (strpos($matchAttributeString, '=') !== false) {
list($attribute, $remainingString) = explode('=', $matchAttributeString, 2);
[$attribute, $remainingString] = explode('=', $matchAttributeString, 2);
$attribute = trim($attribute);
// if first char is " and at least two " exist, get attribute value between ""
if (strpos($remainingString, '"') === 0 && strpos($remainingString, '"', 1) !== false) {
list($empty, $value, $remainingString) = explode('"', $remainingString, 3);
[$empty, $value, $remainingString] = explode('"', $remainingString, 3);
$attributes[$attribute] = $value;
} else {
// attribute value was not between "", get value until next whitespace or until end of $remainingString
if (strpos($remainingString, ' ') !== false) {
list($value, $remainingString) = explode(' ', $remainingString, 2);
[$value, $remainingString] = explode(' ', $remainingString, 2);
$attributes[$attribute] = $value;
} else {
$attributes[$attribute] = $remainingString;
@@ -10,6 +10,7 @@ html, body {
</style>
<script src="<?= phpb_asset('pagebuilder/html2canvas-v0.4.1.min.js') ?>"></script>
<script>
window.csrfToken = '<?= \Plugi\Core\Csrf::getToken() ?>';
$(document).ready(function() {
html2canvas($("body"), {
allowTaint: false,
@@ -21,6 +22,9 @@ $(document).ready(function() {
$.ajax({
type: "POST",
url: "<?= phpb_url('pagebuilder', ['route' => 'thumb_generator', 'action' => 'upload']) ?>",
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', window.csrfToken);
},
data: {
block: "<?= $blockSlug ?>",
data: data
@@ -15,6 +15,31 @@ use Exception;
#[\AllowDynamicProperties]
class Uploader {
/**
* Detect the MIME type of a file using server-side inspection.
*
* @param string $filePath Path to the file
* @return string The detected MIME type
*/
protected function detectMimeType(string $filePath): string
{
if (function_exists('finfo_file')) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
if ($finfo) {
$mime = finfo_file($finfo, $filePath);
finfo_close($finfo);
if (!empty($mime)) {
return $mime;
}
}
}
// Fallback to mime_content_type if available
if (function_exists('mime_content_type')) {
return mime_content_type($filePath);
}
return '';
}
/**
* Indicates if the file has been uploaded properly.
*
@@ -216,7 +241,8 @@ class Uploader {
$this->file_src_temp = $file["tmp_name"];
$this->file_src_size = $file["size"];
$this->file_src_errors = $file['error'];
$this->file_src_mime = $file['type'];
// Use server-side MIME detection instead of trusting client-supplied $_FILES['type']
$this->file_src_mime = $this->detectMimeType($file['tmp_name']);
$this->file_src_name_ext = pathinfo($file["name"], PATHINFO_EXTENSION);
$this->was_uploaded = true;
@@ -241,7 +267,7 @@ class Uploader {
$path = $this->upload_to . $file;
$this->upload_to = dirname($path);
} else {
$hash = md5(uniqid(rand(), true));
$hash = bin2hex(random_bytes(16));
$file = $hash . '.' . $this->file_src_name_ext;
$path = $this->upload_to . $file;
}
@@ -317,7 +343,7 @@ class Uploader {
$this->final_file_name = $file;
// extract image dimensions
list($w, $h) = getimagesize($path);
[$w, $h] = getimagesize($path);
$this->file_width = $w;
$this->file_height = $h;
@@ -345,7 +371,7 @@ class Uploader {
* @param integer $mode Optional permissions
* @return boolean Success
*/
protected function r_mkdir($path, $mode = 0777) {
protected function r_mkdir($path, $mode = 0755) {
return is_dir($path) || ( $this->r_mkdir(dirname($path), $mode) && $this->_mkdir($path, $mode) );
}
@@ -356,7 +382,7 @@ class Uploader {
* @param integer $mode Optional permissions
* @return boolean Success
*/
protected function _mkdir($path, $mode = 0777) {
protected function _mkdir($path, $mode = 0755) {
$old = umask(0);
$res = @mkdir($path, $mode);
umask($old);
@@ -531,7 +531,8 @@
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': window.csrfToken
},
body: formData
});
@@ -61,7 +61,8 @@
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': window.csrfToken
},
body: formData
});
@@ -273,13 +274,15 @@
const formData = new URLSearchParams();
formData.append('data', JSON.stringify(data));
formData.append('_csrf_token', window.csrfToken);
try {
const response = await fetch(saveUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': window.csrfToken
},
body: formData
});
@@ -6,7 +6,8 @@ window.editor.on('asset:remove', function(asset) {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"X-Requested-With": "XMLHttpRequest"
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": window.csrfToken
},
body: new URLSearchParams({ id: assetId })
}).catch(function() {});
@@ -36,9 +36,14 @@ window.pages = <?= json_encode($pageBuilder->getPages()) ?>;
window.renderBlockUrl = '<?= phpb_url('pagebuilder', ['action' => 'renderBlock', 'page' => $page->getId()]) ?>';
window.injectionScriptUrl = '<?= phpb_asset('pagebuilder/page-injection.js') ?>';
window.renderLanguageVariantUrl = '<?= phpb_url('pagebuilder', ['action' => 'renderLanguageVariant', 'page' => $page->getId()]) ?>';
window.csrfToken = '<?= phpb_e(\Plugi\Core\Csrf::getToken()) ?>';
<?php
$config = require __DIR__ . '/grapesjs/config.php';
// Add CSRF token header to GrapesJS file uploads
$config['assetManager']['headers'] = [
'X-CSRF-Token' => \Plugi\Core\Csrf::getToken()
];
?>
let config = <?= json_encode($config) ?>;
config.selectorManager.escapeName = name => `${name}`.trim().replace(/([^a-z0-9\w-\:\/]+)/gi, '-')
@@ -78,18 +78,24 @@ class WebsiteManager implements WebsiteManagerContract
*/
public function handleCreate()
{
$errorMessage = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$pageRepository = new PageRepository;
$page = $pageRepository->create($_POST);
try {
$pageRepository = new PageRepository;
$page = $pageRepository->create($_POST);
} catch (\Throwable) {
$page = false;
}
if ($page) {
phpb_redirect(phpb_url('website_manager'), [
'message-type' => 'success',
'message' => phpb_trans('website-manager.page-created')
]);
}
$errorMessage = phpb_trans('website-manager.page-create-failed');
}
$this->renderPageSettings();
$this->renderPageSettings(null, $errorMessage);
}
/**
@@ -217,7 +223,7 @@ class WebsiteManager implements WebsiteManagerContract
*
* @param PageContract $page
*/
public function renderPageSettings(PageContract $page = null)
public function renderPageSettings(?PageContract $page = null, ?string $errorMessage = null)
{
$action = isset($page) ? 'edit' : 'create';
$theme = phpb_instance('theme', [
@@ -5,11 +5,27 @@ if (isset($page)) {
}
$pageTranslations = $page ? $page->getTranslations() : [];
$fieldValue = static function (string $field, ?string $languageCode = null) use ($page, $pageTranslations): string {
if ($languageCode !== null) {
$postedValues = $_POST[$field] ?? null;
$value = (is_array($postedValues) ? ($postedValues[$languageCode] ?? null) : null)
?? $pageTranslations[$languageCode][$field]
?? '';
} else {
$value = $_POST[$field] ?? ($page?->get($field) ?? '');
}
return is_scalar($value) ? (string) $value : '';
};
$javascriptValue = static function (string $value): string {
$encodedValue = json_encode($value, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES);
return phpb_e($encodedValue === false ? '""' : $encodedValue);
};
?>
<div class="manager-panel p-8 w-full">
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'page_settings', 'action' => $action]) ?><?= $pageUrlParam ?>">
<?php phpb_csrf_field(); ?>
<div class="text-center text-3xl font-bold mb-8 mt-2">
<?php
if ($action === 'create'):
@@ -20,13 +36,19 @@ $pageTranslations = $page ? $page->getTranslations() : [];
?>
</div>
<div class="max-w-lg p-4 mx-auto" x-data="{type: '<?= phpb_field_value('type', $page) ?? 'static' ?>'}">
<?php if (! empty($errorMessage)): ?>
<div class="alert alert-error mb-6" role="alert">
<span><?= phpb_e($errorMessage) ?></span>
</div>
<?php endif; ?>
<div class="max-w-lg p-4 mx-auto" x-data="{type: <?= $javascriptValue($fieldValue('type') !== '' ? $fieldValue('type') : 'static') ?>}">
<div class="form-control w-full mb-4">
<label class="label">
<span class="label-text"> <?= phpb_trans('website-manager.name') ?></span>
<span class="label-text-alt"><?= phpb_trans('website-manager.required') ?></span>
</label>
<input type="text" id="name" name="name" value="<?= phpb_field_value('name', $page) ?>" required class="input input-bordered w-full" />
<input type="text" id="name" name="name" value="<?= phpb_e($fieldValue('name')) ?>" required class="input input-bordered w-full" />
<label class="label">
<span class="label-text-alt"><?= phpb_trans('website-manager.visible-in-page-overview') ?></span>
</label>
@@ -40,7 +62,7 @@ $pageTranslations = $page ? $page->getTranslations() : [];
<select class="select select-bordered" x-model="type" id="type" name="type" required>
<?php
$types = ['static', 'redirect'];
$value = phpb_field_value('type', $page);
$value = $fieldValue('type');
foreach ($types as $type):
if ($type === $value):
echo '<option value="' . phpb_e($type) . '" selected>' . phpb_trans('website-manager.page-types.'.$type) . '</option>';
@@ -59,7 +81,7 @@ $pageTranslations = $page ? $page->getTranslations() : [];
</label>
<select class="select select-bordered" id="layout" name="layout" required>
<?php
$value = phpb_field_value('layout', $page);
$value = $fieldValue('layout');
foreach ($theme->getThemeLayouts() as $layout):
if ($layout->getSlug() === $value):
echo '<option value="' . phpb_e($layout->getSlug()) . '" selected>' . phpb_e($layout->getTitle()) . '</option>';
@@ -78,34 +100,34 @@ $pageTranslations = $page ? $page->getTranslations() : [];
<details class="collapse collapse-plus bg-white mt-6" <?= phpb_e($firstLang ? 'open' : '') ?>>
<summary class="collapse-title text-xl font-medium"><?= phpb_trans('languages.' . $languageCode) ?></summary>
<div class="collapse-content">
<div x-data="{route: '<?= phpb_e($pageTranslations[$languageCode]['route'] ?? '') ?>', empty: true, locale: '<?= $firstLang ? '' : '/'.phpb_e($languageCode) ?>'}" x-init="empty = route.length === 0">
<div x-data="{route: <?= $javascriptValue($fieldValue('route', $languageCode)) ?>, empty: true, locale: <?= $javascriptValue($firstLang ? '' : '/' . $languageCode) ?>}" x-init="empty = route.length === 0">
<div class="form-control w-full mb-2">
<label class="label" for="<?= phpb_e($languageCode) ?>-page-title">
<span class="label-text"><?= phpb_trans('website-manager.page-title') ?></span>
<span class="label-text-alt"><?= phpb_trans('website-manager.required') ?></span>
</label>
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-title" name="title[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($pageTranslations[$languageCode]['title'] ?? '') ?>" @input="if(empty){route=`${locale}/${slugify($event.target.value)}`}" :required="type==='static'" />
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-title" name="title[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($fieldValue('title', $languageCode)) ?>" @input="if(empty){route=`${locale}/${slugify($event.target.value)}`}" :required="type==='static'" />
</div>
<div class="form-control w-full mb-2" x-show="type === 'static'">
<label class="label" for="<?= phpb_e($languageCode) ?>-page-meta-title">
<span class="label-text"><?= phpb_trans('website-manager.page-meta-title') ?></span>
</label>
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-meta-title" name="meta_title[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($pageTranslations[$languageCode]['meta_title'] ?? '') ?>" />
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-meta-title" name="meta_title[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($fieldValue('meta_title', $languageCode)) ?>" />
</div>
<div class="form-control w-full mb-2" x-show="type === 'static'">
<label class="label" for="<?= phpb_e($languageCode) ?>-page-meta-description">
<span class="label-text"><?= phpb_trans('website-manager.page-meta-description') ?></span>
</label>
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-meta-description" name="meta_description[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($pageTranslations[$languageCode]['meta_description'] ?? '') ?>" />
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-meta-description" name="meta_description[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($fieldValue('meta_description', $languageCode)) ?>" />
</div>
<div class="form-control w-full mb-2" x-show="type === 'redirect'">
<label class="label" for="<?= phpb_e($languageCode) ?>-page-target-redirect">
<span class="label-text"><?= phpb_trans('website-manager.target-redirect') ?></span>
</label>
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-target-redirect" name="target[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($pageTranslations[$languageCode]['target'] ?? '') ?>" />
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-target-redirect" name="target[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($fieldValue('target', $languageCode)) ?>" />
</div>
<div class="form-control w-full mb-2">
@@ -114,7 +136,7 @@ $pageTranslations = $page ? $page->getTranslations() : [];
<span class="label-text-alt"><?= phpb_trans('website-manager.required') ?></span>
</label>
<div class="join" x-data="{disabled: true}">
<input type="text" :class="{'join-item': type !== 'redirect'}" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-route" name="route[<?= phpb_e($languageCode) ?>]" :value="route" :disabled="disabled && type !== 'redirect'" required />
<input type="text" :class="{'join-item': type !== 'redirect'}" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-route" name="route[<?= phpb_e($languageCode) ?>]" x-model="route" :readonly="disabled && type !== 'redirect'" required />
<button class="btn join-item btn-outline text-2xl" @click.stop.prevent="disabled=!disabled" type="button" x-show="type !== 'redirect'">
<i class="ph ph-pencil" x-show="disabled"></i>
<i class="ph ph-pencil-slash" x-show="!disabled"></i>
@@ -14,6 +14,7 @@ use Plugi\Setting;
<th>Database</th>
<td>
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'database', 'action' => 'update']) ?>">
<?php phpb_csrf_field(); ?>
<?php
global $phpb_db;
$diff = $phpb_db->diffDB();
@@ -8,6 +8,7 @@ $pages = $pageRepository->getAll();
?>
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'menus', 'action' => 'update', 'tab' => 'menus']) ?>">
<?php phpb_csrf_field(); ?>
<div class="main-spacing" x-data="{menus: <?= phpb_e($menusJson) ?>, pages: <?= phpb_e($menuPagesJson) ?>}">
@@ -6,6 +6,7 @@ $settingIns = phpb_instance('setting');
?>
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'settings', 'action' => 'update', 'tab' => 'settings']) ?>">
<?php phpb_csrf_field(); ?>
<div class="" x-data="{activeTab: 0, tabs: ['Website','Language','Theme','Extensions']}">
<div class="tabs mb-6">
<div class="border-b border-base-300 grow"></div>
@@ -38,7 +39,7 @@ $settingIns = phpb_instance('setting');
</label>
<select class="select select-bordered w-full" id="admin_language" name="admin_language" title="<?= phpb_trans('website-manager.languages-selector-placeholder') ?>" required>
<?php
$beLanguages = ['de', 'en', 'es', 'nl'];
$beLanguages = ['de', 'en', 'sv'];
foreach ($beLanguages as $locale):
?>
<option value="<?= phpb_e($locale) ?>" <?= phpb_e(phpb_config('general.language') === $locale ? 'selected' : '') ?>><?= phpb_e(phpb_trans('languages.'.$locale)) ?></option>
+2 -2
View File
@@ -126,7 +126,7 @@ class Page implements PageContract
* @param string|null $locale
* @return mixed|string|null
*/
public function getTranslation(string $setting, $locale = null)
public function getTranslation(string $setting, ?string $locale = null)
{
$translations = $this->getTranslations();
if (empty($translations)) {
@@ -145,7 +145,7 @@ class Page implements PageContract
* @param string|null $locale
* @return mixed|string|null
*/
public function getRoute($locale = null)
public function getRoute(?string $locale = null)
{
$routeTranslation = $this->getTranslation('route', $locale);
foreach (phpb_route_parameters() as $routeParameter => $value) {
+33 -4
View File
@@ -55,6 +55,12 @@ class Plugi
}
if (session_status() === PHP_SESSION_NONE) {
// Harden session cookies against hijacking and fixation
$isHttps = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
ini_set('session.cookie_httponly', '1');
ini_set('session.cookie_samesite', 'Strict');
ini_set('session.cookie_secure', $isHttps ? '1' : '0');
ini_set('session.use_strict_mode', '1');
session_start();
}
@@ -360,8 +366,14 @@ class Plugi
* @param string|null $action
* @return bool
*/
public function handleRequest($action = null)
public function handleRequest(?string $action = null)
{
// Set security headers on every request
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');
$route = $route ?? $_GET['route'] ?? null;
$action = $action ?? $_GET['action'] ?? $_POST['action'] ?? null;
if (! phpb_config('auth.use_login') || ! phpb_config('website_manager.use_website_manager')) {
@@ -369,6 +381,16 @@ class Plugi
. 'Implement a piece of code that checks whether the user is logged in. If logged in, call handleAuthenticatedRequest() or else call handlePublicRequest().');
}
// Validate CSRF token on POST requests for authenticated admin routes only
// (login has its own protection, public extension routes don't need CSRF)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action !== 'login') {
$isAdminRoute = phpb_in_module('website_manager') || phpb_in_module('pagebuilder');
if ($isAdminRoute && !phpb_validate_csrf()) {
header('HTTP/1.1 403 Forbidden');
die('Invalid CSRF token. Please refresh the page and try again.');
}
}
// handle login and logout requests
$this->auth->handleRequest($action);
@@ -525,7 +547,7 @@ class Plugi
* @param string|null $route
* @param string|null $action
*/
public function handleAuthenticatedRequest($route = null, $action = null)
public function handleAuthenticatedRequest(?string $route = null, ?string $action = null)
{
$route = $route ?? $_GET['route'] ?? null;
$action = $action ?? $_GET['action'] ?? null;
@@ -568,14 +590,21 @@ class Plugi
}
$uploadedFile = $uploadedFile[0];
$serverFile = realpath(phpb_config('storage.uploads_folder') . '/' . $uploadedFile->server_file);
$uploadsFolder = realpath(phpb_config('storage.uploads_folder'));
$serverFile = realpath($uploadsFolder . '/' . $uploadedFile->server_file);
// add backwards compatibility for files uploaded with Plugi <= v0.12.0, stored as /uploads/{id}.{extension}
if (! $serverFile) $serverFile = realpath(phpb_config('storage.uploads_folder') . '/' . basename($uploadedFile->server_file));
if (! $serverFile) $serverFile = realpath($uploadsFolder . '/' . basename($uploadedFile->server_file));
if (! $serverFile) {
header("HTTP/1.1 404 Not Found");
exit();
}
// prevent path traversal by ensuring the resolved path stays within the uploads folder
if (strpos($serverFile, $uploadsFolder) !== 0) {
header("HTTP/1.1 403 Forbidden");
exit();
}
header('Content-Type: ' . $uploadedFile->mime_type);
header('Content-Disposition: inline; filename="' . basename($uploadedFile->original_file) . '"');
header('Expires: 0');
@@ -60,10 +60,13 @@ class BaseRepository
$columns = implode(', ', $columns);
$questionMarks = implode(', ', array_fill(0, sizeof($data), '?'));
$this->db->query(
$success = $this->db->query(
"INSERT INTO {$this->table} ({$columns}) VALUES ({$questionMarks})",
array_values($data)
);
if (! $success) {
return null;
}
$id = $this->db->lastInsertId();
if ($id) {
+108 -28
View File
@@ -4,7 +4,7 @@ namespace Plugi\Repositories;
use Plugi\Contracts\PageContract;
use Plugi\Contracts\PageRepositoryContract;
use Exception;
use Plugi\Contracts\PageTranslationContract;
class PageRepository extends BaseRepository implements PageRepositoryContract
{
@@ -36,26 +36,38 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
* Create a new page.
*
* @param array $data
* @return bool|object|null
* @throws Exception
* @return bool
* @throws \Throwable
*/
public function create(array $data)
{
foreach (['name', 'layout'] as $field) {
if (! isset($data[$field]) || ! is_string($data[$field])) {
if (! isset($data[$field]) || ! is_string($data[$field]) || trim($data[$field]) === '') {
return false;
}
}
$page = parent::create([
'name' => $data['name'],
'layout' => $data['layout'],
'type' => $data['type'],
]);
if (! ($page instanceof PageContract)) {
throw new Exception("Page not of type PageContract");
if (! isset($data['type']) || ! is_string($data['type']) || ! in_array($data['type'], ['static', 'redirect'], true)) {
return false;
}
return $this->replaceTranslations($page, $data);
$activeLanguages = phpb_active_languages();
if (! $this->hasValidTranslationData($data, $activeLanguages)) {
return false;
}
return $this->db->transaction(function () use ($data) {
$page = parent::create([
'name' => $data['name'],
'layout' => $data['layout'],
'type' => $data['type'],
]);
if (! ($page instanceof PageContract)) {
return false;
}
return $this->replaceTranslations($page, $data);
});
}
/**
@@ -63,7 +75,7 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
*
* @param $page
* @param array $data
* @return bool|object|null
* @return bool
*/
public function update($page, array $data)
{
@@ -73,14 +85,25 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
}
}
$this->replaceTranslations($page, $data);
$activeLanguages = phpb_active_languages();
if (! $this->hasValidTranslationData($data, $activeLanguages)) {
return false;
}
$updateResult = parent::update($page, [
'name' => $data['name'],
'layout' => $data['layout'],
'type' => $data['type'],
]);
$page->invalidateCache();
$updateResult = $this->db->transaction(function () use ($page, $data) {
if (! $this->replaceTranslations($page, $data)) {
return false;
}
return parent::update($page, [
'name' => $data['name'],
'layout' => $data['layout'],
'type' => $data['type'],
]);
});
if ($updateResult) {
$page->invalidateCache();
}
return $updateResult;
}
@@ -94,18 +117,17 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
protected function replaceTranslations(PageContract $page, array $data)
{
$activeLanguages = phpb_active_languages();
foreach (['title', 'meta_title', 'meta_description', 'route', 'target'] as $field) {
foreach ($activeLanguages as $languageCode => $languageTranslation) {
if (! isset($data[$field][$languageCode])) {
return false;
}
}
if (! $this->hasValidTranslationData($data, $activeLanguages)
|| $this->hasRouteCollision($data, $activeLanguages, $page->getId())) {
return false;
}
$pageTranslationRepository = new PageTranslationRepository;
$pageTranslationRepository->destroyWhere(phpb_config('page.translation.foreign_key'), $page->getId());
if (! $pageTranslationRepository->destroyWhere(phpb_config('page.translation.foreign_key'), $page->getId())) {
return false;
}
foreach ($activeLanguages as $languageCode => $languageTranslation) {
$pageTranslationRepository->create([
$translation = $pageTranslationRepository->create([
phpb_config('page.translation.foreign_key') => $page->getId(),
'locale' => $languageCode,
'title' => $data['title'][$languageCode],
@@ -114,11 +136,69 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
'route' => $data['route'][$languageCode],
'target' => $data['target'][$languageCode],
]);
if (! ($translation instanceof PageTranslationContract)) {
return false;
}
}
return true;
}
protected function hasValidTranslationData(array $data, array $activeLanguages): bool
{
if (empty($activeLanguages) || ! isset($data['type']) || ! is_string($data['type'])
|| ! in_array($data['type'], ['static', 'redirect'], true)) {
return false;
}
foreach (['title', 'meta_title', 'meta_description', 'route', 'target'] as $field) {
if (! isset($data[$field]) || ! is_array($data[$field])) {
return false;
}
foreach ($activeLanguages as $languageCode => $languageTranslation) {
if (! array_key_exists($languageCode, $data[$field]) || ! is_string($data[$field][$languageCode])) {
return false;
}
if ($field === 'route' && trim($data[$field][$languageCode]) === '') {
return false;
}
if ($field === 'title' && $data['type'] === 'static' && trim($data[$field][$languageCode]) === '') {
return false;
}
if ($field === 'target' && $data['type'] === 'redirect' && trim($data[$field][$languageCode]) === '') {
return false;
}
}
}
return true;
}
protected function hasRouteCollision(array $data, array $activeLanguages, $pageId = null): bool
{
$routes = [];
foreach ($activeLanguages as $languageCode => $languageTranslation) {
$route = $data['route'][$languageCode];
if (array_key_exists($route, $routes)) {
return true;
}
$routes[$route] = true;
}
$foreignKey = phpb_config('page.translation.foreign_key');
$pageTranslationRepository = new PageTranslationRepository;
foreach ($pageTranslationRepository->getAll(['route', $foreignKey]) as $translation) {
if ($pageId !== null && (string) $translation->$foreignKey === (string) $pageId) {
continue;
}
if (array_key_exists($translation->route, $routes)) {
return true;
}
}
return false;
}
/**
* Update the given page with the given updated page data.
*
+2 -2
View File
@@ -49,7 +49,7 @@ class ThemeBlock
* @param bool $isExtension
* @param string|null $extensionSlug
*/
public function __construct(ThemeContract $theme, string $blockSlug, bool $isExtension = false, string $extensionSlug = null)
public function __construct(ThemeContract $theme, string $blockSlug, bool $isExtension = false, ?string $extensionSlug = null)
{
$this->theme = $theme;
$this->blockSlug = $blockSlug;
@@ -292,7 +292,7 @@ class ThemeBlock
* @param $key
* @return mixed
*/
public function get($key = null)
public function get(?string $key = null)
{
if (empty($key)) {
return $this->config;
+1 -1
View File
@@ -39,7 +39,7 @@ class ThemeLayout
* @param ThemeContract $theme the theme this layout belongs to
* @param string $layoutSlug
*/
public function __construct(ThemeContract $theme, string $layoutSlug, bool $isExtension = false, string $extensionSlug = null)
public function __construct(ThemeContract $theme, string $layoutSlug, bool $isExtension = false, ?string $extensionSlug = null)
{
$this->theme = $theme;
$this->layoutSlug = $layoutSlug;
+186
View File
@@ -0,0 +1,186 @@
<?php
require_once dirname(__DIR__) . '/src/Core/Mailer.php';
use Plugi\Core\Mailer;
function assertMailerSame($expected, $actual, string $message): void
{
if ($expected !== $actual) {
throw new RuntimeException($message . ': expected ' . var_export($expected, true) . ', got ' . var_export($actual, true));
}
}
function smtpReadLine($socket): ?string
{
$line = fgets($socket, 2048);
return is_string($line) && str_ends_with($line, "\r\n") ? substr($line, 0, -2) : null;
}
function smtpReply($socket, string $reply): bool
{
return fwrite($socket, $reply . "\r\n") === strlen($reply) + 2;
}
function runSmtpPeer(array $scenario): 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 SMTP 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 SMTP 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);
$passed = smtpReply($client, '220 local.test ESMTP');
$passed = $passed && smtpReadLine($client) === 'EHLO localhost' && smtpReply($client, '250 local.test');
if ($passed && !empty($scenario['auth'])) {
$passed = smtpReadLine($client) === 'AUTH PLAIN' && smtpReply($client, '334 ');
$credentials = smtpReadLine($client);
$expectedCredentials = base64_encode("\0test-user\0test-password");
if ($passed && empty($scenario['reject_auth'])) {
$passed = $credentials === $expectedCredentials && smtpReply($client, '235 authenticated');
} elseif ($passed) {
$passed = $credentials === $expectedCredentials && smtpReply($client, '535 authentication rejected');
$passed = $passed && smtpReadLine($client) === null;
fclose($client);
exit($passed ? 0 : 1);
}
}
if ($passed) {
$passed = smtpReadLine($client) === 'MAIL FROM:<sender@example.test>' && smtpReply($client, '250 sender accepted');
}
if ($passed) {
$passed = smtpReadLine($client) === 'RCPT TO:<recipient@example.test>';
if ($passed && !empty($scenario['reject_recipient'])) {
$passed = smtpReply($client, '550 recipient rejected') && smtpReadLine($client) === null;
fclose($client);
exit($passed ? 0 : 1);
}
$passed = $passed && smtpReply($client, '250 recipient accepted');
}
if ($passed) {
$passed = smtpReadLine($client) === 'DATA' && smtpReply($client, '354 send message');
}
$data = '';
if ($passed) {
$terminated = false;
while (($line = smtpReadLine($client)) !== null) {
if ($line === '.') {
$terminated = true;
break;
}
$data .= $line . "\r\n";
}
$passed = $terminated
&& str_contains($data, 'From: =?UTF-8?B?UGx1Z2kgVGVzdA==?= <sender@example.test>')
&& str_contains($data, 'To: recipient@example.test')
&& str_contains($data, 'Subject: =?UTF-8?B?U3RhdHVzIHVwZGF0ZQ==?=')
&& str_contains($data, "..leading dot\r\n");
}
if ($passed) {
$reply = !empty($scenario['reject_message']) ? '554 message rejected' : '250 message accepted';
$passed = smtpReply($client, $reply) && smtpReadLine($client) === 'QUIT' && smtpReply($client, '221 closing');
}
fclose($client);
exit($passed ? 0 : 1);
}
fclose($server);
$config = [
'transport' => 'smtp',
'host' => '127.0.0.1',
'port' => $port,
'encryption' => 'none',
'username' => !empty($scenario['auth']) ? 'test-user' : '',
'password' => !empty($scenario['auth']) ? 'test-password' : '',
'from_address' => 'sender@example.test',
'from_name' => 'Plugi Test',
'timeout' => 3,
];
$result = (new Mailer($config))->send('recipient@example.test', 'Status update', "First line\r\n.leading dot\r\nLast line");
pcntl_waitpid($pid, $status);
if (!pcntl_wifexited($status) || pcntl_wexitstatus($status) !== 0) {
throw new RuntimeException('The scripted SMTP peer observed an unexpected protocol exchange.');
}
return [$result, $config];
}
function baseMailerConfig(): array
{
return [
'transport' => 'smtp',
'host' => '127.0.0.1',
'port' => 587,
'encryption' => 'tls',
'username' => '',
'password' => '',
'from_address' => 'sender@example.test',
'from_name' => 'Plugi Test',
'timeout' => 1,
];
}
[$success, $config] = runSmtpPeer(['auth' => true]);
assertMailerSame(true, $success, 'Authenticated SMTP delivery must succeed');
[$authFailure] = runSmtpPeer(['auth' => true, 'reject_auth' => true]);
assertMailerSame(false, $authFailure, 'Rejected SMTP authentication must fail');
[$recipientFailure] = runSmtpPeer(['reject_recipient' => true]);
assertMailerSame(false, $recipientFailure, 'A rejected SMTP recipient must fail');
[$messageFailure] = runSmtpPeer(['reject_message' => true]);
assertMailerSame(false, $messageFailure, 'A rejected SMTP message must fail');
$invalidConfig = baseMailerConfig();
$invalidConfig['host'] = '';
assertMailerSame(false, (new Mailer($invalidConfig))->send('recipient@example.test', 'Subject', 'Body'), 'Incomplete SMTP configuration must fail safely');
$invalidConfig = baseMailerConfig();
$invalidConfig['username'] = 'only-a-username';
assertMailerSame(false, (new Mailer($invalidConfig))->send('recipient@example.test', 'Subject', 'Body'), 'Incomplete SMTP authentication settings must fail safely');
assertMailerSame(false, (new Mailer(baseMailerConfig()))->send('not-an-email', 'Subject', 'Body'), 'Invalid recipients must fail safely');
assertMailerSame(false, (new Mailer(baseMailerConfig()))->send('recipient@example.test', "Subject\r\nBcc: other@example.test", 'Body'), 'Header injection must fail safely');
$unavailableServer = stream_socket_server('tcp://127.0.0.1:0', $errorCode, $errorMessage);
if (!is_resource($unavailableServer)) {
throw new RuntimeException('Could not allocate a port for the SMTP connection-failure check.');
}
$unavailableAddress = stream_socket_get_name($unavailableServer, false);
$unavailablePort = (int) substr(strrchr($unavailableAddress, ':'), 1);
fclose($unavailableServer);
$unavailableConfig = baseMailerConfig();
$unavailableConfig['host'] = '127.0.0.1';
$unavailableConfig['port'] = $unavailablePort;
$unavailableConfig['encryption'] = 'none';
assertMailerSame(false, (new Mailer($unavailableConfig))->send('recipient@example.test', 'Subject', 'Body'), 'Connection refusal must fail safely');
$rootConfig = require dirname(__DIR__, 2) . '/config.php';
$templateConfig = require dirname(__DIR__, 2) . '/config.dist.php';
$mailKeys = ['class', 'transport', 'host', 'port', 'encryption', 'username', 'password', 'from_address', 'from_name', 'timeout'];
assertMailerSame($mailKeys, array_keys($rootConfig['mail']), 'Root SMTP settings must expose the documented keys');
assertMailerSame($mailKeys, array_keys($templateConfig['mail']), 'Template SMTP settings must expose the documented keys');
assertMailerSame(Plugi\Core\Mailer::class, $rootConfig['mail']['class'], 'Root configuration must select the core mailer');
assertMailerSame('', $templateConfig['mail']['username'], 'Template SMTP username must not contain credentials');
assertMailerSame('', $templateConfig['mail']['password'], 'Template SMTP password must not contain credentials');
fwrite(STDOUT, "Mailer tests passed.\n");
@@ -0,0 +1,463 @@
<?php
use Plugi\Core\DB;
use Plugi\Contracts\PageContract;
use Plugi\Contracts\PageTranslationContract;
use Plugi\Modules\GrapesJS\PageBuilder;
use Plugi\Modules\Router\DatabasePageRouter;
use Plugi\Page;
use Plugi\PageTranslation;
use Plugi\Modules\WebsiteManager\WebsiteManager;
use Plugi\Repositories\PageRepository;
require_once __DIR__ . '/../src/Contracts/PageContract.php';
require_once __DIR__ . '/../src/Contracts/PageRepositoryContract.php';
require_once __DIR__ . '/../src/Contracts/PageTranslationContract.php';
require_once __DIR__ . '/../src/Contracts/PageTranslationRepositoryContract.php';
require_once __DIR__ . '/../src/Contracts/WebsiteManagerContract.php';
require_once __DIR__ . '/../src/Contracts/RouterContract.php';
require_once __DIR__ . '/../src/Contracts/PageBuilderContract.php';
require_once __DIR__ . '/../src/Contracts/ThemeContract.php';
require_once __DIR__ . '/../src/Core/DB.php';
require_once __DIR__ . '/../src/Repositories/BaseRepository.php';
require_once __DIR__ . '/../src/Repositories/PageTranslationRepository.php';
require_once __DIR__ . '/../src/Page.php';
require_once __DIR__ . '/../src/PageTranslation.php';
require_once __DIR__ . '/../src/Repositories/PageRepository.php';
require_once __DIR__ . '/../src/Modules/WebsiteManager/WebsiteManager.php';
require_once __DIR__ . '/../src/Modules/Router/DatabasePageRouter.php';
require_once __DIR__ . '/../src/Modules/GrapesJS/PageBuilder.php';
class PageCreationTestDatabase extends DB
{
public int $translationInsertCount = 0;
public ?int $failOnTranslationInsert = null;
public bool $throwOnTranslationFailure = false;
public function __construct()
{
$this->pdo = new PDO('sqlite::memory:');
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->databaseName = 'page_creation_test';
}
public function query(string $query, array $parameters = [])
{
if (str_starts_with($query, 'INSERT INTO page_translations')) {
$this->translationInsertCount++;
if ($this->translationInsertCount === $this->failOnTranslationInsert) {
if ($this->throwOnTranslationFailure) {
throw new PDOException('Simulated page translation write failure.');
}
return false;
}
}
return parent::query($query, $parameters);
}
public function createSchema(): void
{
$this->pdo->exec('CREATE TABLE pages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
layout TEXT,
data TEXT,
type TEXT,
status TEXT,
parent_id INTEGER,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
)');
$this->pdo->exec('CREATE TABLE page_translations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id INTEGER NOT NULL,
locale TEXT NOT NULL,
title TEXT,
meta_title TEXT,
meta_description TEXT,
route TEXT,
target TEXT,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
UNIQUE (page_id, locale)
)');
}
public function rows(string $table): array
{
return $this->select("SELECT * FROM {$table}", []);
}
}
class PageCreationTestWebsiteManager extends WebsiteManager
{
public ?string $renderedErrorMessage = null;
public function renderPageSettings(?PageContract $page = null, ?string $errorMessage = null)
{
$this->renderedErrorMessage = $errorMessage;
}
}
class PageCreationTestCache
{
public function invalidate(string $route): void
{
}
}
function phpb_config(?string $key = null): mixed
{
global $pageCreationConfig;
if ($key === null) {
return $pageCreationConfig;
}
$value = $pageCreationConfig;
foreach (explode('.', $key) as $segment) {
if (! is_array($value) || ! array_key_exists($segment, $value)) {
return '';
}
$value = $value[$segment];
}
return $value;
}
function phpb_active_languages(): array
{
global $pageCreationLanguages;
return $pageCreationLanguages;
}
function phpb_route_parameters(): array
{
return [];
}
function phpb_instance(string $name, array $params = []): ?object
{
return match ($name) {
'page' => new Page(...$params),
'page.translation' => new PageTranslation(...$params),
'cache' => new PageCreationTestCache(),
default => null,
};
}
function phpb_remove_non_alpha_numeric(string $string): string
{
return preg_replace('/\W*/', '', $string);
}
function phpb_e(?string $value, bool $doubleEncode = true): string
{
return htmlspecialchars($value ?? '', ENT_QUOTES, 'UTF-8', $doubleEncode);
}
function phpb_trans(string $key): string
{
return $key;
}
function phpb_url(string $module, array $parameters = []): string
{
return '/' . $module;
}
function phpb_csrf_field(): void
{
}
function resetPageCreationDatabase(array $languages = ['en' => [], 'de' => []]): void
{
global $phpb_db, $pageCreationConfig, $pageCreationLanguages;
$_ENV['DATABASE_PREFIX'] = '';
$pageCreationConfig = [
'page' => [
'table' => 'pages',
'translation' => [
'table' => 'page_translations',
'foreign_key' => 'page_id',
],
],
];
$pageCreationLanguages = $languages;
$phpb_db = new PageCreationTestDatabase();
$phpb_db->createSchema();
}
function pageCreationPayload(array $overrides = []): array
{
return array_replace_recursive([
'name' => 'New page',
'layout' => 'default',
'type' => 'static',
'title' => ['en' => 'New page', 'de' => 'Neue Seite'],
'meta_title' => ['en' => '', 'de' => ''],
'meta_description' => ['en' => '', 'de' => ''],
'route' => ['en' => '/new-page', 'de' => '/de/new-page'],
'target' => ['en' => '', 'de' => ''],
], $overrides);
}
function assertPageCreation(bool $condition, string $message): void
{
if (! $condition) {
throw new RuntimeException($message);
}
}
function runPageCreationCase(string $name, callable $case): bool
{
try {
$case();
fwrite(STDOUT, "PASS: {$name}\n");
return true;
} catch (Throwable $exception) {
fwrite(STDERR, "FAIL: {$name}: {$exception->getMessage()}\n");
return false;
}
}
$cases = [
'locked generated routes do not leave a base page without translations' => function (): void {
resetPageCreationDatabase();
$payload = pageCreationPayload();
unset($payload['route']);
$result = (new PageRepository())->create($payload);
assertPageCreation($result === false, 'An omitted disabled route should be rejected.');
global $phpb_db;
assertPageCreation(count($phpb_db->rows('pages')) === 0, 'Invalid create left a base page row.');
assertPageCreation(count($phpb_db->rows('page_translations')) === 0, 'Invalid create left translation rows.');
},
'create handler reports validation failure and retains submitted values' => function (): void {
resetPageCreationDatabase();
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = pageCreationPayload();
unset($_POST['route']);
$submittedValues = $_POST;
$manager = new PageCreationTestWebsiteManager();
$manager->handleCreate();
global $phpb_db;
assertPageCreation($manager->renderedErrorMessage === 'website-manager.page-create-failed', 'Create failure message was not supplied to the form.');
assertPageCreation($_POST === $submittedValues, 'Create handler did not retain submitted field values.');
assertPageCreation(count($phpb_db->rows('pages')) === 0, 'Rejected create left a base page row.');
$_POST = [];
},
'create handler reports database failures and retains submitted values' => function (): void {
resetPageCreationDatabase();
global $phpb_db;
$phpb_db->failOnTranslationInsert = 2;
$phpb_db->throwOnTranslationFailure = true;
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = pageCreationPayload();
$submittedValues = $_POST;
$manager = new PageCreationTestWebsiteManager();
$manager->handleCreate();
assertPageCreation($manager->renderedErrorMessage === 'website-manager.page-create-failed', 'Database failure message was not supplied to the form.');
assertPageCreation($_POST === $submittedValues, 'Database failure discarded submitted values.');
assertPageCreation(count($phpb_db->rows('pages')) === 0, 'Database failure left a base page row.');
assertPageCreation(count($phpb_db->rows('page_translations')) === 0, 'Database failure left translations.');
$_POST = [];
},
'page form retains submitted values and submits locked routes' => function (): void {
resetPageCreationDatabase();
$_POST = [
'name' => 'Retained & page',
'type' => 'static',
'layout' => 'default',
'title' => ['en' => 'English title', 'de' => 'Deutscher Titel'],
'meta_title' => ['en' => 'English meta', 'de' => 'Deutscher Meta'],
'meta_description' => ['en' => 'English description', 'de' => 'Deutsche Beschreibung'],
'route' => ['en' => '/custom', 'de' => '/de/custom'],
'target' => ['en' => '', 'de' => ''],
];
$page = null;
$action = 'create';
$errorMessage = 'Page creation failed.';
$theme = new class {
public function getThemeLayouts(): array
{
return [new class {
public function getSlug(): string
{
return 'default';
}
public function getTitle(): string
{
return 'Default';
}
}];
}
};
ob_start();
include __DIR__ . '/../src/Modules/WebsiteManager/resources/views/page-settings.php';
$html = ob_get_clean();
assertPageCreation(str_contains($html, 'role="alert"'), 'Create failure message was not rendered.');
assertPageCreation(str_contains($html, 'Page creation failed.'), 'Create failure message was not retained.');
assertPageCreation(str_contains($html, 'value="Retained &amp; page"'), 'Page name was not retained safely.');
assertPageCreation(str_contains($html, 'value="English title"'), 'English title was not retained.');
assertPageCreation(str_contains($html, 'route: &quot;/custom&quot;'), 'Submitted route value was not retained safely.');
assertPageCreation(str_contains($html, 'name="route[en]" x-model="route" :readonly="disabled && type !== \'redirect\'"'), 'Locked route is not a successful form control.');
assertPageCreation(str_contains($html, 'disabled=!disabled'), 'Manual route editing toggle was removed.');
$_POST['title'] = 'malformed localized payload';
$_POST['route']['en'] = "'</script><img src=x>";
ob_start();
include __DIR__ . '/../src/Modules/WebsiteManager/resources/views/page-settings.php';
$malformedHtml = ob_get_clean();
assertPageCreation(str_contains($malformedHtml, 'name="title[en]" value=""'), 'Malformed localized payload broke form rendering.');
assertPageCreation(str_contains($malformedHtml, '\\u0027\\u003C/script\\u003E'), 'Submitted route was not safely encoded for Alpine.');
$_POST = [];
},
'generated routes persist for every active locale' => function (): void {
resetPageCreationDatabase();
$page = (new PageRepository())->create(pageCreationPayload());
global $phpb_db;
$pages = $phpb_db->rows('pages');
$translations = $phpb_db->rows('page_translations');
assertPageCreation($page === true, 'Generated-route page create did not succeed.');
assertPageCreation(count($pages) === 1, 'Expected one generated-route page row.');
assertPageCreation(count($translations) === 2, 'Expected generated routes for every active locale.');
assertPageCreation($translations[0]['route'] === '/new-page', 'English generated route was not persisted.');
assertPageCreation($translations[1]['route'] === '/de/new-page', 'German generated route was not persisted.');
$resolvedTranslation = (new DatabasePageRouter())->resolve('/de/new-page');
assertPageCreation($resolvedTranslation instanceof PageTranslationContract, 'Created route did not resolve.');
assertPageCreation($resolvedTranslation->getPage()->getId() === $pages[0]['id'], 'Resolved route belongs to another page.');
$content = ['components' => [['type' => 'text', 'content' => 'Saved by builder']]];
$pageBuilder = new PageBuilder();
assertPageCreation($pageBuilder->updatePage($resolvedTranslation->getPage(), $content) === true, 'Page builder content save failed.');
$updatedPage = (new PageRepository())->findWithId($pages[0]['id']);
assertPageCreation($updatedPage->getBuilderData() === $content, 'Page builder content was not persisted.');
},
'manually edited static routes persist for every active locale' => function (): void {
resetPageCreationDatabase();
$payload = pageCreationPayload([
'route' => ['en' => '/custom-path', 'de' => '/de/custom-path'],
]);
$page = (new PageRepository())->create($payload);
global $phpb_db;
$pages = $phpb_db->rows('pages');
$translations = $phpb_db->rows('page_translations');
assertPageCreation($page === true, 'Valid page create did not succeed.');
assertPageCreation(count($pages) === 1, 'Expected one base page row.');
assertPageCreation(count($translations) === 2, 'Expected one translation for each active locale.');
assertPageCreation($translations[0]['route'] === '/custom-path', 'English route was not preserved.');
assertPageCreation($translations[1]['route'] === '/de/custom-path', 'German route was not preserved.');
},
'redirect targets and routes persist for every active locale' => function (): void {
resetPageCreationDatabase();
$payload = pageCreationPayload([
'type' => 'redirect',
'target' => ['en' => 'https://example.com/en', 'de' => 'https://example.com/de'],
]);
$page = (new PageRepository())->create($payload);
global $phpb_db;
$pages = $phpb_db->rows('pages');
$translations = $phpb_db->rows('page_translations');
assertPageCreation($page === true, 'Redirect page create did not succeed.');
assertPageCreation($pages[0]['type'] === 'redirect', 'Redirect page type was not persisted.');
assertPageCreation(count($translations) === 2, 'Expected one redirect translation per active locale.');
assertPageCreation($translations[0]['target'] === 'https://example.com/en', 'English redirect target was not persisted.');
assertPageCreation($translations[1]['target'] === 'https://example.com/de', 'German redirect target was not persisted.');
},
'missing localized fields do not leave partial create state' => function (): void {
resetPageCreationDatabase();
$payload = pageCreationPayload();
unset($payload['meta_title']['de']);
$result = (new PageRepository())->create($payload);
assertPageCreation($result === false, 'An incomplete locale payload should be rejected.');
global $phpb_db;
assertPageCreation(count($phpb_db->rows('pages')) === 0, 'Incomplete create left a base page row.');
assertPageCreation(count($phpb_db->rows('page_translations')) === 0, 'Incomplete create left translation rows.');
},
'duplicate routes are rejected without creating a conflicting page' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$firstPage = $repository->create(pageCreationPayload());
$secondPage = $repository->create(pageCreationPayload(['name' => 'Conflicting page']));
global $phpb_db;
assertPageCreation($firstPage === true, 'Initial page was not created.');
assertPageCreation($secondPage === false, 'Duplicate route was not rejected.');
assertPageCreation(count($phpb_db->rows('pages')) === 1, 'Duplicate create left an extra base page.');
assertPageCreation(count($phpb_db->rows('page_translations')) === 2, 'Duplicate create changed translations.');
},
'translation write failures roll back the base page and translations' => function (): void {
resetPageCreationDatabase();
global $phpb_db;
$phpb_db->failOnTranslationInsert = 2;
$result = (new PageRepository())->create(pageCreationPayload());
assertPageCreation($result === false, 'Failed translation write was not reported.');
assertPageCreation(count($phpb_db->rows('pages')) === 0, 'Failed translation write left a base page row.');
assertPageCreation(count($phpb_db->rows('page_translations')) === 0, 'Failed translation write left partial translations.');
},
'translation write exceptions roll back the base page and translations' => function (): void {
resetPageCreationDatabase();
global $phpb_db;
$phpb_db->failOnTranslationInsert = 2;
$phpb_db->throwOnTranslationFailure = true;
try {
(new PageRepository())->create(pageCreationPayload());
} catch (PDOException) {
}
assertPageCreation(count($phpb_db->rows('pages')) === 0, 'Translation exception left a base page row.');
assertPageCreation(count($phpb_db->rows('page_translations')) === 0, 'Translation exception left partial translations.');
},
'failed translation updates restore previous page and translation state' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
$phpb_db->failOnTranslationInsert = 4;
$result = $repository->update($page, pageCreationPayload([
'name' => 'Changed page',
'route' => ['en' => '/changed', 'de' => '/de/changed'],
]));
$pages = $phpb_db->rows('pages');
$translations = $phpb_db->rows('page_translations');
assertPageCreation($result === false, 'Failed translation update was not reported.');
assertPageCreation($pages[0]['name'] === 'New page', 'Failed update changed the base page.');
assertPageCreation(count($translations) === 2, 'Failed update changed the translation count.');
assertPageCreation($translations[0]['route'] === '/new-page', 'Failed update did not restore the English route.');
assertPageCreation($translations[1]['route'] === '/de/new-page', 'Failed update did not restore the German route.');
},
];
$passed = 0;
foreach ($cases as $name => $case) {
if (runPageCreationCase($name, $case)) {
$passed++;
}
}
fwrite(STDOUT, sprintf("%d/%d page creation regression cases passed.\n", $passed, count($cases)));
exit($passed === count($cases) ? 0 : 1);
+1 -4
View File
@@ -24,8 +24,6 @@ use Plugi\Repositories\MenuRepository;
<?= Extensions::getHeaderAssets() ?>
<?php phpb_registered_assets('header'); ?>
<script src="<?= phpb_theme_asset("dist/script.js") ?>"></script>
</head>
<body>
@@ -145,8 +143,7 @@ use Plugi\Repositories\MenuRepository;
</div>
</footer>
<script src="<?= phpb_theme_asset("dist/phpb-demo-template.js") ?>"></script>
<script src="<?= phpb_theme_asset("dist/script.js") ?>"></script>
<!-- Run Plugi script.js files -->
<script type="text/javascript">
document.querySelectorAll("script").forEach(function(scriptTag) {