add configurable form finishers and webhook delivery
Expose finisher settings through the editor registry and build the action editor dynamically. Add configurable admin email recipients and subjects, and introduce a webhook finisher with validated request options and JSON submission payloads. Expand submission handler tests to cover editor configuration, email overrides, webhook validation, HTTP responses, and submission outcomes.
This commit is contained in:
@@ -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']);
|
||||
|
||||
@@ -8,12 +8,28 @@ class SendEmailToAdmin extends DefaultFinisher
|
||||
public function execute(): bool
|
||||
{
|
||||
$settings = Extensions::getSettings('form');
|
||||
$to = $settings['email']['value'] ?? null;
|
||||
$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 = 'Form submission: '.$this->getFormName();
|
||||
$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();
|
||||
$mailer = phpb_instance('mail');
|
||||
return $mailer !== null && $mailer->send($to, $subject, $message) === true;
|
||||
|
||||
@@ -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,15 +4,95 @@ return [
|
||||
'finishers' => [
|
||||
'saveToDatabase' => [
|
||||
'class' => \Plugi\Extensions\Form\Finishers\SaveEntryToDatabase::class,
|
||||
'label' => 'Save to database'
|
||||
'label' => 'Save to database',
|
||||
'settings' => [],
|
||||
],
|
||||
'sendMailToAdmin' => [
|
||||
'class' => \Plugi\Extensions\Form\Finishers\SendEmailToAdmin::class,
|
||||
'label' => 'Send email to admin'
|
||||
'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'
|
||||
]
|
||||
'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,
|
||||
],
|
||||
],
|
||||
],
|
||||
]
|
||||
];
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
<?php
|
||||
|
||||
use Plugi\Extensions\Form\DefinitionsRepository;
|
||||
use Plugi\Extensions\Form\Finishers\FinishersRepository;
|
||||
|
||||
$formsRepository = new DefinitionsRepository();
|
||||
$finisherRepository = new FinishersRepository();
|
||||
$finisherDefinitions = $finisherRepository->getEditorConfig();
|
||||
|
||||
$form = [
|
||||
'name' => "New Form",
|
||||
@@ -31,13 +34,13 @@ $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: 'form_field', label: 'Form field', type: 'text', required: false, options: []},
|
||||
defaultFinisher: {type: 'saveToDatabase'},
|
||||
dragIndex: null,
|
||||
addField() {
|
||||
const nextNum = this.fields.length + 1;
|
||||
@@ -70,21 +73,25 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
|
||||
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;
|
||||
if (type === 'sendConfirmationEmailToSubmitter' && (!finisher.options || typeof finisher.options !== 'object' || Array.isArray(finisher.options))) {
|
||||
finisher.options = {
|
||||
recipientField: '',
|
||||
subject: 'Thank you for your submission',
|
||||
message: 'Thank you for contacting us. We have received your message.'
|
||||
};
|
||||
}
|
||||
finisher.options = {};
|
||||
this.getFinisherSettings(type).forEach(setting => {
|
||||
finisher.options[setting.name] = setting.default ?? '';
|
||||
});
|
||||
},
|
||||
init() {
|
||||
this.finishers.forEach(finisher => {
|
||||
if (finisher.type === 'sendConfirmationEmailToSubmitter') {
|
||||
this.setFinisherType(finisher, finisher.type);
|
||||
}
|
||||
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) {
|
||||
@@ -242,7 +249,7 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
|
||||
<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">No actions added yet</p>
|
||||
<a href="javascript:void(0)" @click="finishers.push({...defaultFinisher})" class="btn btn-sm btn-primary mt-2">Add your first action</a>
|
||||
<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">
|
||||
@@ -251,40 +258,50 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
|
||||
<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">
|
||||
<option value="saveToDatabase">Save to database</option>
|
||||
<option value="sendMailToAdmin">Send email to admin</option>
|
||||
<option value="sendConfirmationEmailToSubmitter">Send confirmation email to submitter</option>
|
||||
<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="finisher.type === 'sendConfirmationEmailToSubmitter'" class="space-y-3 pl-8">
|
||||
<div class="form-control">
|
||||
<label class="label"><span class="label-text">Recipient email field</span></label>
|
||||
<select x-model="finisher.options.recipientField" 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>
|
||||
<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>
|
||||
</select>
|
||||
<span x-show="fields.filter(field => field.type === 'email').length === 0" class="label-text-alt text-warning mt-1">Add an email field to the form before using this action.</span>
|
||||
</div>
|
||||
<div class="form-control">
|
||||
<label class="label"><span class="label-text">Subject</span></label>
|
||||
<input type="text" x-model="finisher.options.subject" class="input input-bordered input-sm w-full" />
|
||||
</div>
|
||||
<div class="form-control">
|
||||
<label class="label"><span class="label-text">Message</span></label>
|
||||
<textarea x-model="finisher.options.message" class="textarea textarea-bordered w-full" rows="4"></textarea>
|
||||
</div>
|
||||
<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>
|
||||
Add action
|
||||
</a>
|
||||
|
||||
Reference in New Issue
Block a user