Skip to content

Beautiful Open-Source Form Builder

5.4 KB
Raw Blame
<?php

namespace App\Integrations\Handlers;

use App\Models\Forms\Form;
use App\Models\Integration\FormIntegration;
use Illuminate\Support\Facades\Log;
use App\Open\MentionParser;
use App\Service\Billing\Feature;
use App\Service\Forms\FormSubmissionFormatter;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Auth;

class EmailIntegration extends AbstractIntegrationHandler
{
    use TracksEmailIntegration;

    public const RISKY_USERS_LIMIT = 120;
    public const MAX_PDF_ATTACHMENTS = 3;

    public static function getValidationRules(?Form $form): array
    {
        $rules = [
            'send_to' => ['required'],
            'sender_name' => 'required',
            'sender_email' => 'email|nullable',
            'subject' => 'required',
            'email_content' => 'required',
            'include_submission_data' => 'boolean',
            'include_hidden_fields_submission_data' => ['nullable', 'boolean'],
            'embed_uploaded_images' => ['nullable', 'boolean'],
            'reply_to' => 'nullable',
            'link_edit_submission' => ['nullable', 'boolean'],
            'logo_url' => ['nullable', 'url', 'starts_with:https://'],
            'font_family' => ['nullable', 'string', 'max:255'],
            'font_color' => ['nullable', 'string', 'regex:/^#[0-9A-Fa-f]{6}$/'],
            'outer_background_color' => ['nullable', 'string', 'regex:/^#[0-9A-Fa-f]{6}$/'],
            'inner_background_color' => ['nullable', 'string', 'regex:/^#[0-9A-Fa-f]{6}$/'],
            'pdf_template_ids' => ['nullable', 'array', 'max:' . self::MAX_PDF_ATTACHMENTS],
            'pdf_template_ids.*' => ['integer', Rule::exists('pdf_templates', 'id')->where('form_id', $form->id)],
        ];

        if ($form->workspace?->hasFeature(Feature::EMAIL_ADVANCED) || config('app.self_hosted')) {
            return $rules;
        }

        // Free plan users can only send to a single email address (avoid spam)
        $rules['send_to'][] = function ($attribute, $value, $fail) use ($form) {
            if (count(explode("\n", trim($value))) > 1 || count(explode(',', $value)) > 1) {
                $fail('You can only send to a single email address on the free plan. Please upgrade to the Pro plan to create a new integration.');
            }
        };

        // Free plan users can only send to their own email address
        $rules['send_to'][] = function ($attribute, $value, $fail) {
            $currentUser = Auth::user();
            $userEmail = $currentUser->email;
            $sendToEmail = trim($value);

            if ($sendToEmail !== $userEmail) {
                $fail("You can only send email notification to your own email address ({$userEmail}). Please upgrade to the Pro plan to send to other email addresses.");
            }
        };

        // Free plan users can only have a single email integration per form (avoid spam)
        if (!request()->route('integrationid')) {
            $existingEmailIntegrations = FormIntegration::where('form_id', $form->id)
                ->where('integration_id', 'email')
                ->count();
            if ($existingEmailIntegrations > 0) {
                throw ValidationException::withMessages([
                    'data.send_to' => ['Free users are limited to 1 email integration per form.']
                ]);
            }
        }

        return $rules;
    }

    protected function shouldRun(): bool
    {
        return $this->integrationData?->send_to && parent::shouldRun();
    }

    // To avoid phishing abuse we limit this feature for risky users
    private function riskLimitReached(): bool
    {
        // This is a per-workspace limit for risky workspaces
        if ($this->form->workspace->is_risky) {
            if ($this->form->workspace->submissions_count >= self::RISKY_USERS_LIMIT) {
                Log::channel('slack_alerts')->error('🚨 Dangerous new user detected! Attempting many email sending.', [
                    'form_id' => $this->form->id,
                    'workspace_id' => $this->form->workspace->id,
                ]);

                return true;
            }
        }

        return false;
    }

    public function handle(): void
    {
        if (!$this->emailTrackingId) {
            $this->run();
            return;
        }
        if (!$this->shouldRun()) {
            $this->emailSkipped('No email sent: integration conditions were not met or recipients were not configured.');
            return;
        }

        if ($this->riskLimitReached()) {
            app(\App\Service\Integrations\EmailDeliveryTracker::class)->outcome(
                $this->emailTrackingId,
                'error',
                'Email sending is blocked by account restrictions. Contact support to review the account.'
            );
            return;
        }

        if ($this->form->workspace?->hasFeature(Feature::EMAIL_ADVANCED)) {
            $formatter = (new FormSubmissionFormatter($this->form, $this->submissionData))->outputStringsOnly()->showHiddenFields();
            $parser = new MentionParser(
                $this->integrationData?->send_to,
                $formatter->getFieldsWithValue(),
                $this->getComputedValues()
            );
            $sendTo = $parser->parseAsText();
        } else {
            $sendTo = $this->integrationData?->send_to;
        }

        $this->sendTrackedEmails(preg_split("/\r\n|\n|\r/", $sendTo));
    }
}