Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,18 @@

# Changelog

## Unreleased

- **Confirmation emails for respondents**

Form owners can enable an automatic confirmation email that is sent to the respondent after a successful submission.
Requires an email-validated short text question in the form.

Supported placeholders in subject/body:

- `{formTitle}`, `{formDescription}`
- `{<fieldName>}` (question `name` or text, sanitized)

## v5.2.0 - 2025-09-25

- **Time: restrictions and ranges**
Expand Down
3 changes: 3 additions & 0 deletions docs/API_v3.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,9 @@ Returns the full-depth object of the requested form (without submissions).
"state": 0,
"lockedBy": null,
"lockedUntil": null,
"confirmationEmailEnabled": false,
"confirmationEmailSubject": null,
"confirmationEmailBody": null,
"permissions": [
"edit",
"results",
Expand Down
6 changes: 6 additions & 0 deletions docs/DataStructure.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ This document describes the Object-Structure, that is used within the Forms App
| description | String | max. 8192 ch. | The Form description |
| ownerId | String | | The nextcloud userId of the form owner |
| submissionMessage | String | max. 2048 ch. | Optional custom message, with Markdown support, to be shown to users when the form is submitted (default is used if set to null) |
| confirmationEmailEnabled | Boolean | | If enabled, send a confirmation email to the respondent after submission |
| confirmationEmailSubject | String | max. 255 ch. | Optional confirmation email subject template (supports placeholders) |
| confirmationEmailBody | String | | Optional confirmation email body template (plain text, supports placeholders) |
| created | unix timestamp | | When the form has been created |
| access | [Access-Object](#access-object) | | Describing access-settings of the form |
| expires | unix-timestamp | | When the form should expire. Timestamp `0` indicates _never_ |
Expand All @@ -46,6 +49,9 @@ This document describes the Object-Structure, that is used within the Forms App
"title": "Form 1",
"description": "Description Text",
"ownerId": "jonas",
"confirmationEmailEnabled": false,
"confirmationEmailSubject": null,
"confirmationEmailBody": null,
"created": 1611240961,
"access": {},
"expires": 0,
Expand Down
1 change: 1 addition & 0 deletions lib/Constants.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ class Constants {
];

public const EXTRA_SETTINGS_SHORT = [
'confirmationEmailRecipient' => ['boolean'],
'validationType' => ['string'],
'validationRegex' => ['string'],
];
Expand Down
22 changes: 22 additions & 0 deletions lib/Db/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,14 @@
* @method int|null getMaxSubmissions()
* @method void setMaxSubmissions(int|null $value)
* @method void setLockedUntil(int|null $value)
* @method int getConfirmationEmailEnabled()
* @method void setConfirmationEmailEnabled(bool $value)
* @method string|null getConfirmationEmailSubject()
* @method void setConfirmationEmailSubject(string|null $value)
* @method string|null getConfirmationEmailBody()
* @method void setConfirmationEmailBody(string|null $value)
* @method int|null getConfirmationEmailRecipient()
* @method void setConfirmationEmailRecipient(int|null $value)
*/
class Form extends Entity {
protected $hash;
Expand All @@ -74,6 +82,10 @@ class Form extends Entity {
protected $lockedBy;
protected $lockedUntil;
protected $maxSubmissions;
protected $confirmationEmailEnabled;
protected $confirmationEmailSubject;
protected $confirmationEmailBody;
protected $confirmationEmailRecipient;

/**
* Form constructor.
Expand All @@ -90,6 +102,8 @@ public function __construct() {
$this->addType('lockedBy', 'string');
$this->addType('lockedUntil', 'integer');
$this->addType('maxSubmissions', 'integer');
$this->addType('confirmationEmailEnabled', 'boolean');
$this->addType('confirmationEmailRecipient', 'integer');
}

// JSON-Decoding of access-column.
Expand Down Expand Up @@ -164,6 +178,10 @@ public function setAccess(array $access): void {
* lockedBy: ?string,
* lockedUntil: ?int,
* maxSubmissions: ?int,
* confirmationEmailEnabled: bool,
* confirmationEmailSubject: ?string,
* confirmationEmailBody: ?string,
* confirmationEmailRecipient: ?int,
* }
*/
public function read() {
Expand All @@ -188,6 +206,10 @@ public function read() {
'lockedBy' => $this->getLockedBy(),
'lockedUntil' => $this->getLockedUntil(),
'maxSubmissions' => $this->getMaxSubmissions(),
'confirmationEmailEnabled' => (bool)$this->getConfirmationEmailEnabled(),
'confirmationEmailSubject' => $this->getConfirmationEmailSubject(),
'confirmationEmailBody' => $this->getConfirmationEmailBody(),
'confirmationEmailRecipient' => $this->getConfirmationEmailRecipient(),
];
}
}
65 changes: 65 additions & 0 deletions lib/Migration/Version050301Date20260413233000.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Forms\Migration;

use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\DB\Types;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;

/**
* Add confirmation email fields to forms
*/
class Version050301Date20260413233000 extends SimpleMigrationStep {

/**
* @param IOutput $output
* @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
* @param array $options
* @return null|ISchemaWrapper
*/
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();
$table = $schema->getTable('forms_v2_forms');

if (!$table->hasColumn('confirmation_email_enabled')) {
$table->addColumn('confirmation_email_enabled', Types::BOOLEAN, [
'notnull' => false,
'default' => 0,
]);
}

if (!$table->hasColumn('confirmation_email_subject')) {
$table->addColumn('confirmation_email_subject', Types::STRING, [
'notnull' => false,
'default' => null,
'length' => 255,
]);
}

if (!$table->hasColumn('confirmation_email_body')) {
$table->addColumn('confirmation_email_body', Types::TEXT, [
'notnull' => false,
'default' => null,
]);
}

if (!$table->hasColumn('confirmation_email_recipient')) {
$table->addColumn('confirmation_email_recipient', Types::INTEGER, [
'notnull' => false,
'default' => null,
]);
}

return $schema;
}
}
8 changes: 6 additions & 2 deletions lib/ResponseDefinitions.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
* dateMax?: int,
* dateMin?: int,
* dateRange?: bool,
* confirmationEmailRecipient?: bool,
* maxAllowedFilesCount?: int,
* maxFileSize?: int,
* optionsHighest?: 2|3|4|5|6|7|8|9|10,
Expand Down Expand Up @@ -141,8 +142,11 @@
* shares: list<FormsShare>,
* submissionCount?: int,
* submissionMessage: ?string,
* }
*
* confirmationEmailEnabled: bool,
* confirmationEmailSubject: ?string,
* confirmationEmailBody: ?string,
* confirmationEmailRecipient: ?int,
* } *
* @psalm-type FormsUploadedFile = array{
* uploadedFileId: int,
* fileName: string
Expand Down
170 changes: 170 additions & 0 deletions lib/Service/FormsService.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

use OCA\Forms\Activity\ActivityManager;
use OCA\Forms\Constants;
use OCA\Forms\Db\AnswerMapper;
use OCA\Forms\Db\Form;
use OCA\Forms\Db\FormMapper;
use OCA\Forms\Db\OptionMapper;
Expand All @@ -34,6 +35,8 @@
use OCP\IUser;
use OCP\IUserManager;
use OCP\IUserSession;
use OCP\Mail\IEmailValidator;
use OCP\Mail\IMailer;
use OCP\Search\ISearchQuery;
use OCP\Security\ISecureRandom;
use OCP\Share\IShare;
Expand Down Expand Up @@ -67,6 +70,9 @@ public function __construct(
private IL10N $l10n,
private LoggerInterface $logger,
private IEventDispatcher $eventDispatcher,
private IMailer $mailer,
private IEmailValidator $emailValidator,
private AnswerMapper $answerMapper,
) {
$this->currentUser = $userSession->getUser();
}
Expand Down Expand Up @@ -739,6 +745,170 @@ public function notifyNewSubmission(Form $form, Submission $submission): void {
}

$this->eventDispatcher->dispatchTyped(new FormSubmittedEvent($form, $submission));

// Send confirmation email if enabled
$this->sendConfirmationEmail($form, $submission);
}

/**
* Send confirmation email to the respondent
*
* @param Form $form The form that was submitted
* @param Submission $submission The submission
*/
private function sendConfirmationEmail(Form $form, Submission $submission): void {
// Check if confirmation email is enabled
if (!$form->getConfirmationEmailEnabled()) {
return;
}

$subject = $form->getConfirmationEmailSubject();
$body = $form->getConfirmationEmailBody();

// If no subject or body is set, use defaults
if (empty($subject)) {
$subject = $this->l10n->t('Thank you for your submission');
}
if (empty($body)) {
$body = $this->l10n->t('Thank you for submitting the form "%s".', [$form->getTitle()]);
}

// Get questions and answers
$questions = $this->getQuestions($form->getId());
$answers = $this->answerMapper->findBySubmission($submission->getId());

$answerMap = [];
foreach ($answers as $answer) {
$questionId = $answer->getQuestionId();
if (!isset($answerMap[$questionId])) {
$answerMap[$questionId] = [];
}
$answerMap[$questionId][] = $answer->getText();
}

$recipientQuestion = $this->getConfirmationEmailRecipientQuestion($questions);
if ($recipientQuestion === null) {
$this->logger->debug('No confirmation email recipient question is available', [
'formId' => $form->getId(),
'submissionId' => $submission->getId(),
]);
return;
}

$recipientQuestionId = $recipientQuestion['id'];
$recipientEmail = $answerMap[$recipientQuestionId][0] ?? null;
if ($recipientEmail === null || !$this->emailValidator->isValid($recipientEmail)) {
$this->logger->debug('No valid email address found in submission for confirmation email', [
'formId' => $form->getId(),
'submissionId' => $submission->getId(),
]);
return;
}

// Replace placeholders in subject and body
$replacements = [
'{formTitle}' => $form->getTitle(),
'{formDescription}' => $form->getDescription() ?? '',
];

// Add field placeholders (e.g., {name}, {email})
foreach ($questions as $question) {
$questionId = $question['id'];
$questionName = $question['name'] ?? '';
$questionText = $question['text'] ?? '';

// Use question name if available, otherwise use text
$fieldKey = !empty($questionName) ? $questionName : $questionText;
// Sanitize field key for placeholder (remove special chars, lowercase)
$fieldKey = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $fieldKey));

if (!empty($answerMap[$questionId])) {
$answerValue = implode('; ', $answerMap[$questionId]);
$replacements['{' . $fieldKey . '}'] = $answerValue;
// Also support {questionName} format
if (!empty($questionName)) {
$replacements['{' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $questionName)) . '}'] = $answerValue;
}
}
}

// Apply replacements
$subject = str_replace(array_keys($replacements), array_values($replacements), $subject);
$body = str_replace(array_keys($replacements), array_values($replacements), $body);

try {
$message = $this->mailer->createMessage();
$message->setSubject($subject);
$message->setPlainBody($body);
$message->setTo([$recipientEmail]);

$this->mailer->send($message);
$this->logger->debug('Confirmation email sent successfully', [
'formId' => $form->getId(),
'submissionId' => $submission->getId(),
'recipient' => $recipientEmail,
]);
} catch (\Exception $e) {
// Handle exceptions silently, as this is not critical.
// We don't want to break the submission process just because of an email error.
$this->logger->error(
'Error while sending confirmation email',
[
'exception' => $e,
'formId' => $form->getId(),
'submissionId' => $submission->getId(),
]
);
}
}

/**
* @param list<FormsQuestion> $questions
* @return FormsQuestion|null
*/
private function getConfirmationEmailRecipientQuestion(array $questions): ?array {
$emailQuestions = array_values(array_filter(
$questions,
fn (array $question): bool => $this->isConfirmationEmailQuestion($question),
));

if ($emailQuestions === []) {
return null;
}

$explicitRecipients = array_values(array_filter(
$emailQuestions,
function (array $question): bool {
$extraSettings = (array)($question['extraSettings'] ?? []);
return !empty($extraSettings['confirmationEmailRecipient']);
},
));

if (count($explicitRecipients) === 1) {
return $explicitRecipients[0];
}

if (count($explicitRecipients) > 1) {
return null;
}

if (count($emailQuestions) === 1) {
return $emailQuestions[0];
}

return null;
}

/**
* @param FormsQuestion $question
*/
private function isConfirmationEmailQuestion(array $question): bool {
if (($question['type'] ?? null) !== Constants::ANSWER_TYPE_SHORT) {
return false;
}

$extraSettings = (array)($question['extraSettings'] ?? []);
return ($extraSettings['validationType'] ?? null) === 'email';
}

/**
Expand Down
Loading