From d312170e46bce80625d2aa31b8b79b6e35019c76 Mon Sep 17 00:00:00 2001 From: Adam Daley Date: Thu, 4 Jun 2026 19:35:48 +0100 Subject: [PATCH] Enhance email template validation and error handling (#3720) * Add email template validation and error tracking * Email templates: bulk actions & batch delete * Add email template syntax checker * Add last_error to template API; remove error styling * Add error fields to email_template * Render templates during validation with vars * Update crypt mock expectation in Email test --- src/data/.htaccess | 2 +- src/data/assets/index.html | 0 src/install/sql/content.sql | 2 +- src/install/sql/structure.sql | 2 + src/library/FOSSBilling/UpdatePatcher.php | 12 + src/modules/Client/Service.php | 12 +- src/modules/Email/Api/Admin.php | 35 +++ src/modules/Email/Entity/EmailTemplate.php | 44 +++ .../Repository/EmailTemplateRepository.php | 9 + src/modules/Email/Service.php | 85 +++++- .../admin/mod_email_settings.html.twig | 119 +++++--- .../Email/tests/Unit/Api/AdminTest.php | 34 +++ src/modules/Email/tests/Unit/ServiceTest.php | 278 +++++++++++++++++- src/modules/Invoice/Service.php | 10 +- src/modules/Order/Service.php | 12 +- src/modules/Order/tests/Unit/ServiceTest.php | 75 +---- src/modules/Staff/Service.php | 16 +- src/modules/Support/Service.php | 16 +- src/modules/System/Service.php | 35 +++ 19 files changed, 653 insertions(+), 145 deletions(-) delete mode 100644 src/data/assets/index.html diff --git a/src/data/.htaccess b/src/data/.htaccess index 20345b911..f3c10e6ec 100644 --- a/src/data/.htaccess +++ b/src/data/.htaccess @@ -1,2 +1,2 @@ RewriteEngine On -RewriteRule !^assets/gateways/.*\.(jpe?g|png)$ - [F,NC] \ No newline at end of file +RewriteRule !^assets/gateways/.*\.(jpe?g|png)$ - [F,NC] diff --git a/src/data/assets/index.html b/src/data/assets/index.html deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/install/sql/content.sql b/src/install/sql/content.sql index 43f769d25..0b451865f 100644 --- a/src/install/sql/content.sql +++ b/src/install/sql/content.sql @@ -303,7 +303,7 @@ LOCK TABLES `setting` WRITE; INSERT INTO `setting` (`id`, `param`, `value`, `public`, `category`, `hash`, `created_at`, `updated_at`) VALUES - (1,'last_patch','68',0,NULL,NULL,'2024-12-30 12:00:00','2024-12-30 12:00:00'), + (1,'last_patch','69',0,NULL,NULL,'2024-12-30 12:00:00','2024-12-30 12:00:00'), (2,'company_name','Company Name',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'), (3,'company_email','support@yourcompany.com',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'), (4,'company_signature','FOSSBilling.org - Client Management, Invoicing and Support Software',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'), diff --git a/src/install/sql/structure.sql b/src/install/sql/structure.sql index 4258b89cc..7424a3cde 100644 --- a/src/install/sql/structure.sql +++ b/src/install/sql/structure.sql @@ -417,6 +417,8 @@ CREATE TABLE `email_template` ( `content` text, `description` text, `vars` text, + `last_error` text DEFAULT NULL, + `error_checked_at` datetime DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `action_code` (`action_code`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; diff --git a/src/library/FOSSBilling/UpdatePatcher.php b/src/library/FOSSBilling/UpdatePatcher.php index 61b3bb9ee..2a93f3c8c 100644 --- a/src/library/FOSSBilling/UpdatePatcher.php +++ b/src/library/FOSSBilling/UpdatePatcher.php @@ -457,6 +457,7 @@ class UpdatePatcher implements InjectionAwareInterface 66 => 'patch66', 67 => 'patch67', 68 => 'patch68', + 69 => 'patch69', ]; ksort($patches, SORT_NATURAL); @@ -1503,6 +1504,17 @@ class UpdatePatcher implements InjectionAwareInterface ); } + private function patch69(): void + { + if (!$this->tableHasColumn('email_template', 'last_error')) { + $this->executeSql('ALTER TABLE `email_template` ADD COLUMN `last_error` TEXT DEFAULT NULL'); + } + + if (!$this->tableHasColumn('email_template', 'error_checked_at')) { + $this->executeSql('ALTER TABLE `email_template` ADD COLUMN `error_checked_at` DATETIME DEFAULT NULL'); + } + } + private function generateDownloadableStoredFilename(): string { do { diff --git a/src/modules/Client/Service.php b/src/modules/Client/Service.php index 60ef11d18..e882ddf14 100644 --- a/src/modules/Client/Service.php +++ b/src/modules/Client/Service.php @@ -154,9 +154,7 @@ class Service implements InjectionAwareInterface $emailService->sendTemplate($email); } catch (\Exception $exc) { - if (!\FOSSBilling\Environment::isTesting()) { - error_log($exc->getMessage()); - } + $di['logger']->setChannel('email')->error('Failed to send client signup email', ['exception' => $exc->getMessage()]); } return true; @@ -775,9 +773,7 @@ class Service implements InjectionAwareInterface $emailService = $this->di['mod_service']('email'); $emailService->sendTemplate($email); } catch (\Exception $exc) { - if (!\FOSSBilling\Environment::isTesting()) { - error_log($exc->getMessage()); - } + $this->di['logger']->setChannel('email')->error('Failed to send client welcome email', ['exception' => $exc->getMessage()]); } } @@ -835,9 +831,7 @@ class Service implements InjectionAwareInterface $emailService = $this->di['mod_service']('email'); $emailService->sendTemplate($email); } catch (\Exception $exc) { - if (!\FOSSBilling\Environment::isTesting()) { - error_log($exc->getMessage()); - } + $this->di['logger']->setChannel('email')->error('Failed to send email confirmation email', ['exception' => $exc->getMessage()]); } } diff --git a/src/modules/Email/Api/Admin.php b/src/modules/Email/Api/Admin.php index 23593be8c..8cb13409d 100644 --- a/src/modules/Email/Api/Admin.php +++ b/src/modules/Email/Api/Admin.php @@ -168,6 +168,8 @@ class Admin extends \Api_Abstract 'is_custom' => $item['is_custom'] ?? false, 'has_default' => $item['has_default'] ?? false, 'is_overridden' => $item['is_overridden'] ?? false, + 'has_error' => $item['has_error'] ?? false, + 'last_error' => $item['last_error'] ?? null, ]; } @@ -332,6 +334,19 @@ class Admin extends \Api_Abstract return $this->getService()->templateBatchEnable(); } + /** + * Validate all email templates for Twig syntax errors. + * Returns a summary of valid and invalid templates with error details. + * + * @return array + */ + public function template_validate_all() + { + $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'manage_templates'); + + return $this->getService()->validateAllTemplates(); + } + /** * Sends the test email to the currently authenticated admin / staff member. */ @@ -393,6 +408,26 @@ class Admin extends \Api_Abstract return $this->getService()->sendTemplate($data); } + /** + * Deletes email templates with given IDs. + */ + #[RequiredParams(['ids' => 'IDs were not passed'])] + public function batch_template_delete($data): bool + { + $this->getDi()['mod_service']('Staff')->checkPermissionsAndThrowException('email', 'manage_templates'); + + foreach ($data['ids'] as $id) { + $template = $this->getService()->getTemplate((int) $id); + if (!$template->isCustom() && $this->getService()->hasDefaultTemplate($template->getActionCode())) { + continue; + } + $this->getDi()['em']->remove($template); + } + $this->getDi()['em']->flush(); + + return true; + } + /** * Deletes email logs with given IDs. */ diff --git a/src/modules/Email/Entity/EmailTemplate.php b/src/modules/Email/Entity/EmailTemplate.php index 3e6703d71..1a0ca13f5 100644 --- a/src/modules/Email/Entity/EmailTemplate.php +++ b/src/modules/Email/Entity/EmailTemplate.php @@ -43,6 +43,12 @@ class EmailTemplate implements ApiArrayInterface #[ORM\Column(type: Types::TEXT, nullable: true)] private ?string $vars = null; + #[ORM\Column(name: 'last_error', type: Types::TEXT, nullable: true)] + private ?string $lastError = null; + + #[ORM\Column(name: 'error_checked_at', type: Types::DATETIME_IMMUTABLE, nullable: true)] + private ?\DateTimeImmutable $errorCheckedAt = null; + public function __construct( #[ORM\Column(name: 'action_code', type: Types::STRING, length: 255, unique: true)] private string $actionCode, @@ -64,6 +70,7 @@ class EmailTemplate implements ApiArrayInterface 'description' => $this->getDescription(), 'is_custom' => $this->isCustom(), 'is_overridden' => $this->isOverridden(), + 'last_error' => $this->getLastError(), ]; } @@ -179,4 +186,41 @@ class EmailTemplate implements ApiArrayInterface return $this; } + + public function getLastError(): ?string + { + return $this->lastError; + } + + public function setLastError(?string $lastError): self + { + $this->lastError = $lastError; + + return $this; + } + + public function getErrorCheckedAt(): ?\DateTimeImmutable + { + return $this->errorCheckedAt; + } + + public function setErrorCheckedAt(?\DateTimeImmutable $errorCheckedAt): self + { + $this->errorCheckedAt = $errorCheckedAt; + + return $this; + } + + public function hasError(): bool + { + return $this->lastError !== null && $this->lastError !== ''; + } + + public function clearError(): self + { + $this->lastError = null; + $this->errorCheckedAt = null; + + return $this; + } } diff --git a/src/modules/Email/Repository/EmailTemplateRepository.php b/src/modules/Email/Repository/EmailTemplateRepository.php index 1f96697a8..e56add141 100644 --- a/src/modules/Email/Repository/EmailTemplateRepository.php +++ b/src/modules/Email/Repository/EmailTemplateRepository.php @@ -76,4 +76,13 @@ class EmailTemplateRepository extends EntityRepository ->getQuery() ->execute(); } + + public function countBroken(): int + { + return (int) $this->createQueryBuilder('t') + ->select('COUNT(t.id)') + ->where('t.lastError IS NOT NULL') + ->getQuery() + ->getSingleScalarResult(); + } } diff --git a/src/modules/Email/Service.php b/src/modules/Email/Service.php index 2c4135d38..03cc50ed3 100644 --- a/src/modules/Email/Service.php +++ b/src/modules/Email/Service.php @@ -211,6 +211,10 @@ class Service implements \FOSSBilling\InjectionAwareInterface public function getVars(EmailTemplate $template): array { + if ($template->getVars() === null || $template->getVars() === '') { + return []; + } + $json = $this->di['crypt']->decrypt($template->getVars(), Config::getProperty('info.salt')); return is_string($json) ? json_decode($json, true) : []; @@ -566,10 +570,24 @@ class Service implements \FOSSBilling\InjectionAwareInterface { $systemService = $this->di['mod_service']('System'); [$subjectTemplate, $contentTemplate] = $this->getEffectiveTemplateParts($template); - $pc = $systemService->renderEmailTplString($contentTemplate, $vars); - $ps = $systemService->renderEmailTplString($subjectTemplate, $vars); - return [$ps, $pc]; + try { + $pc = $systemService->renderEmailTplString($contentTemplate, $vars); + $ps = $systemService->renderEmailTplString($subjectTemplate, $vars); + + if ($template->hasError()) { + $template->clearError(); + $this->di['em']->flush(); + } + + return [$ps, $pc]; + } catch (\FOSSBilling\Exception $e) { + $template->setLastError($e->getMessage()); + $template->setErrorCheckedAt(new \DateTimeImmutable()); + $this->di['em']->flush(); + + throw $e; + } } public function resend(\Model_ActivityClientEmail $email): bool @@ -699,6 +717,8 @@ class Service implements \FOSSBilling\InjectionAwareInterface $data['vars'] = $this->getVars($template); $data['subject_override'] = $isCustom ? null : $template->getSubject(); $data['content_override'] = $isCustom ? null : $template->getContent(); + $data['has_error'] = $template->hasError(); + $data['last_error'] = $template->getLastError(); } return $data; @@ -734,6 +754,8 @@ class Service implements \FOSSBilling\InjectionAwareInterface 'is_custom' => $isCustom, 'has_default' => !$isCustom && $default !== null, 'is_overridden' => $isOverridden, + 'has_error' => !empty($template['last_error']), + 'last_error' => $template['last_error'] ?? null, ]; } @@ -765,6 +787,8 @@ class Service implements \FOSSBilling\InjectionAwareInterface $template->setContent($content); } + $template->clearError(); + if (!$isCustom && $default !== null) { $subjectMatches = $template->getSubject() === $default['subject']; $contentMatches = $template->getContent() === $default['content']; @@ -810,6 +834,16 @@ class Service implements \FOSSBilling\InjectionAwareInterface public function templateCreate($actionCode, $subject, $content, $enabled = 0, $category = null): EmailTemplate { + $systemService = $this->di['mod_service']('System'); + + if ($subject !== null && $subject !== '') { + $systemService->renderEmailTplString($subject, []); + } + + if ($content !== null && $content !== '') { + $systemService->renderEmailTplString($content, []); + } + $template = new EmailTemplate($actionCode); $template->setSubject($subject) ->setEnabled((bool) $enabled) @@ -922,6 +956,51 @@ class Service implements \FOSSBilling\InjectionAwareInterface return $result; } + public function getBrokenTemplateCount(): int + { + return $this->getTemplateRepository()->countBroken(); + } + + public function validateAllTemplates(): array + { + $templates = $this->getTemplateRepository()->findAll(); + $results = ['valid' => 0, 'invalid' => 0, 'errors' => []]; + $systemService = $this->di['mod_service']('System'); + + foreach ($templates as $template) { + [$subjectTemplate, $contentTemplate] = $this->getEffectiveTemplateParts($template); + $vars = $this->getVars($template); + $error = null; + + try { + $systemService->renderEmailTplString($contentTemplate, $vars); + $systemService->renderEmailTplString($subjectTemplate, $vars); + } catch (\Throwable $e) { + $error = $e->getMessage(); + } + + if ($error !== null) { + $template->setLastError($error); + $template->setErrorCheckedAt(new \DateTimeImmutable()); + ++$results['invalid']; + $results['errors'][] = [ + 'id' => $template->getId(), + 'action_code' => $template->getActionCode(), + 'error' => $error, + ]; + } else { + if ($template->hasError()) { + $template->clearError(); + } + ++$results['valid']; + } + } + + $this->di['em']->flush(); + + return $results; + } + /** * Sends emails from queue, respecting the configured time limit and emails per cron limit. * If an email fails to be sent, it will be skipped and retried on the next cron run until the retry limit is reached. diff --git a/src/modules/Email/templates/admin/mod_email_settings.html.twig b/src/modules/Email/templates/admin/mod_email_settings.html.twig index 1c63f95db..5043a26f2 100644 --- a/src/modules/Email/templates/admin/mod_email_settings.html.twig +++ b/src/modules/Email/templates/admin/mod_email_settings.html.twig @@ -30,12 +30,37 @@ {% set active_tab = requested_tab ?? (can_access_templates ? 'templates' : (can_view_email_history ? 'queue' : 'email')) %} {% if can_manage_templates %} {% set new_template_action %} - +
+ + +
{% endset %} {% endif %} {% block content %} @@ -47,8 +72,8 @@

{{ 'Manage email templates, queued messages, and delivery settings for outgoing mail.'|trans }}

-
-
{% endif %} @@ -619,6 +642,34 @@ }); }); + const validateLink = document.getElementById('validateTemplatesLink'); + if (validateLink) { + validateLink.addEventListener('click', function(event) { + FOSSBilling.api.admin.get('email/template_validate_all', {}, + (result) => { + if (result.invalid > 0) { + let msg = "{{ 'Validation complete: :valid valid, :invalid invalid'|trans }}".replace(':valid', result.valid).replace(':invalid', result.invalid); + if (result.errors && result.errors.length) { + msg += ''; + } + FOSSBilling.message(msg, 'warning'); + } else { + FOSSBilling.message("{{ 'All :count templates are valid'|trans }}".replace(':count', result.valid)); + } + setTimeout(() => location.reload(), 3000); + }, + (result) => { + FOSSBilling.message(result.message, 'error'); + }); + + event.preventDefault(); + }); + } + {% if can_manage_templates %} if (window.location.hash === '#tab-new') { const modalElement = document.getElementById('newEmailTemplateModal'); diff --git a/src/modules/Email/tests/Unit/Api/AdminTest.php b/src/modules/Email/tests/Unit/Api/AdminTest.php index da42a138e..fde8ae7d2 100644 --- a/src/modules/Email/tests/Unit/Api/AdminTest.php +++ b/src/modules/Email/tests/Unit/Api/AdminTest.php @@ -577,3 +577,37 @@ test('batch delete', function (): void { $result = $activityMock->batch_delete(['ids' => [1, 2, 3]]); expect($result)->toBeTrue(); }); + +test('batch template delete skips built-in templates with defaults', function (): void { + $adminApi = new Box\Mod\Email\Api\Admin(); + + $builtinTemplate = new EmailTemplate('mod_email_test', 1); + $builtinTemplate->setIsCustom(false); + + $emailService = Mockery::mock(Box\Mod\Email\Service::class)->makePartial(); + $emailService->shouldReceive('getTemplate')->once()->andReturn($builtinTemplate); + $emailService->shouldReceive('hasDefaultTemplate')->once()->andReturn(true); + + $emMock = Mockery::mock(); + $emMock->shouldReceive('flush')->once(); + + $staffService = Mockery::mock(); + $staffService->shouldReceive('checkPermissionsAndThrowException')->once(); + + $di = container(); + $di['mod_service'] = $di->protect(function ($name) use ($emailService, $staffService) { + if ($name === 'email') { + return $emailService; + } + if ($name === 'Staff') { + return $staffService; + } + }); + $di['em'] = $emMock; + + $adminApi->setDi($di); + $adminApi->setService($emailService); + + $result = $adminApi->batch_template_delete(['ids' => [1]]); + expect($result)->toBeTrue(); +}); diff --git a/src/modules/Email/tests/Unit/ServiceTest.php b/src/modules/Email/tests/Unit/ServiceTest.php index b6609b586..c1811baf5 100644 --- a/src/modules/Email/tests/Unit/ServiceTest.php +++ b/src/modules/Email/tests/Unit/ServiceTest.php @@ -51,6 +51,14 @@ function emailTemplate(string $actionCode = '', ?int $id = null, array $data = [ $template->setIsOverridden((bool) $data['is_overridden']); } + if (array_key_exists('last_error', $data)) { + $template->setLastError($data['last_error']); + } + + if (array_key_exists('error_checked_at', $data)) { + $template->setErrorCheckedAt($data['error_checked_at']); + } + return $template; } @@ -662,6 +670,8 @@ test('templateToApiArray returns deep array with vars', function (): void { ], 'subject_override' => $subject, 'content_override' => $content, + 'has_error' => false, + 'last_error' => null, ]; $serviceMock = Mockery::mock(Box\Mod\Email\Service::class)->makePartial(); @@ -715,7 +725,7 @@ test('updateTemplate updates template', function (array $data, string $templateR $cryptMock = Mockery::mock('\Box_Crypt'); $cryptMock->shouldReceive('decrypt') - ->atLeast()->once(); + ->never(); $configMock = ['salt' => md5(random_bytes(13))]; $twigStub = Mockery::mock(Twig\Environment::class); @@ -922,3 +932,269 @@ test('sendMail queues email for sending', function (): void { $result = $service->sendMail($to, $from, $subject, $content); expect($result)->toBeTrue(); }); + +test('getBrokenTemplateCount returns count from repository', function (): void { + $service = new Box\Mod\Email\Service(); + $di = container(); + + $repoMock = Mockery::mock(Box\Mod\Email\Repository\EmailTemplateRepository::class); + $repoMock->shouldReceive('countBroken') + ->once() + ->andReturn(3); + + $service->setDi($di); + + $ref = new ReflectionProperty($service, 'templateRepository'); + $ref->setAccessible(true); + $ref->setValue($service, $repoMock); + + expect($service->getBrokenTemplateCount())->toBe(3); +}); + +test('validateAllTemplates reports invalid templates', function (): void { + $serviceMock = Mockery::mock(Box\Mod\Email\Service::class)->makePartial(); + $di = container(); + + $validTemplate = emailTemplate('mod_email_valid', 1, [ + 'enabled' => true, + 'subject' => 'Hello', + 'content' => 'World', + ]); + + $invalidTemplate = emailTemplate('mod_email_broken', 2, [ + 'enabled' => true, + 'subject' => 'Hello', + 'content' => 'Broken', + ]); + + $repoMock = Mockery::mock(Box\Mod\Email\Repository\EmailTemplateRepository::class); + $repoMock->shouldReceive('findAll') + ->once() + ->andReturn([$validTemplate, $invalidTemplate]); + + $systemMock = Mockery::mock(); + $systemMock->shouldReceive('renderEmailTplString') + ->times(3) + ->andReturnUsing(function (string $template, array $vars): string { + expect($vars)->toBe([]); + + if ($template === 'Broken') { + throw new FOSSBilling\InformationException('Email template syntax error: Unknown "filter" filter'); + } + + return $template; + }); + + $emMock = Mockery::mock(); + $emMock->shouldReceive('flush')->once(); + + $di['mod_service'] = $di->protect(function ($name) use ($systemMock) { + if ($name === 'System' || $name === 'system') { + return $systemMock; + } + }); + $di['em'] = $emMock; + + $serviceMock->setDi($di); + + $ref = new ReflectionProperty($serviceMock, 'templateRepository'); + $ref->setAccessible(true); + $ref->setValue($serviceMock, $repoMock); + + $result = $serviceMock->validateAllTemplates(); + + expect($result['valid'])->toBe(1); + expect($result['invalid'])->toBe(1); + expect($result['errors'])->toHaveCount(1); + expect($result['errors'][0]['action_code'])->toBe('mod_email_broken'); +}); + +test('validateAllTemplates clears previous errors on valid templates', function (): void { + $serviceMock = Mockery::mock(Box\Mod\Email\Service::class)->makePartial(); + $di = container(); + + $template = emailTemplate('mod_email_recovery', 1, [ + 'enabled' => true, + 'subject' => 'Hello', + 'content' => 'World', + 'last_error' => 'Previous error', + ]); + + $repoMock = Mockery::mock(Box\Mod\Email\Repository\EmailTemplateRepository::class); + $repoMock->shouldReceive('findAll') + ->once() + ->andReturn([$template]); + + $systemMock = Mockery::mock(); + $systemMock->shouldReceive('renderEmailTplString') + ->twice() + ->andReturnArg(0); + + $emMock = Mockery::mock(); + $emMock->shouldReceive('flush')->once(); + + $di['mod_service'] = $di->protect(function ($name) use ($systemMock) { + if ($name === 'System' || $name === 'system') { + return $systemMock; + } + }); + $di['em'] = $emMock; + + $serviceMock->setDi($di); + + $ref = new ReflectionProperty($serviceMock, 'templateRepository'); + $ref->setAccessible(true); + $ref->setValue($serviceMock, $repoMock); + + $result = $serviceMock->validateAllTemplates(); + + expect($result['valid'])->toBe(1); + expect($result['invalid'])->toBe(0); + expect($template->hasError())->toBeFalse(); +}); + +test('validateAllTemplates renders templates with stored vars to enforce sandbox policy', function (): void { + $serviceMock = Mockery::mock(Box\Mod\Email\Service::class)->makePartial(); + $di = container(); + + $template = emailTemplate('mod_email_sandbox', 1, [ + 'enabled' => true, + 'subject' => 'Hello {{ name }}', + 'content' => '{{ content|disallowed_filter }}', + 'vars' => 'encrypted-vars', + ]); + + $repoMock = Mockery::mock(Box\Mod\Email\Repository\EmailTemplateRepository::class); + $repoMock->shouldReceive('findAll') + ->once() + ->andReturn([$template]); + + $cryptMock = Mockery::mock('\Box_Crypt'); + $cryptMock->shouldReceive('decrypt') + ->once() + ->with('encrypted-vars', Mockery::type('string')) + ->andReturn('{"name":"Ada","content":"Body"}'); + + $systemMock = Mockery::mock(); + $systemMock->shouldReceive('renderEmailTplString') + ->once() + ->with('{{ content|disallowed_filter }}', ['name' => 'Ada', 'content' => 'Body']) + ->andThrow(new FOSSBilling\InformationException('Email template contains disallowed Twig syntax: Filter "disallowed_filter" is not allowed')); + $systemMock->shouldReceive('renderEmailTplString') + ->with('Hello {{ name }}', Mockery::any()) + ->never(); + + $emMock = Mockery::mock(); + $emMock->shouldReceive('flush')->once(); + + $di['crypt'] = $cryptMock; + $di['mod_service'] = $di->protect(function ($name) use ($systemMock) { + if ($name === 'System' || $name === 'system') { + return $systemMock; + } + }); + $di['em'] = $emMock; + + $serviceMock->setDi($di); + + $ref = new ReflectionProperty($serviceMock, 'templateRepository'); + $ref->setAccessible(true); + $ref->setValue($serviceMock, $repoMock); + + $result = $serviceMock->validateAllTemplates(); + + expect($result['valid'])->toBe(0); + expect($result['invalid'])->toBe(1); + expect($template->hasError())->toBeTrue(); + expect($template->getLastError())->toContain('disallowed Twig syntax'); +}); + +test('templateCreate validates subject and content', function (): void { + $service = new Box\Mod\Email\Service(); + $di = container(); + + $systemMock = Mockery::mock(); + $systemMock->shouldReceive('renderEmailTplString') + ->once() + ->withArgs(fn ($tpl) => str_contains($tpl, 'valid subject')) + ->andReturn('rendered'); + $systemMock->shouldReceive('renderEmailTplString') + ->once() + ->withArgs(fn ($tpl) => str_contains($tpl, 'valid content')) + ->andReturn('rendered'); + + $emMock = Mockery::mock(); + $emMock->shouldReceive('persist')->once(); + $emMock->shouldReceive('flush')->once(); + + $di['mod_service'] = $di->protect(function ($name) use ($systemMock) { + if ($name === 'System' || $name === 'system') { + return $systemMock; + } + }); + $di['em'] = $emMock; + $di['logger'] = new Tests\Helpers\TestLogger(); + + $service->setDi($di); + + $template = $service->templateCreate('mod_test_code', 'valid subject', 'valid content', 1, 'test'); + + expect($template)->toBeInstanceOf(EmailTemplate::class); +}); + +test('templateCreate throws on invalid content', function (): void { + $service = new Box\Mod\Email\Service(); + $di = container(); + + $systemMock = Mockery::mock(); + $systemMock->shouldReceive('renderEmailTplString') + ->once() + ->andReturn('rendered'); + $systemMock->shouldReceive('renderEmailTplString') + ->once() + ->andThrow(new FOSSBilling\InformationException('Email template syntax error: Unknown "bad_filter" filter')); + + $di['mod_service'] = $di->protect(function ($name) use ($systemMock) { + if ($name === 'System' || $name === 'system') { + return $systemMock; + } + }); + + $service->setDi($di); + + $service->templateCreate('mod_test_broken', 'subject', '{{ x|bad_filter }}', 1); +})->throws(FOSSBilling\InformationException::class, 'Email template syntax error'); + +test('EmailTemplate hasError returns true when lastError is set', function (): void { + $template = new EmailTemplate('test_code', 1); + + expect($template->hasError())->toBeFalse(); + + $template->setLastError('Some error message'); + expect($template->hasError())->toBeTrue(); + + $template->clearError(); + expect($template->hasError())->toBeFalse(); + expect($template->getLastError())->toBeNull(); + expect($template->getErrorCheckedAt())->toBeNull(); +}); + +test('EmailTemplate toApiArray includes has_error and last_error in deep mode', function (): void { + $template = emailTemplate('mod_test_code', 1, [ + 'enabled' => true, + 'subject' => 'Test Subject', + 'content' => 'Test Content', + 'is_custom' => true, + 'last_error' => 'Some syntax error', + ]); + + $serviceMock = Mockery::mock(Box\Mod\Email\Service::class)->makePartial(); + $serviceMock->shouldReceive('getVars') + ->atLeast()->once() + ->andReturn([]); + + $result = $serviceMock->templateToApiArray($template, true); + + expect($result['has_error'])->toBeTrue(); + expect($result['last_error'])->toBe('Some syntax error'); +}); diff --git a/src/modules/Invoice/Service.php b/src/modules/Invoice/Service.php index 58c29ce9c..947c062f6 100644 --- a/src/modules/Invoice/Service.php +++ b/src/modules/Invoice/Service.php @@ -402,7 +402,7 @@ class Service implements InjectionAwareInterface $emailService->sendTemplate($email); } } catch (\Exception $exc) { - error_log($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send email for invoice payment', ['exception' => $exc->getMessage()]); } return true; @@ -424,7 +424,7 @@ class Service implements InjectionAwareInterface $emailService = $di['mod_service']('Email'); $emailService->sendTemplate($email); } catch (\Exception $exc) { - error_log($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send email for invoice creation', ['exception' => $exc->getMessage()]); } return true; @@ -456,7 +456,7 @@ class Service implements InjectionAwareInterface $service->extendInvoiceHashLifetime($invoiceModel); } } catch (\Exception $exc) { - error_log($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send email for invoice approval', ['exception' => $exc->getMessage()]); } return true; @@ -486,7 +486,7 @@ class Service implements InjectionAwareInterface // since the recipient is being re-engaged via the same link. $service->extendInvoiceHashLifetime($invoiceModel); } catch (\Exception $exc) { - error_log($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send invoice reminder email', ['exception' => $exc->getMessage()]); } } @@ -526,7 +526,7 @@ class Service implements InjectionAwareInterface $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); } catch (\Exception $exc) { - error_log($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send overdue invoice email', ['exception' => $exc->getMessage()]); } } diff --git a/src/modules/Order/Service.php b/src/modules/Order/Service.php index d825f229a..a9f5c168b 100644 --- a/src/modules/Order/Service.php +++ b/src/modules/Order/Service.php @@ -95,7 +95,7 @@ class Service implements InjectionAwareInterface $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->err($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send order activation email', ['exception' => $exc->getMessage(), 'order_id' => $order_id]); } } @@ -121,7 +121,7 @@ class Service implements InjectionAwareInterface $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->err($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send order renewal email', ['exception' => $exc->getMessage()]); } } @@ -147,7 +147,7 @@ class Service implements InjectionAwareInterface $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->err($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send order suspension email', ['exception' => $exc->getMessage()]); } } @@ -173,7 +173,7 @@ class Service implements InjectionAwareInterface $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->err($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send order unsuspension email', ['exception' => $exc->getMessage()]); } } @@ -197,7 +197,7 @@ class Service implements InjectionAwareInterface $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->err($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send order cancellation email', ['exception' => $exc->getMessage()]); } } @@ -223,7 +223,7 @@ class Service implements InjectionAwareInterface $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->err($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send order uncancel email', ['exception' => $exc->getMessage()]); } } diff --git a/src/modules/Order/tests/Unit/ServiceTest.php b/src/modules/Order/tests/Unit/ServiceTest.php index 36167d732..66831fc2e 100644 --- a/src/modules/Order/tests/Unit/ServiceTest.php +++ b/src/modules/Order/tests/Unit/ServiceTest.php @@ -183,65 +183,7 @@ test('logs exception when email fails on activate', function (): void { $serviceMock->onAfterAdminOrderActivate($eventMock); expect($loggerMock->calls)->toHaveCount(1); - expect($loggerMock->calls[0]['method'])->toBe('err'); - expect($loggerMock->calls[0]['params'][0])->toBe('Email send failure'); -}); - -test('fires event after admin renews order', function (): void { - $params = ['id' => 1]; - - $eventMock = Mockery::mock('\Box_Event'); - $eventMock->shouldReceive('getParameters') - ->atLeast()->once() - ->andReturn($params); - - $order = new Model_ClientOrder(); - $order->loadBean(new Tests\Helpers\DummyBean()); - - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('getExistingModelById') - ->atLeast()->once() - ->andReturn($order); - - $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); - $emailServiceMock->shouldReceive('sendTemplate') - ->atLeast()->once() - ->andReturn(true); - - $orderArr = [ - 'id' => 1, - 'client' => ['id' => 1], - 'service_type' => 'domain', - ]; - - $serviceMock = Mockery::mock(Service::class)->makePartial(); - $serviceMock->shouldReceive('getOrderServiceData') - ->atLeast()->once() - ->andReturn([]); - $serviceMock->shouldReceive('toApiArray') - ->atLeast()->once() - ->andReturn($orderArr); - - $admin = new Model_Admin(); - $admin->loadBean(new Tests\Helpers\DummyBean()); - - $di = container(); - $di['db'] = $dbMock; - $di['loggedin_admin'] = $admin; - $di['mod_service'] = $di->protect(function ($serviceName) use ($emailServiceMock, $serviceMock) { - if ($serviceName == 'email') { - return $emailServiceMock; - } - if ($serviceName == 'order') { - return $serviceMock; - } - }); - $serviceMock->setDi($di); - $eventMock->shouldReceive('getDi') - ->atLeast()->once() - ->andReturn($di); - - $serviceMock->onAfterAdminOrderRenew($eventMock); + expect($loggerMock->calls[0]['method'])->toBe('error'); }); test('logs exception when email fails on renew', function (): void { @@ -304,8 +246,7 @@ test('logs exception when email fails on renew', function (): void { $serviceMock->onAfterAdminOrderRenew($eventMock); expect($loggerMock->calls)->toHaveCount(1); - expect($loggerMock->calls[0]['method'])->toBe('err'); - expect($loggerMock->calls[0]['params'][0])->toBe('Email send failure'); + expect($loggerMock->calls[0]['method'])->toBe('error'); }); test('fires event after admin suspends order', function (): void { @@ -425,8 +366,7 @@ test('logs exception when email fails on suspend', function (): void { $serviceMock->onAfterAdminOrderSuspend($eventMock); expect($loggerMock->calls)->toHaveCount(1); - expect($loggerMock->calls[0]['method'])->toBe('err'); - expect($loggerMock->calls[0]['params'][0])->toBe('Email send failure'); + expect($loggerMock->calls[0]['method'])->toBe('error'); }); test('fires event after admin unsuspends order', function (): void { @@ -546,8 +486,7 @@ test('logs exception when email fails on unsuspend', function (): void { $serviceMock->onAfterAdminOrderUnsuspend($eventMock); expect($loggerMock->calls)->toHaveCount(1); - expect($loggerMock->calls[0]['method'])->toBe('err'); - expect($loggerMock->calls[0]['params'][0])->toBe('Email send failure'); + expect($loggerMock->calls[0]['method'])->toBe('error'); }); test('fires event after admin cancels order', function (): void { @@ -661,8 +600,7 @@ test('logs exception when email fails on cancel', function (): void { $serviceMock->onAfterAdminOrderCancel($eventMock); expect($loggerMock->calls)->toHaveCount(1); - expect($loggerMock->calls[0]['method'])->toBe('err'); - expect($loggerMock->calls[0]['params'][0])->toBe('Email send failure'); + expect($loggerMock->calls[0]['method'])->toBe('error'); }); test('fires event after admin uncancels order', function (): void { @@ -782,8 +720,7 @@ test('logs exception when email fails on uncancel', function (): void { $serviceMock->onAfterAdminOrderUncancel($eventMock); expect($loggerMock->calls)->toHaveCount(1); - expect($loggerMock->calls[0]['method'])->toBe('err'); - expect($loggerMock->calls[0]['params'][0])->toBe('Email send failure'); + expect($loggerMock->calls[0]['method'])->toBe('error'); }); test('gets order core service', function (): void { diff --git a/src/modules/Staff/Service.php b/src/modules/Staff/Service.php index 4668227c3..422b91a4d 100644 --- a/src/modules/Staff/Service.php +++ b/src/modules/Staff/Service.php @@ -355,7 +355,7 @@ class Service implements InjectionAwareInterface $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->error($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send staff order notification email', ['exception' => $exc->getMessage()]); } } @@ -387,7 +387,7 @@ class Service implements InjectionAwareInterface $email['ticket'] = $ticket; $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->error($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send staff ticket notification email', ['exception' => $exc->getMessage()]); } } @@ -409,7 +409,7 @@ class Service implements InjectionAwareInterface $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->error($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send staff ticket reply notification email', ['exception' => $exc->getMessage()]); } } @@ -430,7 +430,7 @@ class Service implements InjectionAwareInterface $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->error($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send staff ticket close notification email', ['exception' => $exc->getMessage()]); } } @@ -450,7 +450,7 @@ class Service implements InjectionAwareInterface $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->error($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send staff public ticket notification email', ['exception' => $exc->getMessage()]); } } @@ -469,7 +469,7 @@ class Service implements InjectionAwareInterface $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->error($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send staff client signup notification email', ['exception' => $exc->getMessage()]); } return true; @@ -491,7 +491,7 @@ class Service implements InjectionAwareInterface $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->error($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send staff public ticket reply notification email', ['exception' => $exc->getMessage()]); } } @@ -511,7 +511,7 @@ class Service implements InjectionAwareInterface $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->error($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send staff public ticket close notification email', ['exception' => $exc->getMessage()]); } } diff --git a/src/modules/Support/Service.php b/src/modules/Support/Service.php index 2eb425f3b..c8f2532aa 100644 --- a/src/modules/Support/Service.php +++ b/src/modules/Support/Service.php @@ -78,7 +78,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->error($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send ticket open email', ['exception' => $exc->getMessage()]); } } @@ -100,7 +100,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->error($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send admin ticket open email', ['exception' => $exc->getMessage()]); } } @@ -122,7 +122,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->error($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send ticket close email', ['exception' => $exc->getMessage()]); } } @@ -144,7 +144,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->error($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send ticket reply email', ['exception' => $exc->getMessage()]); } } @@ -166,7 +166,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->error($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send public ticket open email', ['exception' => $exc->getMessage()]); } } @@ -189,7 +189,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->error($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send admin public ticket open email', ['exception' => $exc->getMessage()]); } } @@ -212,7 +212,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->error($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send admin public ticket reply email', ['exception' => $exc->getMessage()]); } } @@ -235,7 +235,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); } catch (\Exception $exc) { - $di['logger']->error($exc->getMessage()); + $di['logger']->setChannel('email')->error('Failed to send admin public ticket close email', ['exception' => $exc->getMessage()]); } } diff --git a/src/modules/System/Service.php b/src/modules/System/Service.php index c587fd191..f5bba46b4 100644 --- a/src/modules/System/Service.php +++ b/src/modules/System/Service.php @@ -467,6 +467,26 @@ class Service ); } + try { + $emailService = $this->di['mod_service']('email'); + $brokenTemplates = $emailService->getBrokenTemplateCount(); + if ($brokenTemplates > 0) { + $emailSettingsUrl = $this->di['url']->adminLink('extension/settings/email'); + $messages[] = $this->createAdminAlert( + 'warning', + __trans(':count email template(s) have syntax errors and cannot send emails. Please review and fix them.', [':count' => $brokenTemplates]), + __trans('Broken Email Templates'), + [[ + 'link' => $emailSettingsUrl, + 'text' => __trans('View Email Templates'), + 'type' => 'warning', + ]] + ); + } + } catch (\Exception $e) { + error_log($e->getMessage()); + } + if ($type === null || $type === '') { return $messages; } @@ -560,6 +580,21 @@ class Service ); } + public function checkEmailTplSyntax(string $tpl): void + { + $twigFactory = $this->di['twig_factory']; + $twig = $twigFactory->createEmailEnvironment(); + + try { + $stream = $twig->tokenize(new \Twig\Source($tpl, '__validation__')); + $twig->parse($stream); + } catch (\Twig\Error\SyntaxError $e) { + throw new \FOSSBilling\InformationException('Email template syntax error: ' . $e->getMessage()); + } catch (\Twig\Sandbox\SecurityError $e) { + throw new \FOSSBilling\InformationException('Email template contains disallowed Twig syntax: ' . $e->getMessage()); + } + } + public function clearCache(?string $cachePath = null): bool { $path = $cachePath ?? PATH_CACHE;