diff --git a/config.dist.php b/config.dist.php index a6a486f..05b625a 100644 --- a/config.dist.php +++ b/config.dist.php @@ -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 diff --git a/extensions/plugi-ext-form/LICENSE b/extensions/plugi-ext-form/LICENSE deleted file mode 100644 index b4ef163..0000000 --- a/extensions/plugi-ext-form/LICENSE +++ /dev/null @@ -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. diff --git a/extensions/plugi-ext-form/admin/Classes/Finishers/DefaultFinisher.php b/extensions/plugi-ext-form/admin/Classes/Finishers/DefaultFinisher.php index bf9e398..a3248e3 100644 --- a/extensions/plugi-ext-form/admin/Classes/Finishers/DefaultFinisher.php +++ b/extensions/plugi-ext-form/admin/Classes/Finishers/DefaultFinisher.php @@ -1,29 +1,36 @@ 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'] ?? ''); } } diff --git a/extensions/plugi-ext-form/admin/Classes/Finishers/FinishersRepository.php b/extensions/plugi-ext-form/admin/Classes/Finishers/FinishersRepository.php index 0e7644b..5b5e5e0 100644 --- a/extensions/plugi-ext-form/admin/Classes/Finishers/FinishersRepository.php +++ b/extensions/plugi-ext-form/admin/Classes/Finishers/FinishersRepository.php @@ -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']); diff --git a/extensions/plugi-ext-form/admin/Classes/Finishers/SaveEntryToDatabase.php b/extensions/plugi-ext-form/admin/Classes/Finishers/SaveEntryToDatabase.php index ea3b18a..e385c3c 100644 --- a/extensions/plugi-ext-form/admin/Classes/Finishers/SaveEntryToDatabase.php +++ b/extensions/plugi-ext-form/admin/Classes/Finishers/SaveEntryToDatabase.php @@ -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; } } diff --git a/extensions/plugi-ext-form/admin/Classes/Finishers/SendConfirmationEmailToSubmitter.php b/extensions/plugi-ext-form/admin/Classes/Finishers/SendConfirmationEmailToSubmitter.php new file mode 100644 index 0000000..7148247 --- /dev/null +++ b/extensions/plugi-ext-form/admin/Classes/Finishers/SendConfirmationEmailToSubmitter.php @@ -0,0 +1,44 @@ +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; + } +} \ No newline at end of file diff --git a/extensions/plugi-ext-form/admin/Classes/Finishers/SendEmailToAdmin.php b/extensions/plugi-ext-form/admin/Classes/Finishers/SendEmailToAdmin.php index 0298683..b750548 100644 --- a/extensions/plugi-ext-form/admin/Classes/Finishers/SendEmailToAdmin.php +++ b/extensions/plugi-ext-form/admin/Classes/Finishers/SendEmailToAdmin.php @@ -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; } diff --git a/extensions/plugi-ext-form/admin/Classes/Finishers/SendWebhook.php b/extensions/plugi-ext-form/admin/Classes/Finishers/SendWebhook.php new file mode 100644 index 0000000..96c703c --- /dev/null +++ b/extensions/plugi-ext-form/admin/Classes/Finishers/SendWebhook.php @@ -0,0 +1,108 @@ +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; + } +} \ No newline at end of file diff --git a/extensions/plugi-ext-form/admin/Classes/Finishers/config.php b/extensions/plugi-ext-form/admin/Classes/Finishers/config.php index 768941d..551d764 100644 --- a/extensions/plugi-ext-form/admin/Classes/Finishers/config.php +++ b/extensions/plugi-ext-form/admin/Classes/Finishers/config.php @@ -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, + ], + ], + ], ] ]; diff --git a/extensions/plugi-ext-form/admin/Classes/SubmissionHandler.php b/extensions/plugi-ext-form/admin/Classes/SubmissionHandler.php new file mode 100644 index 0000000..a66e5dd --- /dev/null +++ b/extensions/plugi-ext-form/admin/Classes/SubmissionHandler.php @@ -0,0 +1,222 @@ +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); + } +} \ No newline at end of file diff --git a/extensions/plugi-ext-form/admin/Views/EditForm.php b/extensions/plugi-ext-form/admin/Views/EditForm.php index f7c2333..38964ab 100644 --- a/extensions/plugi-ext-form/admin/Views/EditForm.php +++ b/extensions/plugi-ext-form/admin/Views/EditForm.php @@ -1,11 +1,14 @@ getEditorConfig(); $form = [ - 'name' => "Neues Formular", + 'name' => "New Form", 'fields' => "[]", 'finishers' => "[]", ]; @@ -22,8 +25,8 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
= $isEditing ? 'Ändere die Einstellungen deines Formulars.' : 'Erstelle ein neues Formular mit Feldern und Aktionen.' ?>
+= $isEditing ? 'Change your form settings.' : 'Create a new form with fields and actions.' ?>