Skip to content
Open
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
16 changes: 16 additions & 0 deletions lib/Db/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@
* @method void setLockedBy(string|null $value)
* @method int getLockedUntil()
* @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)
*/
class Form extends Entity {
protected $hash;
Expand All @@ -71,6 +77,9 @@ class Form extends Entity {
protected $state;
protected $lockedBy;
protected $lockedUntil;
protected $confirmationEmailEnabled;
protected $confirmationEmailSubject;
protected $confirmationEmailBody;

/**
* Form constructor.
Expand All @@ -86,6 +95,7 @@ public function __construct() {
$this->addType('state', 'integer');
$this->addType('lockedBy', 'string');
$this->addType('lockedUntil', 'integer');
$this->addType('confirmationEmailEnabled', 'boolean');
}

// JSON-Decoding of access-column.
Expand Down Expand Up @@ -159,6 +169,9 @@ public function setAccess(array $access): void {
* state: 0|1|2,
* lockedBy: ?string,
* lockedUntil: ?int,
* confirmationEmailEnabled: bool,
* confirmationEmailSubject: ?string,
* confirmationEmailBody: ?string,
* }
*/
public function read() {
Expand All @@ -182,6 +195,9 @@ public function read() {
'state' => $this->getState(),
'lockedBy' => $this->getLockedBy(),
'lockedUntil' => $this->getLockedUntil(),
'confirmationEmailEnabled' => (bool)$this->getConfirmationEmailEnabled(),
'confirmationEmailSubject' => $this->getConfirmationEmailSubject(),
'confirmationEmailBody' => $this->getConfirmationEmailBody(),
];
}
}
58 changes: 58 additions & 0 deletions lib/Migration/Version050202Date20251217203121.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?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 Version050202Date20251217203121 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,
]);
}

return $schema;
}
}
3 changes: 3 additions & 0 deletions lib/ResponseDefinitions.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@
* shares: list<FormsShare>,
* submissionCount?: int,
* submissionMessage: ?string,
* confirmationEmailEnabled: bool,
* confirmationEmailSubject: ?string,
* confirmationEmailBody: ?string,
* }
*
* @psalm-type FormsUploadedFile = array{
Expand Down
149 changes: 149 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,7 @@
use OCP\IUser;
use OCP\IUserManager;
use OCP\IUserSession;
use OCP\Mail\IMailer;
use OCP\Search\ISearchQuery;
use OCP\Security\ISecureRandom;
use OCP\Share\IShare;
Expand Down Expand Up @@ -67,6 +69,8 @@ public function __construct(
private IL10N $l10n,
private LoggerInterface $logger,
private IEventDispatcher $eventDispatcher,
private IMailer $mailer,
private AnswerMapper $answerMapper,
) {
$this->currentUser = $userSession->getUser();
}
Expand Down Expand Up @@ -737,6 +741,151 @@ 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());

// Build a map of question IDs to questions and answers
$questionMap = [];
foreach ($questions as $question) {
$questionMap[$question['id']] = $question;
}

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

// Find email address from answers
$recipientEmail = null;
foreach ($questions as $question) {
if ($question['type'] !== Constants::ANSWER_TYPE_SHORT) {
continue;
}

$extraSettings = (array)($question['extraSettings'] ?? []);
$validationType = $extraSettings['validationType'] ?? null;
if ($validationType !== 'email') {
continue;
}

$questionId = $question['id'];
if (empty($answerMap[$questionId])) {
continue;
}

$emailValue = $answerMap[$questionId][0];
if ($this->mailer->validateMailAddress($emailValue)) {
$recipientEmail = $emailValue;
break;
}
}

// If no email found, cannot send confirmation
if (empty($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]);

// Set from address to form owner or system default
$owner = $this->userManager->get($form->getOwnerId());
if ($owner instanceof IUser) {
$ownerEmail = $owner->getEMailAddress();
if (!empty($ownerEmail)) {
$message->setFrom([$ownerEmail => $owner->getDisplayName()]);
}
}

$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(),
]
);
}
}

/**
Expand Down
16 changes: 15 additions & 1 deletion openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,10 @@
"lockedBy",
"lockedUntil",
"shares",
"submissionMessage"
"submissionMessage",
"confirmationEmailEnabled",
"confirmationEmailSubject",
"confirmationEmailBody"
],
"properties": {
"id": {
Expand Down Expand Up @@ -222,6 +225,17 @@
"submissionMessage": {
"type": "string",
"nullable": true
},
"confirmationEmailEnabled": {
"type": "boolean"
},
"confirmationEmailSubject": {
"type": "string",
"nullable": true
},
"confirmationEmailBody": {
"type": "string",
"nullable": true
}
}
},
Expand Down
Loading
Loading