Merge remote-tracking branch 'origin/dev' into dev
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
+44
@@ -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,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>
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
@@ -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.
|
||||
@@ -150,5 +150,6 @@ return [
|
||||
'es' => 'Spanisch',
|
||||
'it' => 'Italienisch',
|
||||
'fr' => 'Französisch',
|
||||
'sv' => 'Schwedisch',
|
||||
],
|
||||
];
|
||||
|
||||
@@ -150,5 +150,6 @@ return [
|
||||
'it' => 'Italian',
|
||||
'fr' => 'French',
|
||||
'de' => 'German',
|
||||
'sv' => 'Swedish',
|
||||
],
|
||||
];
|
||||
|
||||
@@ -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',
|
||||
],
|
||||
];
|
||||
@@ -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',
|
||||
],
|
||||
];
|
||||
@@ -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',
|
||||
],
|
||||
];
|
||||
@@ -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) . '?=';
|
||||
}
|
||||
}
|
||||
@@ -39,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>
|
||||
|
||||
@@ -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");
|
||||
Reference in New Issue
Block a user