Separated laravel app to its own folder (#540)

This commit is contained in:
Julien Nahum
2024-08-26 18:24:56 +02:00
committed by GitHub
parent 39b8df5eed
commit 5bd1dda504
546 changed files with 124 additions and 143 deletions

View File

@@ -0,0 +1,167 @@
<?php
namespace App\Integrations\Handlers;
use App\Models\Integration\FormIntegration;
use App\Events\Forms\FormSubmitted;
use App\Models\Forms\Form;
use App\Models\Integration\FormIntegrationsEvent;
use App\Service\Forms\FormSubmissionFormatter;
use App\Service\Forms\FormLogicConditionChecker;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Vinkla\Hashids\Facades\Hashids;
abstract class AbstractIntegrationHandler
{
protected $form = null;
protected $submissionData = null;
protected $integrationData = null;
public function __construct(
protected FormSubmitted $event,
protected FormIntegration $formIntegration,
protected array $integration
) {
$this->form = $event->form;
$this->submissionData = $event->data;
$this->integrationData = $formIntegration->data;
}
protected function getProviderName(): string
{
return $this->integration['name'] ?? '';
}
protected function logicConditionsMet(): bool
{
if (!$this->formIntegration->logic || empty((array) $this->formIntegration->logic)) {
return true;
}
return FormLogicConditionChecker::conditionsMet(
json_decode(json_encode($this->formIntegration->logic), true),
$this->submissionData
);
}
protected function shouldRun(): bool
{
return $this->logicConditionsMet();
}
protected function getWebhookUrl(): ?string
{
return '';
}
/**
* Default webhook payload. Can be changed in child classes.
*/
protected function getWebhookData(): array
{
return self::formatWebhookData($this->form, $this->submissionData);
}
final public function run(): void
{
try {
$this->handle();
$this->formIntegration->events()->create([
'status' => FormIntegrationsEvent::STATUS_SUCCESS,
]);
} catch (\Exception $e) {
$this->formIntegration->events()->create([
'status' => FormIntegrationsEvent::STATUS_ERROR,
'data' => $this->extractEventDataFromException($e),
]);
}
}
public function created(): void
{
//
}
/**
* Default handle. Can be changed in child classes.
*/
public function handle(): void
{
if (!$this->shouldRun()) {
return;
}
Http::throw()->post($this->getWebhookUrl(), $this->getWebhookData());
}
abstract public static function getValidationRules(): array;
public static function isOAuthRequired(): bool
{
return false;
}
public static function getValidationAttributes(): array
{
return [];
}
public static function formatWebhookData(Form $form, array $submissionData): array
{
$formatter = (new FormSubmissionFormatter($form, $submissionData))
->useSignedUrlForFiles()
->showHiddenFields();
// Old format - kept for retro-compatibility
$oldFormatData = [];
foreach ($formatter->getFieldsWithValue() as $field) {
$oldFormatData[$field['name']] = $field['value'];
}
// New format using ID
$formattedData = [];
foreach ($formatter->getFieldsWithValue() as $field) {
$formattedData[$field['id']] = [
'value' => $field['value'],
'name' => $field['name'],
];
}
$data = [
'form_title' => $form->title,
'form_slug' => $form->slug,
'submission' => $oldFormatData,
'data' => $formattedData,
'message' => 'Please do not use the `submission` field. It is deprecated and will be removed in the future.'
];
if ($form->is_pro && $form->editable_submissions) {
$data['edit_link'] = $form->share_url . '?submission_id=' . Hashids::encode(
$submissionData['submission_id']
);
}
return $data;
}
public function extractEventDataFromException(\Exception $e): array
{
if ($e instanceof RequestException) {
return [
'message' => $e->getMessage(),
'response' => $e->response->json(),
'status' => $e->response->status(),
];
}
return [
'message' => $e->getMessage()
];
}
/**
* Used in FormIntegrationRequest to format integration
*/
public static function formatData(array $data): array
{
return $data;
}
}

View File

@@ -0,0 +1,91 @@
<?php
namespace App\Integrations\Handlers;
use App\Service\Forms\FormSubmissionFormatter;
use Illuminate\Support\Arr;
use Vinkla\Hashids\Facades\Hashids;
class DiscordIntegration extends AbstractIntegrationHandler
{
public static function getValidationRules(): array
{
return [
'discord_webhook_url' => 'required|url|starts_with:https://discord.com/api/webhooks',
'include_submission_data' => 'boolean',
'link_open_form' => 'boolean',
'link_edit_form' => 'boolean',
'views_submissions_count' => 'boolean',
'link_edit_submission' => 'boolean'
];
}
protected function getWebhookUrl(): ?string
{
return $this->integrationData->discord_webhook_url;
}
protected function shouldRun(): bool
{
return !is_null($this->getWebhookUrl()) && $this->form->is_pro && parent::shouldRun();
}
protected function getWebhookData(): array
{
$settings = (array) $this->integrationData ?? [];
$externalLinks = [];
if (Arr::get($settings, 'link_open_form', true)) {
$externalLinks[] = '[**🔗 Open Form**](' . $this->form->share_url . ')';
}
if (Arr::get($settings, 'link_edit_form', true)) {
$editFormURL = front_url('forms/' . $this->form->slug . '/show');
$externalLinks[] = '[**✍️ Edit Form**](' . $editFormURL . ')';
}
if (Arr::get($settings, 'link_edit_submission', true) && $this->form->editable_submissions) {
$submissionId = Hashids::encode($this->submissionData['submission_id']);
$externalLinks[] = '[**✍️ ' . $this->form->editable_submissions_button_text . '**](' . $this->form->share_url . '?submission_id=' . $submissionId . ')';
}
$color = hexdec(str_replace('#', '', $this->form->color));
$blocks = [];
if (Arr::get($settings, 'include_submission_data', true)) {
$submissionString = '';
$formatter = (new FormSubmissionFormatter($this->form, $this->submissionData))->outputStringsOnly();
foreach ($formatter->getFieldsWithValue() as $field) {
$tmpVal = is_array($field['value']) ? implode(',', $field['value']) : $field['value'];
$submissionString .= '**' . ucfirst($field['name']) . '**: ' . $tmpVal . "\n";
}
$blocks[] = [
'type' => 'rich',
'color' => $color,
'description' => $submissionString,
];
}
if (Arr::get($settings, 'views_submissions_count', true)) {
$countString = '**👀 Views**: ' . (string) $this->form->views_count . " \n";
$countString .= '**🖊️ Submissions**: ' . (string) $this->form->submissions_count;
$blocks[] = [
'type' => 'rich',
'color' => $color,
'description' => $countString,
];
}
if (count($externalLinks) > 0) {
$blocks[] = [
'type' => 'rich',
'color' => $color,
'description' => implode(' - ', $externalLinks),
];
}
return [
'content' => 'New submission for your form **' . $this->form->title . '**',
'tts' => false,
'username' => config('app.name'),
'avatar_url' => asset('img/logo.png'),
'embeds' => $blocks,
];
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace App\Integrations\Handlers;
use App\Rules\OneEmailPerLine;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Notification;
use App\Notifications\Forms\FormSubmissionNotification;
class EmailIntegration extends AbstractIntegrationHandler
{
public static function getValidationRules(): array
{
return [
'notification_emails' => ['required', new OneEmailPerLine()],
'notification_reply_to' => 'email|nullable',
];
}
protected function shouldRun(): bool
{
return $this->integrationData->notification_emails && parent::shouldRun();
}
public function handle(): void
{
if (!$this->shouldRun()) {
return;
}
$subscribers = collect(preg_split("/\r\n|\n|\r/", $this->integrationData->notification_emails))
->filter(function ($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
});
Log::debug('Sending email notification', [
'recipients' => $subscribers->toArray(),
'form_id' => $this->form->id,
'form_slug' => $this->form->slug,
]);
$subscribers->each(function ($subscriber) {
Notification::route('mail', $subscriber)->notify(
new FormSubmissionNotification($this->event, $this->integrationData)
);
});
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace App\Integrations\Handlers\Events;
use App\Models\Integration\FormIntegration;
class AbstractIntegrationCreated
{
public function __construct(
protected FormIntegration $formIntegration
) {
}
public function handle(): void
{
//
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace App\Integrations\Handlers\Events;
use App\Integrations\Google\Google;
use App\Models\Integration\FormIntegration;
class GoogleSheetsIntegrationCreated extends AbstractIntegrationCreated
{
protected Google $client;
public function __construct(
protected FormIntegration $formIntegration
) {
parent::__construct($formIntegration);
$this->client = new Google($formIntegration);
}
public function handle(): void
{
$this->client->sheets()
->create($this->formIntegration->form);
}
}

View File

@@ -0,0 +1,72 @@
<?php
namespace App\Integrations\Handlers;
use App\Events\Forms\FormSubmitted;
use App\Integrations\Google\Google;
use App\Models\Integration\FormIntegration;
use Exception;
use Illuminate\Support\Facades\Log;
class GoogleSheetsIntegration extends AbstractIntegrationHandler
{
protected Google $client;
public function __construct(
protected FormSubmitted $event,
protected FormIntegration $formIntegration,
protected array $integration
) {
parent::__construct($event, $formIntegration, $integration);
$this->client = new Google($formIntegration);
}
public static function getValidationRules(): array
{
return [
];
}
public static function isOAuthRequired(): bool
{
return true;
}
public static function getValidationAttributes(): array
{
return [
'oauth_id' => 'Google Account',
];
}
public function handle(): void
{
if (!$this->shouldRun()) {
return;
}
Log::debug('Creating Google Spreadsheet record', [
'spreadsheet_id' => $this->getSpreadsheetId(),
'form_id' => $this->form->id,
'form_slug' => $this->form->slug,
]);
$this->client->sheets()->submit($this->submissionData);
}
protected function getSpreadsheetId(): string
{
if(!isset($this->integrationData->spreadsheet_id)) {
throw new Exception('The spreadsheed is not instantiated');
}
return $this->integrationData->spreadsheet_id;
}
protected function shouldRun(): bool
{
return parent::shouldRun() && $this->formIntegration->oauth_id && $this->getSpreadsheetId();
}
}

View File

@@ -0,0 +1,101 @@
<?php
namespace App\Integrations\Handlers;
use App\Service\Forms\FormSubmissionFormatter;
use Illuminate\Support\Arr;
use Vinkla\Hashids\Facades\Hashids;
class SlackIntegration extends AbstractIntegrationHandler
{
public static function getValidationRules(): array
{
return [
'slack_webhook_url' => 'required|url|starts_with:https://hooks.slack.com/',
'include_submission_data' => 'boolean',
'link_open_form' => 'boolean',
'link_edit_form' => 'boolean',
'views_submissions_count' => 'boolean',
'link_edit_submission' => 'boolean'
];
}
protected function getWebhookUrl(): ?string
{
return $this->integrationData->slack_webhook_url;
}
protected function shouldRun(): bool
{
return !is_null($this->getWebhookUrl()) && $this->form->is_pro && parent::shouldRun();
}
protected function getWebhookData(): array
{
$settings = (array) $this->integrationData ?? [];
$externalLinks = [];
if (Arr::get($settings, 'link_open_form', true)) {
$externalLinks[] = '*<' . $this->form->share_url . '|🔗 Open Form>*';
}
if (Arr::get($settings, 'link_edit_form', true)) {
$editFormURL = front_url('forms/' . $this->form->slug . '/show');
$externalLinks[] = '*<' . $editFormURL . '|✍️ Edit Form>*';
}
if (Arr::get($settings, 'link_edit_submission', true) && $this->form->editable_submissions) {
$submissionId = Hashids::encode($this->submissionData['submission_id']);
$externalLinks[] = '*<' . $this->form->share_url . '?submission_id=' . $submissionId . '|✍️ ' . $this->form->editable_submissions_button_text . '>*';
}
$blocks = [
[
'type' => 'section',
'text' => [
'type' => 'mrkdwn',
'text' => 'New submission for your form *' . $this->form->title . '*',
],
],
];
if (Arr::get($settings, 'include_submission_data', true)) {
$submissionString = '';
$formatter = (new FormSubmissionFormatter($this->form, $this->submissionData))->outputStringsOnly();
foreach ($formatter->getFieldsWithValue() as $field) {
$tmpVal = is_array($field['value']) ? implode(',', $field['value']) : $field['value'];
$submissionString .= '>*' . ucfirst($field['name']) . '*: ' . $tmpVal . " \n";
}
$blocks[] = [
'type' => 'section',
'text' => [
'type' => 'mrkdwn',
'text' => $submissionString,
],
];
}
if (Arr::get($settings, 'views_submissions_count', true)) {
$countString = '*👀 Views*: ' . (string) $this->form->views_count . " \n";
$countString .= '*🖊️ Submissions*: ' . (string) $this->form->submissions_count;
$blocks[] = [
'type' => 'section',
'text' => [
'type' => 'mrkdwn',
'text' => $countString,
],
];
}
if (count($externalLinks) > 0) {
$blocks[] = [
'type' => 'section',
'text' => [
'type' => 'mrkdwn',
'text' => implode(' ', $externalLinks),
],
];
}
return [
'blocks' => $blocks,
];
}
}

View File

@@ -0,0 +1,112 @@
<?php
namespace App\Integrations\Handlers;
use App\Mail\Forms\SubmissionConfirmationMail;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;
use Stevebauman\Purify\Facades\Purify;
/**
* Sends a confirmation to form respondant that form was submitted
*/
class SubmissionConfirmationIntegration extends AbstractIntegrationHandler
{
public const RISKY_USERS_LIMIT = 120;
public static function getValidationRules(): array
{
return [
'respondent_email' => [
'required',
'boolean',
function ($attribute, $value, $fail) {
if ($value !== true) {
$fail('Need at least 1 email field.');
}
},
],
'confirmation_reply_to' => 'email|nullable',
'notification_sender' => 'required',
'notification_subject' => 'required',
'notification_body' => 'required',
'notifications_include_submission' => 'boolean'
];
}
protected function shouldRun(): bool
{
return !(!$this->form->is_pro) && parent::shouldRun() && !$this->riskLimitReached();
}
public function handle(): void
{
if (!$this->shouldRun()) {
return;
}
$email = $this->getRespondentEmail();
if (!$email) {
return;
}
Log::info('Sending submission confirmation', [
'recipient' => $email,
'form_id' => $this->form->id,
'form_slug' => $this->form->slug,
]);
Mail::to($email)->send(new SubmissionConfirmationMail($this->event, $this->integrationData));
}
private function getRespondentEmail()
{
// Make sure we only have one email field in the form
$emailFields = collect($this->form->properties)->filter(function ($field) {
$hidden = $field['hidden'] ?? false;
return !$hidden && $field['type'] == 'email';
});
if ($emailFields->count() != 1) {
return null;
}
if (isset($this->submissionData[$emailFields->first()['id']])) {
$email = $this->submissionData[$emailFields->first()['id']];
if ($this->validateEmail($email)) {
return $email;
}
}
return null;
}
// 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::error('!!!DANGER!!! Dangerous user detected! Attempting many email sending.', [
'form_id' => $this->form->id,
'workspace_id' => $this->form->workspace->id,
]);
return true;
}
}
return false;
}
public static function validateEmail($email): bool
{
return (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
}
public static function formatData(array $data): array
{
return array_merge(parent::formatData($data), [
'notification_body' => Purify::clean($data['notification_body'] ?? ''),
]);
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace App\Integrations\Handlers;
class WebhookIntegration extends AbstractIntegrationHandler
{
public static function getValidationRules(): array
{
return [
'webhook_url' => 'required|url'
];
}
protected function getWebhookUrl(): ?string
{
return $this->integrationData->webhook_url;
}
protected function shouldRun(): bool
{
return !is_null($this->getWebhookUrl()) && parent::shouldRun();
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace App\Integrations\Handlers;
use App\Events\Forms\FormSubmitted;
use App\Models\Integration\FormIntegration;
use Exception;
class ZapierIntegration extends AbstractIntegrationHandler
{
public function __construct(
protected FormSubmitted $event,
protected FormIntegration $formIntegration,
protected array $integration
) {
parent::__construct($event, $formIntegration, $integration);
}
public static function getValidationRules(): array
{
return [];
}
public static function isOAuthRequired(): bool
{
return false;
}
protected function getWebhookUrl(): string
{
if (!isset($this->integrationData->hook_url)) {
throw new Exception('The webhook URL is missing');
}
return $this->integrationData->hook_url;
}
protected function shouldRun(): bool
{
return parent::shouldRun() && $this->getWebhookUrl();
}
}