-
Notifications
You must be signed in to change notification settings - Fork 112
feat: Add confirmation email for form respondents #3098
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dtretyakov
wants to merge
1
commit into
nextcloud:main
Choose a base branch
from
dtretyakov:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,203
−9
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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; | ||
|
|
@@ -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; | ||
|
|
@@ -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(); | ||
| } | ||
|
|
@@ -735,6 +739,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 | ||
| $recipientEmails = []; | ||
| 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)) { | ||
| $recipientEmails[] = $emailValue; | ||
| } | ||
| } | ||
|
|
||
| // If no email found, cannot send confirmation | ||
| if (empty($recipientEmails)) { | ||
| $this->logger->debug('No valid email address found in submission for confirmation email', [ | ||
| 'formId' => $form->getId(), | ||
| 'submissionId' => $submission->getId(), | ||
| ]); | ||
| return; | ||
| } | ||
|
|
||
| if (count($recipientEmails) > 1) { | ||
| $this->logger->debug('Multiple email fields found in submission for confirmation email, using first match', [ | ||
| 'formId' => $form->getId(), | ||
| 'submissionId' => $submission->getId(), | ||
| 'emailCount' => count($recipientEmails), | ||
| ]); | ||
| } | ||
|
Comment on lines
+813
to
+828
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I am not sure if this is the best way to configure the mail. Maybe we can set a flag on such a question? So the form creator can configure which field to use? |
||
|
|
||
| $recipientEmail = $recipientEmails[0]; | ||
|
|
||
| // 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(), | ||
| ] | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should rather use
\OCP\Mail\IEmailValidatorfor validation