Feature/languages #4
@@ -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 = $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();
|
||||
$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 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">Recipient email field</span></label>
|
||||
<select x-model="finisher.options.recipientField" class="select select-bordered select-sm w-full">
|
||||
<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>
|
||||
<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>
|
||||
</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>
|
||||
Add action
|
||||
</a>
|
||||
|
||||
@@ -4,6 +4,8 @@ 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
|
||||
{
|
||||
@@ -26,6 +28,83 @@ namespace FormExtensionTests {
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
@@ -68,6 +147,7 @@ namespace FormExtensionTests {
|
||||
'first' => FirstFinisher::class,
|
||||
'second' => SecondFinisher::class,
|
||||
'sendConfirmationEmailToSubmitter' => TestConfirmationFinisher::class,
|
||||
'sendWebhook' => TestWebhookFinisher::class,
|
||||
];
|
||||
|
||||
public function finisherExists(string $key): bool
|
||||
@@ -184,9 +264,9 @@ namespace {
|
||||
}
|
||||
|
||||
$editor = file_get_contents(dirname(__DIR__) . '/admin/Views/EditForm.php');
|
||||
foreach (['finisher.options.recipientField', 'finisher.options.subject', 'finisher.options.message'] as $setting) {
|
||||
foreach (['finisherDefinitions', 'getFinisherSettings', 'finisher.options[setting.name]', 'setting.type'] as $setting) {
|
||||
if (strpos($editor, $setting) === false) {
|
||||
throw new \RuntimeException('The action editor is missing a confirmation setting: ' . $setting);
|
||||
throw new \RuntimeException('The action editor is missing registry-driven setting support: ' . $setting);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,6 +276,24 @@ namespace {
|
||||
$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,
|
||||
@@ -239,6 +337,79 @@ namespace {
|
||||
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);
|
||||
@@ -278,6 +449,18 @@ namespace {
|
||||
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']]),
|
||||
|
||||
Reference in New Issue
Block a user