Skip to content

Beautiful Open-Source Form Builder

19.4 KB
Raw Blame
<?php

namespace App\Notifications\Forms;

use App\Events\Forms\FormSubmitted;
use App\Models\Forms\FormSubmission;
use App\Models\PdfTemplate;
use App\Open\MentionParser;
use App\Service\Branding\BrandingPolicy;
use App\Service\Billing\Feature;
use App\Service\Forms\FormSubmissionFormatter;
use App\Service\Forms\SubmissionUrlService;
use App\Service\Formulas\ComputedVariableEvaluator;
use App\Service\Pdf\PdfCacheService;
use App\Service\Pdf\PdfGeneratorService;
use App\Service\Storage\FileUploadPathService;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Part\DataPart;

class FormEmailNotification extends Notification
{
    private const MAX_PDF_ATTACHMENTS = 3;
    private const MAX_TOTAL_ATTACHMENT_BYTES = 15 * 1024 * 1024;
    private const MAX_INLINE_IMAGE_BYTES = 6 * 1024 * 1024;
    private const INLINE_IMAGE_MIME_TYPES = [
        'image/gif',
        'image/jpeg',
        'image/png',
    ];

    public FormSubmitted $event;
    public ?string $emailTransport = null;
    public ?array $emailTracking = null;
    private ?array $computedValues = null;
    private array $inlineImages = [];
    private int $inlineImageBytes = 0;
    private int $pdfAttachmentBytes = 0;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(FormSubmitted $event, private $integrationData)
    {
        $this->event = $event;
    }

    /**
     * Get computed variable values for this submission
     */
    private function getComputedValues(): array
    {
        if ($this->computedValues === null) {
            $this->computedValues = ComputedVariableEvaluator::evaluateForSubmission(
                $this->event->form,
                $this->event->data
            );
        }
        return $this->computedValues;
    }

    private function getMailer(): string
    {
        $workspace = $this->event->form->workspace;
        $emailSettings = $workspace->settings['email_settings'] ?? [];

        if (
            $workspace->hasFeature(Feature::CUSTOM_SMTP)
            && $emailSettings
            && !empty($emailSettings['host'])
            && !empty($emailSettings['port'])
            && !empty($emailSettings['username'])
            && !empty($emailSettings['password'])
        ) {
            config([
                'mail.mailers.custom_smtp.host' => $emailSettings['host'],
                'mail.mailers.custom_smtp.port' => $emailSettings['port'],
                'mail.mailers.custom_smtp.encryption' => array_key_exists('encryption', $emailSettings) ? $emailSettings['encryption'] : 'tls',
                'mail.mailers.custom_smtp.username' => $emailSettings['username'],
                'mail.mailers.custom_smtp.password' => $emailSettings['password']
            ]);

            // Laravel caches mailer instances (and their transport) in long-lived processes
            // like queue workers (Horizon). If workspace SMTP settings change, we must purge
            // the cached mailer so the next send uses the updated config.
            Mail::purge('custom_smtp');
            return 'custom_smtp';
        }

        return config('mail.default');
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param mixed $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param mixed $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        $mail = (new MailMessage())
            ->mailer($mailer = $this->getMailer())
            ->withSymfonyMessage(function ($message) use ($mailer) {
                $this->emailTransport = config("mail.mailers.$mailer.transport", $mailer);
                if ($this->emailTracking) {
                    $message->getHeaders()->addTextHeader('X-Form-Email-Event-ID', $this->emailTracking['event']);
                    $message->getHeaders()->addTextHeader('X-Form-Email-Recipient-ID', $this->emailTracking['recipient']);
                }
            })
            ->replyTo($this->getReplyToEmail($this->event->form->creator->email))
            ->from($this->getFromEmail(), $this->getSenderName())
            ->subject($this->getSubject());

        // Explicitly selected PDF attachments take priority over optional inline images.
        $this->attachPdfTemplatesIfRequested($mail);

        return $mail
            ->withSymfonyMessage(function (Email $message) {
                $this->addCustomHeaders($message);
                $this->addInlineImages($message);
            })
            ->markdown('mail.form.email-notification', $this->getMailData());
    }

    /**
     * Attach PDFs for selected templates when integration has pdf_template_ids.
     */
    private function attachPdfTemplatesIfRequested(MailMessage $mail): void
    {
        $this->pdfAttachmentBytes = 0;
        $form = $this->event->form;

        $templateIds = $this->integrationData->pdf_template_ids ?? [];
        if (! is_array($templateIds) || count($templateIds) === 0) {
            return;
        }
        $templateIds = array_values(array_unique(array_slice($templateIds, 0, self::MAX_PDF_ATTACHMENTS)));

        $submissionId = $this->event->data['submission_id'] ?? null;
        if (! $submissionId) {
            return;
        }

        $submission = FormSubmission::where('form_id', $form->id)->where('id', $submissionId)->first();
        if (! $submission) {
            return;
        }

        $cacheService = app(PdfCacheService::class);
        $generator = app(PdfGeneratorService::class);
        $totalBytes = 0;

        foreach ($templateIds as $templateId) {
            $template = PdfTemplate::where('form_id', $form->id)->find($templateId);
            if (! $template) {
                continue;
            }
            try {
                $pdfPath = $cacheService->getOrGenerateFromTemplate($form, $submission, $template, $generator);
                $content = Storage::get($pdfPath);
                if ($content !== false) {
                    $nextSize = strlen($content);
                    if (($totalBytes + $nextSize) > self::MAX_TOTAL_ATTACHMENT_BYTES) {
                        logger()->warning('Skipping PDF email attachment: total size limit exceeded', [
                            'form_id' => $form->id,
                            'submission_id' => $submission->id,
                            'template_id' => $template->id,
                            'limit_bytes' => self::MAX_TOTAL_ATTACHMENT_BYTES,
                        ]);
                        continue;
                    }

                    $filename = $template->resolveFilename($form, $submission);
                    $mail->attachData($content, $filename, ['mime' => 'application/pdf']);
                    $totalBytes += $nextSize;
                    $this->pdfAttachmentBytes += $nextSize;
                }
            } catch (\Throwable $e) {
                report($e);
            }
        }
    }

    private function formatSubmissionData(bool $createLinks = true, bool $forMentionParsing = false): array
    {
        $formatter = (new FormSubmissionFormatter($this->event->form, $this->event->data))
            ->outputStringsOnly()
            ->useSignedUrlForFiles();

        if ($createLinks) {
            $formatter->createLinks();
        }
        if ($forMentionParsing || ($this->integrationData->include_hidden_fields_submission_data ?? false)) {
            $formatter->showHiddenFields();
        }

        return $formatter->getFieldsWithValue();
    }

    private function getFromEmail(): string
    {
        $workspace = $this->event->form->workspace;
        $emailSettings = $workspace->settings['email_settings'] ?? [];

        if (
            $workspace->hasFeature(Feature::CUSTOM_SMTP)
            && $emailSettings
            && !empty($emailSettings['sender_address'])
        ) {
            return $emailSettings['sender_address'];
        }

        if (
            config('app.self_hosted')
            && isset($this->integrationData->sender_email)
            && $this->validateEmail($this->integrationData->sender_email)
        ) {
            return $this->integrationData->sender_email;
        }

        $baseEmail = config('mail.from.address');
        if (!config('app.self_hosted')) {
            // Insert timestamp before the @ to prevent email grouping
            $parts = explode('@', $baseEmail);
            return $parts[0] . '+' . time() . '@' . $parts[1];
        }

        return $baseEmail;
    }

    private function getSenderName(): string
    {
        $parser = new MentionParser(
            $this->integrationData->sender_name ?? config('app.name'),
            $this->formatSubmissionData(false, true),
            $this->getComputedValues()
        );
        return $parser->parseAsText();
    }

    private function getReplyToEmail($default): string
    {
        $replyTo = $this->integrationData->reply_to ?? null;
        if ($replyTo) {
            $parsedReplyTo = $this->parseReplyTo($replyTo);
            if ($parsedReplyTo && $this->validateEmail($parsedReplyTo)) {
                return $parsedReplyTo;
            }
        }
        return $default;
    }

    private function parseReplyTo(string $replyTo): ?string
    {
        $parser = new MentionParser($replyTo, $this->formatSubmissionData(false, true), $this->getComputedValues());
        return $parser->parseAsText();
    }

    private function getSubject(): string
    {
        $defaultSubject = 'New form submission';
        $parser = new MentionParser(
            $this->integrationData->subject ?? $defaultSubject,
            $this->formatSubmissionData(false, true),
            $this->getComputedValues()
        );
        return $parser->parseAsText();
    }

    private function addCustomHeaders(Email $message): void
    {
        $formId = $this->event->form->id;
        $submissionId = $this->event->data['submission_id'] ?? 'unknown';
        $hashedSubmissionId = md5($submissionId);
        $domain = Str::after(config('app.url'), '://');

        // Create a unique Message-ID for each submission (without timestamp)
        $messageId = "<form-{$formId}-submission-{$hashedSubmissionId}@{$domain}>";

        // Add our custom Message-ID as X-Custom-Message-ID
        $message->getHeaders()->addTextHeader('X-Custom-Message-ID', $messageId);

        // Add X-Entity-Ref-ID header for Google+ notifications
        $message->getHeaders()->addTextHeader('X-Entity-Ref-ID', $messageId);

        // Add References header with the same value as Message-ID
        // This ensures emails are only threaded by submission ID, not by form ID
        $message->getHeaders()->addTextHeader('References', $messageId);

        // Add a unique Thread-Index to further prevent grouping
        $threadIndex = base64_encode(pack('H*', md5($formId . $submissionId)));
        $message->getHeaders()->addTextHeader('Thread-Index', $threadIndex);
    }

    private function getMailData(): array
    {
        $form = $this->event->form;
        $hasAdvancedEmailCustomization = $form->workspace?->hasFeature(Feature::EMAIL_ADVANCED) ?? false;
        $fields = $this->prepareInlineImages($this->formatSubmissionData());

        $emailAppearance = $hasAdvancedEmailCustomization ? [
            'logoUrl' => $this->integrationData->logo_url ?? null,
            'fontFamily' => $this->integrationData->font_family ?? null,
            'fontColor' => $this->integrationData->font_color ?? null,
            'outerBackgroundColor' => $this->integrationData->outer_background_color ?? null,
            'innerBackgroundColor' => $this->integrationData->inner_background_color ?? null,
        ] : [];

        return [
            'emailContent' => $this->getEmailContent(),
            'fields' => $fields,
            'form' => $form,
            'integrationData' => $this->integrationData,
            'noBranding' => app(BrandingPolicy::class)->canRemoveFormBranding($form),
            'submission_id' => $this->getEncodedSubmissionId(),
            'emailAppearance' => $emailAppearance,
        ];
    }

    private function prepareInlineImages(array $fields): array
    {
        $this->inlineImages = [];
        $this->inlineImageBytes = 0;

        if (
            !($this->integrationData->include_submission_data ?? false)
            || !($this->integrationData->embed_uploaded_images ?? false)
        ) {
            return $fields;
        }

        foreach ($fields as &$field) {
            if (empty($field['email_data']) || !is_array($field['email_data'])) {
                continue;
            }

            foreach ($field['email_data'] as &$file) {
                $inlineImage = $this->prepareInlineImage($file);
                if ($inlineImage) {
                    $file['inline_cid'] = $inlineImage['cid'];
                }
            }
            unset($file);
        }
        unset($field);

        return $fields;
    }

    private function prepareInlineImage(array $file): ?array
    {
        if (!($file['is_image'] ?? false) || empty($file['file_name'])) {
            return null;
        }

        try {
            $path = FileUploadPathService::getFileUploadPath(
                $this->event->form->id,
                $file['file_name']
            );

            if (!Storage::exists($path)) {
                return null;
            }

            $cid = hash('sha256', $this->event->form->id . '|' . $file['file_name']) . '@opnform';
            if (isset($this->inlineImages[$cid])) {
                return $this->inlineImages[$cid];
            }

            $size = Storage::size($path);
            if (
                $size <= 0
                || $size > self::MAX_INLINE_IMAGE_BYTES
                || ($this->pdfAttachmentBytes + $this->inlineImageBytes + $size) > self::MAX_TOTAL_ATTACHMENT_BYTES
            ) {
                return null;
            }

            $contents = Storage::get($path);
            $actualSize = strlen($contents);
            if (
                $actualSize <= 0
                || $actualSize > self::MAX_INLINE_IMAGE_BYTES
                || ($this->pdfAttachmentBytes + $this->inlineImageBytes + $actualSize) > self::MAX_TOTAL_ATTACHMENT_BYTES
            ) {
                return null;
            }

            $mimeType = (new \finfo(FILEINFO_MIME_TYPE))->buffer($contents);
            if (!is_string($mimeType) || !in_array(strtolower($mimeType), self::INLINE_IMAGE_MIME_TYPES, true)) {
                return null;
            }

            $this->inlineImages[$cid] = [
                'cid' => $cid,
                'contents' => $contents,
                'file_name' => $file['label'] ?? $file['file_name'],
                'mime_type' => strtolower($mimeType),
            ];
            $this->inlineImageBytes += $actualSize;

            return $this->inlineImages[$cid];
        } catch (\Throwable $exception) {
            report($exception);

            return null;
        }
    }

    private function addInlineImages(Email $message): void
    {
        foreach ($this->inlineImages as $image) {
            $message->addPart(
                (new DataPart($image['contents'], $image['file_name'], $image['mime_type']))
                    ->asInline()
                    ->setContentId($image['cid'])
            );
        }
    }

    private function getEmailContent(): string
    {
        $parser = new MentionParser(
            $this->integrationData->email_content ?? '',
            $this->formatSubmissionData(true, true),
            $this->getComputedValues()
        );
        $html = $parser->parse();

        return $this->convertResizeAlignmentToInlineStyles($html);
    }

    /**
     * Convert quill-resize-module CSS classes to inline styles for email client compatibility.
     * Email clients often strip class-based styles; inline styles are required.
     */
    private function convertResizeAlignmentToInlineStyles(string $html): string
    {
        $alignments = [
            'ql-resize-style-left' => 'float:left; margin:0 1em 1em 0;',
            'ql-resize-style-right' => 'float:right; margin:0 0 1em 1em;',
            'ql-resize-style-center' => 'display:block; margin:auto; text-align:center;',
            'ql-resize-style-full' => 'width:100% !important;',
        ];

        // Match tags once, consuming large quoted attributes without backtracking.
        return preg_replace_callback(
            '/<([a-z]+)\b((?:[^>"\']++|"[^"]*+"|\'[^\']*+\')*+)>/i',
            function ($match) use ($alignments) {
                $attributes = $match[2];
                preg_match_all(
                    '/\s+([a-z_:][a-z0-9_.:-]*)\s*=\s*(?:"([^"]*+)"|\'([^\']*+)\'|([^\s>]+))/i',
                    $attributes,
                    $attributeMatches,
                    PREG_SET_ORDER | PREG_OFFSET_CAPTURE | PREG_UNMATCHED_AS_NULL
                );
                $parsedAttributes = [];
                foreach ($attributeMatches as $attribute) {
                    $parsedAttributes[strtolower($attribute[1][0])] ??= [
                        'value' => $attribute[2][0] ?? $attribute[3][0] ?? $attribute[4][0],
                        'offset' => $attribute[0][1],
                        'length' => strlen($attribute[0][0]),
                    ];
                }
                $classAttribute = $parsedAttributes['class'] ?? null;
                if (!$classAttribute) {
                    return $match[0];
                }

                $classes = preg_split('/\s+/', trim($classAttribute['value']));
                $style = '';
                foreach ($alignments as $class => $inlineStyle) {
                    if (in_array($class, $classes, true)) {
                        $classes = array_values(array_diff($classes, [$class]));
                        $style = $inlineStyle . $style;
                    }
                }

                if ($style === '') {
                    return $match[0];
                }

                $replacements = [[
                    'offset' => $classAttribute['offset'],
                    'length' => $classAttribute['length'],
                    'value' => $classes ? ' class="' . e(implode(' ', $classes), false) . '"' : '',
                ]];
                if ($styleAttribute = $parsedAttributes['style'] ?? null) {
                    $style .= $styleAttribute['value'];
                    $replacements[] = [...$styleAttribute, 'value' => ''];
                }

                usort($replacements, fn ($left, $right) => $right['offset'] <=> $left['offset']);
                foreach ($replacements as $replacement) {
                    $attributes = substr_replace($attributes, $replacement['value'], $replacement['offset'], $replacement['length']);
                }

                return '<' . $match[1] . $attributes . ' style="' . e($style, false) . '">';
            },
            $html
        ) ?? $html;
    }

    private function getEncodedSubmissionId(): ?string
    {
        $submissionId = $this->event->data['submission_id'] ?? null;
        if (!$submissionId) {
            return null;
        }

        return SubmissionUrlService::getSubmissionIdentifierById($this->event->form, $submissionId);
    }

    public static function validateEmail($email): bool
    {
        return (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
    }
}