From 43d3f7b738bbe5674474167070684bda45b18069 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Mon, 23 Nov 2026 15:22:53 +0400 Subject: [PATCH 01/14] update dependencies to Symfony 7.4 and adjust session configuration in test settings --- composer.json | 52 +++++++++---------- config/config.yml | 2 + config/config_dev.yml | 2 +- config/config_test.yml | 4 +- .../Command/ProcessQueueCommandTest.php | 6 +-- 5 files changed, 35 insertions(+), 31 deletions(-) diff --git a/composer.json b/composer.json index 3f2f2db7..a7a9c48a 100644 --- a/composer.json +++ b/composer.json @@ -46,36 +46,36 @@ }, "require": { "php": "^8.2", - "symfony/framework-bundle": "^6.4", - "symfony/dependency-injection": "^6.4", - "symfony/config": "^6.4", - "symfony/yaml": "^6.4", - "symfony/error-handler": "^6.4", - "symfony/serializer": "^6.4", + "symfony/framework-bundle": "^7.4", + "symfony/dependency-injection": "^7.4", + "symfony/config": "^7.4", + "symfony/yaml": "^7.4", + "symfony/error-handler": "^7.4", + "symfony/serializer": "^7.4", "symfony/monolog-bundle": "^3.10", "graylog2/gelf-php": "^2.0", "symfony/serializer-pack": "^1.3", "symfony/orm-pack": "^2.4", "doctrine/orm": "^3.3", "doctrine/cache": "^2.2", - "symfony/asset": "^6.4", - "symfony/security-csrf": "^6.4", - "symfony/form": "^6.4", - "symfony/validator": "^6.4", + "symfony/asset": "^7.4", + "symfony/security-csrf": "^7.4", + "symfony/form": "^7.4", + "symfony/validator": "^7.4", "doctrine/doctrine-fixtures-bundle": "^3.7", "doctrine/instantiator": "^2.0", "masterminds/html5": "^2.9", "ext-dom": "*", "league/csv": "^9.23.0", "doctrine/doctrine-migrations-bundle": "^3.4", - "symfony/mailer": "^6.4", - "symfony/google-mailer": "^6.4", - "symfony/amazon-mailer": "^6.4", - "symfony/mailchimp-mailer": "^6.4", - "symfony/sendgrid-mailer": "^6.4", - "symfony/twig-bundle": "^6.4", - "symfony/messenger": "^6.4", - "symfony/lock": "^6.4", + "symfony/mailer": "^7.4", + "symfony/google-mailer": "^7.4", + "symfony/amazon-mailer": "^7.4", + "symfony/mailchimp-mailer": "^7.4", + "symfony/sendgrid-mailer": "^7.4", + "symfony/twig-bundle": "^7.4", + "symfony/messenger": "^7.4", + "symfony/lock": "^7.4", "webklex/php-imap": "^6.2", "tatevikgr/rss-feed": "dev-main", "ext-imap": "*", @@ -88,8 +88,8 @@ "setasign/fpdf": "^1.8", "phpdocumentor/reflection-docblock": "^5.2", "guzzlehttp/guzzle": "^7.4.5", - "symfony/dotenv": "^6.4", - "symfony/doctrine-messenger": "^6.4", + "symfony/dotenv": "^7.4", + "symfony/doctrine-messenger": "^7.4", "elasticsearch/elasticsearch": "^8.9" }, "require-dev": { @@ -97,15 +97,15 @@ "squizlabs/php_codesniffer": "^3.2.0", "phpstan/phpstan": "^2.2", "nette/caching": "^3.0.0", - "nikic/php-parser": "^4.19.1", + "nikic/php-parser": "^5.1", "phpmd/phpmd": "^2.6.0", "symfony/test-pack": "^1.1", - "symfony/process": "^6.4", + "symfony/process": "^7.4", "composer/composer": "^2.7", - "symfony/http-kernel": "^6.4", - "symfony/http-foundation": "^6.4", - "symfony/routing": "^6.4", - "symfony/console": "^6.4", + "symfony/http-kernel": "^7.4", + "symfony/http-foundation": "^7.4", + "symfony/routing": "^7.4", + "symfony/console": "^7.4", "psr/simple-cache": "^1.0 || ^2.0 || ^3.0", "phpstan/phpstan-doctrine": "^2.0" }, diff --git a/config/config.yml b/config/config.yml index f01f4eeb..ee324464 100644 --- a/config/config.yml +++ b/config/config.yml @@ -18,6 +18,8 @@ framework: router: resource: '%kernel.project_dir%/config/routing.yml' strict_requirements: ~ + property_info: + with_constructor_extractor: true form: ~ csrf_protection: ~ validation: diff --git a/config/config_dev.yml b/config/config_dev.yml index 561d1a43..2d45f2db 100644 --- a/config/config_dev.yml +++ b/config/config_dev.yml @@ -5,7 +5,7 @@ framework: router: resource: '%kernel.project_dir%/config/routing_dev.yml' strict_requirements: true - profiler: { only_exceptions: false } + profiler: { only_exceptions: false, collect_serializer_data: true } monolog: handlers: diff --git a/config/config_test.yml b/config/config_test.yml index c98f659c..3bb755cc 100644 --- a/config/config_test.yml +++ b/config/config_test.yml @@ -4,10 +4,12 @@ imports: framework: test: ~ session: - cookie_domain: session.storage.mock_file + storage_factory_id: session.storage.factory.mock_file handler_id: null + save_path: null profiler: collect: false + collect_serializer_data: true doctrine: dbal: diff --git a/tests/Unit/Domain/Messaging/Command/ProcessQueueCommandTest.php b/tests/Unit/Domain/Messaging/Command/ProcessQueueCommandTest.php index 3f5adf27..140d2a71 100644 --- a/tests/Unit/Domain/Messaging/Command/ProcessQueueCommandTest.php +++ b/tests/Unit/Domain/Messaging/Command/ProcessQueueCommandTest.php @@ -17,7 +17,7 @@ use Symfony\Component\Console\Application; use Symfony\Component\Console\Tester\CommandTester; use Symfony\Component\Lock\LockFactory; -use Symfony\Component\Lock\LockInterface; +use Symfony\Component\Lock\SharedLockInterface; use Symfony\Component\Messenger\Envelope; use Symfony\Component\Messenger\MessageBusInterface; use Symfony\Component\Translation\Translator; @@ -27,7 +27,7 @@ class ProcessQueueCommandTest extends TestCase private MessageRepository&MockObject $messageRepository; private MessageProcessingPreparator&MockObject $messageProcessingPreparator; private MessageBusInterface&MockObject $messageBus; - private LockInterface&MockObject $lock; + private SharedLockInterface&MockObject $lock; private CommandTester $commandTester; private Translator&MockObject $translator; @@ -37,7 +37,7 @@ protected function setUp(): void $lockFactory = $this->createMock(LockFactory::class); $this->messageProcessingPreparator = $this->createMock(MessageProcessingPreparator::class); $this->messageBus = $this->createMock(MessageBusInterface::class); - $this->lock = $this->createMock(LockInterface::class); + $this->lock = $this->createMock(SharedLockInterface::class); $this->translator = $this->createMock(Translator::class); $lockFactory->method('createLock') From c490571f7e7eeb7c82d1c72b7608b699532ca6c9 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Tue, 24 Nov 2026 22:26:20 +0400 Subject: [PATCH 02/14] feat: CLI commands --- config/services/commands.yml | 4 + config/services/services.yml | 4 + .../Analytics/Service/AnalyticsService.php | 16 +- .../Command/CleanUpOldSessionTokens.php | 14 ++ .../Messaging/Command/ProcessQueueCommand.php | 9 + .../Command/SendCampaignsCommand.php | 170 ++++++++++++++++++ src/Domain/Messaging/Command/SendCommand.php | 114 ++++++++++++ .../Messaging/Service/CliCampaignCreator.php | 113 ++++++++++++ .../Command/BlacklistEmailCommand.php | 134 ++++++++++++++ .../Command/ExportSubscribersCommand.php | 134 ++++++++++++++ .../Command/ImportSubscribersCommand.php | 118 ++++++++++++ .../Model/Dto/SubscriberImportOptions.php | 1 + .../Service/SubscriberCsvImporter.php | 2 +- .../Command/SendCampaignsCommandTest.php | 161 +++++++++++++++++ .../Messaging/Command/SendCommandTest.php | 83 +++++++++ .../Service/CliCampaignCreatorTest.php | 158 ++++++++++++++++ .../Command/BlacklistEmailCommandTest.php | 150 ++++++++++++++++ .../Command/ExportSubscribersCommandTest.php | 106 +++++++++++ .../Command/ImportSubscribersCommandTest.php | 117 ++++++++++++ 19 files changed, 1606 insertions(+), 2 deletions(-) create mode 100644 src/Domain/Messaging/Command/SendCampaignsCommand.php create mode 100644 src/Domain/Messaging/Command/SendCommand.php create mode 100644 src/Domain/Messaging/Service/CliCampaignCreator.php create mode 100644 src/Domain/Subscription/Command/BlacklistEmailCommand.php create mode 100644 src/Domain/Subscription/Command/ExportSubscribersCommand.php create mode 100644 src/Domain/Subscription/Command/ImportSubscribersCommand.php create mode 100644 tests/Unit/Domain/Messaging/Command/SendCampaignsCommandTest.php create mode 100644 tests/Unit/Domain/Messaging/Command/SendCommandTest.php create mode 100644 tests/Unit/Domain/Messaging/Service/CliCampaignCreatorTest.php create mode 100644 tests/Unit/Domain/Subscription/Command/BlacklistEmailCommandTest.php create mode 100644 tests/Unit/Domain/Subscription/Command/ExportSubscribersCommandTest.php create mode 100644 tests/Unit/Domain/Subscription/Command/ImportSubscribersCommandTest.php diff --git a/config/services/commands.yml b/config/services/commands.yml index 32b431f6..38154dd4 100644 --- a/config/services/commands.yml +++ b/config/services/commands.yml @@ -16,6 +16,10 @@ services: resource: '../../src/Domain/Search/Command' tags: ['console.command'] + PhpList\Core\Domain\Subscription\Command\: + resource: '../../src/Domain/Subscription/Command' + tags: ['console.command'] + PhpList\Core\Domain\Messaging\Command\ProcessBouncesCommand: arguments: $protocolProcessors: !tagged_iterator 'phplist.bounce_protocol_processor' diff --git a/config/services/services.yml b/config/services/services.yml index 5b19db15..ebe9d982 100644 --- a/config/services/services.yml +++ b/config/services/services.yml @@ -60,6 +60,10 @@ services: autoconfigure: true public: true + PhpList\Core\Domain\Messaging\Service\CliCampaignCreator: + autowire: true + autoconfigure: true + PhpList\Core\Domain\Analytics\Service\LinkTrackService: autowire: true autoconfigure: true diff --git a/src/Domain/Analytics/Service/AnalyticsService.php b/src/Domain/Analytics/Service/AnalyticsService.php index 3fb41d44..d2cebb6e 100644 --- a/src/Domain/Analytics/Service/AnalyticsService.php +++ b/src/Domain/Analytics/Service/AnalyticsService.php @@ -17,7 +17,21 @@ use PhpList\Core\Domain\Subscription\Repository\SubscriberRepository; use Psr\SimpleCache\CacheInterface; -/** @SuppressWarnings("ExcessiveParameterList") */ +/** + * TODO: add the monthly/yearly time-series statistics that phplist3's systemstats page provides and that are + * missing here (legacy: public_html/lists/admin/systemstats.php). Write them with DBAL/DQL date functions that + * work on both MySQL and PostgreSQL (the legacy queries use MySQL-only year()/month()/information_schema): + * - new subscribers per month, and running total of subscribers + * - sent campaigns per month and per year + * - opened messages per month + * - bounces per month + * - blacklist additions per month, and spam complaints per month + * (blacklist reason "blacklisted due to spam complaints") + * - subscribers who clicked per month, and unsubscribe-link clicks per month + * Expose them through the REST API (phplist/rest-api), not a console command. + * + * @SuppressWarnings("ExcessiveParameterList") + */ class AnalyticsService { private const SUMMARY_STATISTICS_CACHE_KEY = 'analytics.summary_statistics'; diff --git a/src/Domain/Identity/Command/CleanUpOldSessionTokens.php b/src/Domain/Identity/Command/CleanUpOldSessionTokens.php index 981a5210..5505ca73 100644 --- a/src/Domain/Identity/Command/CleanUpOldSessionTokens.php +++ b/src/Domain/Identity/Command/CleanUpOldSessionTokens.php @@ -12,6 +12,20 @@ use Symfony\Component\Console\Output\OutputInterface; use Throwable; +/** + * TODO: housekeeping. This is the only cleanup command in core; phplist3 does other housekeeping inside web + * pages, and core has no command for it yet. Decide for each whether it is needed, then add commands (or one + * `phplist:housekeeping` command that runs them all, so a single cron entry is enough): + * - eventlog rows older than a retention period (legacy: the "delete entries older than 2 months" action on + * the eventlog page, eventlog.php; EventLogManager can only delete single entries) + * - unidentified bounces older than 2 months (legacy: bounces.php); not checked whether bounce processing + * here already prunes them + * - other expired tokens, if any (e.g. password reset tokens); not checked whether they are cleaned up + * elsewhere in core + * user_message_view rows: legacy only deletes them together with their message or subscriber (lib.php, + * inc/userlib.php) and never prunes them by age, so an age based cleanup would be new behaviour, not a port. + * Also add the new commands to the scheduling TODO on ProcessQueueCommand. + */ #[AsCommand( name: 'phplist:clean-up-old-session-tokens', description: 'Removes expired administrator session tokens.' diff --git a/src/Domain/Messaging/Command/ProcessQueueCommand.php b/src/Domain/Messaging/Command/ProcessQueueCommand.php index cc960ac3..09d3b5aa 100644 --- a/src/Domain/Messaging/Command/ProcessQueueCommand.php +++ b/src/Domain/Messaging/Command/ProcessQueueCommand.php @@ -21,6 +21,15 @@ use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; +/** + * TODO: scheduling. phplist3 documents putting processqueue and processbounces in the system cron, and core has + * no schedule definition, so users have to write the crontab themselves. Close this with either: + * - a documented crontab example (e.g. in docs/), or + * - a Symfony Scheduler schedule (symfony/scheduler is not installed yet) covering the recurring commands: + * phplist:process-queue, phplist:bounces:process, phplist:update-tlds (monthly) and the cleanup commands such + * as phplist:clean-up-old-session-tokens. + * Keep the existing "queue_processor" lock in mind: a schedule must not start overlapping runs. + */ #[AsCommand( name: 'phplist:process-queue', description: 'Processes the email campaign queue.' diff --git a/src/Domain/Messaging/Command/SendCampaignsCommand.php b/src/Domain/Messaging/Command/SendCampaignsCommand.php new file mode 100644 index 00000000..f9767ea5 --- /dev/null +++ b/src/Domain/Messaging/Command/SendCampaignsCommand.php @@ -0,0 +1,170 @@ +addOption( + 'campaign', + 'c', + InputOption::VALUE_REQUIRED, + 'Only send the submitted campaign with this id' + ); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $campaignId = $this->parseCampaignId($input->getOption('campaign')); + if ($campaignId === false) { + $output->writeln($this->translator->trans('The campaign option must be a positive integer.')); + + return Command::INVALID; + } + + $lock = $this->lockFactory->createLock('queue_processor'); + if (!$lock->acquire()) { + $output->writeln($this->translator->trans('Queue is already being processed by another instance.')); + + return Command::FAILURE; + } + + try { + return $this->sendCampaigns($campaignId, $output); + } catch (Throwable $throwable) { + $output->writeln($throwable->getMessage()); + + return Command::FAILURE; + } finally { + $lock->release(); + } + } + + /** @return int|null|false null when not given, false when invalid */ + private function parseCampaignId(mixed $value): int|false|null + { + if ($value === null) { + return null; + } + + return ctype_digit((string) $value) && (int) $value > 0 ? (int) $value : false; + } + + private function sendCampaigns(?int $campaignId, OutputInterface $output): int + { + if ($this->configProvider->isEnabled(ConfigOption::MaintenanceMode)) { + $output->writeln( + $this->translator->trans('The system is in maintenance mode, stopping. Try again later.') + ); + + return Command::FAILURE; + } + + $this->messagePreparator->ensureSubscribersHaveUuid($output); + $this->messagePreparator->ensureCampaignsHaveUuid($output); + $this->entityManager->flush(); + + $campaigns = $this->findDueCampaigns($campaignId); + if ($campaignId !== null && $campaigns === []) { + $output->writeln( + $this->translator->trans( + 'Campaign %id% is not submitted or its embargo has not passed.', + ['%id%' => $campaignId] + ) + ); + + return Command::FAILURE; + } + + $failed = $this->dispatchAll($campaigns, $output); + $output->writeln( + $this->translator->trans( + 'Finished, processed %count% campaigns.', + ['%count%' => count($campaigns) - $failed] + ) + ); + + return $failed > 0 ? Command::FAILURE : Command::SUCCESS; + } + + private function findDueCampaigns(?int $campaignId): array + { + $campaigns = $this->messageRepository->getByStatusAndEmbargo( + status: MessageStatus::Submitted, + embargo: new DateTimeImmutable() + ); + if ($campaignId === null) { + return $campaigns; + } + + return array_values( + array_filter($campaigns, static fn ($campaign): bool => $campaign->getId() === $campaignId) + ); + } + + /** + * @param array $campaigns + * @return int number of campaigns that could not be dispatched + */ + private function dispatchAll(array $campaigns, OutputInterface $output): int + { + $failed = 0; + foreach ($campaigns as $campaign) { + $id = $campaign->getId(); + $output->writeln($this->translator->trans('Sending campaign %id%', ['%id%' => $id])); + try { + $this->messageBus->dispatch(new SyncCampaignProcessorMessage(messageId: $id)); + } catch (Throwable $throwable) { + ++$failed; + $output->writeln($throwable->getMessage()); + } + } + + return $failed; + } +} diff --git a/src/Domain/Messaging/Command/SendCommand.php b/src/Domain/Messaging/Command/SendCommand.php new file mode 100644 index 00000000..5fb59c84 --- /dev/null +++ b/src/Domain/Messaging/Command/SendCommand.php @@ -0,0 +1,114 @@ +addOption('subject', 's', InputOption::VALUE_REQUIRED, 'Campaign subject') + ->addOption('list', 'l', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'List id or name') + ->addOption('from', 'f', InputOption::VALUE_REQUIRED, 'From field, defaults to the configured sender') + ->addOption('admin', null, InputOption::VALUE_REQUIRED, 'Id of the owning administrator'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $subject = trim((string) $input->getOption('subject')); + $lists = array_values( + array_filter( + array_map('trim', explode(' ', implode(' ', (array) $input->getOption('list')))), + static fn (string $list): bool => $list !== '' + ) + ); + $admin = $input->getOption('admin'); + + if ($subject === '' || $lists === []) { + $output->writeln($this->translator->trans('Usage: -s subject -l list [-f from] < message')); + + return Command::INVALID; + } + if ($admin !== null && !ctype_digit((string) $admin)) { + $output->writeln($this->translator->trans('The admin option must be a positive integer.')); + + return Command::INVALID; + } + + $body = $this->readBody($input); + if (trim($body) === '') { + $output->writeln($this->translator->trans('The message body is empty, pipe it in on stdin.')); + + return Command::INVALID; + } + + try { + $campaign = $this->campaignCreator->create( + subject: $subject, + body: $body, + listReferences: $lists, + from: $input->getOption('from'), + adminId: $admin !== null ? (int) $admin : null, + ); + $this->entityManager->flush(); + } catch (InvalidArgumentException $exception) { + $output->writeln($exception->getMessage()); + + return Command::FAILURE; + } catch (Throwable $throwable) { + $output->writeln($throwable->getMessage()); + + return Command::FAILURE; + } + + $output->writeln( + $this->translator->trans( + 'Campaign "%subject%" (id %id%) was queued for lists: %lists%', + ['%subject%' => $subject, '%id%' => $campaign->getId(), '%lists%' => implode(', ', $lists)] + ) + ); + + return Command::SUCCESS; + } + + private function readBody(InputInterface $input): string + { + $stream = $input instanceof StreamableInputInterface ? $input->getStream() : null; + $contents = stream_get_contents($stream ?? STDIN); + + return $contents === false ? '' : $contents; + } +} diff --git a/src/Domain/Messaging/Service/CliCampaignCreator.php b/src/Domain/Messaging/Service/CliCampaignCreator.php new file mode 100644 index 00000000..cd9bb154 --- /dev/null +++ b/src/Domain/Messaging/Service/CliCampaignCreator.php @@ -0,0 +1,113 @@ +resolveLists($listReferences); + $owner = $this->resolveOwner($adminId); + + $dto = new CreateMessageDto( + content: new MessageContentDto( + subject: $subject, + text: $body, + footer: $this->configProvider->getValue(ConfigOption::MessageFooter) ?? '', + ), + format: new MessageFormatDto(sendFormat: 'HTML'), + metadata: new MessageMetadataDto(status: MessageStatus::Draft), + options: new MessageOptionsDto(fromField: $from ?? $this->defaultFrom()), + schedule: new MessageScheduleDto(embargo: 'now'), + ); + + $message = $this->messageManager->createMessage($dto, $owner); + $this->listMessageManager->associateMessageWithLists($message, $lists); + $this->messageManager->updateStatus($message, MessageStatus::Submitted); + + return $message; + } + + /** + * @return SubscriberList[] + * @throws InvalidArgumentException when a list or the owner cannot be resolved + */ + private function resolveLists(array $references): array + { + $lists = []; + foreach ($references as $reference) { + $reference = trim($reference); + $list = ctype_digit($reference) + ? $this->listRepository->findById((int) $reference) + : $this->listRepository->findOneBy(['name' => $reference]); + if ($list === null) { + throw new InvalidArgumentException(sprintf('List "%s" not found.', $reference)); + } + $lists[$list->getId()] = $list; + } + if ($lists === []) { + throw new InvalidArgumentException('At least one list is required.'); + } + + return array_values($lists); + } + + private function resolveOwner(?int $adminId): Administrator + { + $admin = $adminId !== null + ? $this->administratorRepository->find($adminId) + : $this->administratorRepository->findOneBy([], ['id' => 'ASC']); + if ($admin === null) { + throw new InvalidArgumentException('No administrator found to own the campaign.'); + } + + return $admin; + } + + private function defaultFrom(): string + { + return trim( + ($this->configProvider->getValue(ConfigOption::MessageFromName) ?? '') . ' ' + . ($this->configProvider->getValue(ConfigOption::MessageFromAddress) ?? '') + ); + } +} diff --git a/src/Domain/Subscription/Command/BlacklistEmailCommand.php b/src/Domain/Subscription/Command/BlacklistEmailCommand.php new file mode 100644 index 00000000..370b065c --- /dev/null +++ b/src/Domain/Subscription/Command/BlacklistEmailCommand.php @@ -0,0 +1,134 @@ +" or + * "FAIL" so existing scripts that parse the legacy output keep working. + * + * Deviation: the email is validated, and an unparsable --date is rejected instead of written to SQL. + */ +#[AsCommand( + name: 'phplist:blacklist-email', + description: 'Blacklists an email address (and its subscriber, if any).' +)] +class BlacklistEmailCommand extends Command +{ + private const REASON = 'blacklisted due to spam complaints'; + + public function __construct( + private readonly SubscriberRepository $subscriberRepository, + private readonly SubscriberBlacklistManager $blacklistManager, + private readonly SubscriberBlacklistService $blacklistService, + private readonly EntityManagerInterface $entityManager, + private readonly TranslatorInterface $translator, + ) { + parent::__construct(); + } + + protected function configure(): void + { + $this + ->addOption('email', 'e', InputOption::VALUE_REQUIRED, 'Email address to blacklist') + ->addOption('uid', 'u', InputOption::VALUE_REQUIRED, 'Unique id of the subscriber') + ->addOption('date', 'd', InputOption::VALUE_REQUIRED, 'Date the address was blacklisted (default: now)'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $email = trim((string) $input->getOption('email')); + $uid = trim((string) $input->getOption('uid')); + $date = $this->parseDate($input->getOption('date')); + + if ($date === false || ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL))) { + $output->writeln($this->translator->trans('Invalid email or date.')); + + return Command::INVALID; + } + + $subscriber = $this->findSubscriber($uid, $email); + $address = $subscriber?->getEmail() ?? $email; + if ($address === '') { + $output->writeln('FAIL'); + + return Command::FAILURE; + } + + try { + $this->blacklist($subscriber, $address, $date); + } catch (Throwable $throwable) { + $output->writeln('FAIL'); + $output->writeln($throwable->getMessage()); + + return Command::FAILURE; + } + + $output->writeln('OK ' . $address); + + return Command::SUCCESS; + } + + private function findSubscriber(string $uid, string $email): ?Subscriber + { + $subscriber = $uid !== '' ? $this->subscriberRepository->findOneByUniqueId($uid) : null; + + return $subscriber ?? ($email !== '' ? $this->subscriberRepository->findOneByEmail($email) : null); + } + + private function blacklist(?Subscriber $subscriber, string $address, ?DateTime $date): void + { + if ($this->blacklistManager->isEmailBlacklisted($address)) { + // legacy does this anyway, just to be sure + $subscriber?->setBlacklisted(true); + $this->entityManager->flush(); + + return; + } + + if ($subscriber !== null) { + $this->blacklistService->blacklist($subscriber, self::REASON); + } else { + $this->blacklistManager->addEmailToBlacklist($address, self::REASON); + $this->entityManager->flush(); + } + + if ($date !== null) { + $this->blacklistManager->getBlacklistInfo($address)?->setAdded($date); + $this->entityManager->flush(); + } + } + + /** @return DateTime|false|null false when the value cannot be parsed */ + private function parseDate(mixed $value): DateTime|false|null + { + if ($value === null || $value === '') { + return null; + } + + try { + return new DateTime((string) $value); + } catch (Throwable) { + return false; + } + } +} diff --git a/src/Domain/Subscription/Command/ExportSubscribersCommand.php b/src/Domain/Subscription/Command/ExportSubscribersCommand.php new file mode 100644 index 00000000..dde8655c --- /dev/null +++ b/src/Domain/Subscription/Command/ExportSubscribersCommand.php @@ -0,0 +1,134 @@ +addOption('list', 'l', InputOption::VALUE_REQUIRED, 'Only export subscribers of this list id') + ->addOption('output', 'o', InputOption::VALUE_REQUIRED, 'Write the CSV to this file instead of stdout'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $list = $input->getOption('list'); + $target = $input->getOption('output'); + $error = $this->validate($list, $target); + if ($error !== null) { + $output->writeln($error); + + return Command::INVALID; + } + + try { + $response = $this->exporter->exportToCsv( + new SubscriberFilter(listId: $list !== null ? (int) $list : null, columns: $this->allColumns()) + ); + } catch (Throwable $throwable) { + $output->writeln($throwable->getMessage()); + + return Command::FAILURE; + } + + if (!$response instanceof BinaryFileResponse) { + $output->writeln($this->translator->trans('Export failed.')); + + return Command::FAILURE; + } + + $path = $response->getFile()->getPathname(); + try { + return $target !== null + ? $this->copyToFile($path, (string) $target, $output) + : $this->streamToOutput($path, $output); + } finally { + if (is_file($path)) { + unlink($path); + } + } + } + + private function validate(mixed $list, mixed $target): ?string + { + if ($list !== null && (!ctype_digit((string) $list) || (int) $list < 1)) { + return $this->translator->trans('The list option must be a positive integer.'); + } + if ($target !== null && !is_writable(dirname((string) $target))) { + return $this->translator->trans('Cannot write to %file%', ['%file%' => $target]); + } + + return null; + } + + /** @return string[] */ + private function allColumns(): array + { + $columns = self::BASE_COLUMNS; + foreach ($this->definitionRepository->findAll() as $definition) { + $columns[] = $definition->getName(); + } + + return $columns; + } + + private function copyToFile(string $path, string $target, OutputInterface $output): int + { + if (!copy($path, $target)) { + return Command::FAILURE; + } + $output->writeln($this->translator->trans('Exported subscribers to %file%', ['%file%' => $target])); + + return Command::SUCCESS; + } + + private function streamToOutput(string $path, OutputInterface $output): int + { + $handle = fopen($path, 'rb'); + if ($handle === false) { + return Command::FAILURE; + } + while (!feof($handle)) { + $output->write((string) fread($handle, 65536), false, OutputInterface::OUTPUT_RAW); + } + fclose($handle); + + return Command::SUCCESS; + } +} diff --git a/src/Domain/Subscription/Command/ImportSubscribersCommand.php b/src/Domain/Subscription/Command/ImportSubscribersCommand.php new file mode 100644 index 00000000..c53b47e2 --- /dev/null +++ b/src/Domain/Subscription/Command/ImportSubscribersCommand.php @@ -0,0 +1,118 @@ +addOption('file', 'f', InputOption::VALUE_REQUIRED, 'Path of the CSV file to import') + ->addOption('list', 'l', InputOption::VALUE_REQUIRED, 'Comma separated list ids to add subscribers to') + ->addOption('admin', null, InputOption::VALUE_REQUIRED, 'Id of the administrator recorded in the history') + ->addOption('no-update', null, InputOption::VALUE_NONE, 'Skip subscribers that already exist') + ->addOption('notify', null, InputOption::VALUE_NONE, 'Send confirmation requests to new subscribers') + ->addOption('dry-run', null, InputOption::VALUE_NONE, 'Process the file but do not save anything'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $file = (string) $input->getOption('file'); + if ($file === '' || !is_file($file) || !is_readable($file)) { + $output->writeln($this->translator->trans('Cannot find file to import (hint: use -f)')); + + return Command::INVALID; + } + + $listIds = array_values(array_unique(array_map( + 'intval', + array_filter( + array_map('trim', explode(',', (string) $input->getOption('list'))), + static fn (string $id): bool => ctype_digit($id) && (int) $id > 0 + ) + ))); + if ($listIds === []) { + $output->writeln($this->translator->trans('Specify lists to import subscribers to (hint: use -l 1,2)')); + + return Command::INVALID; + } + + $admin = $this->resolveAdmin($input->getOption('admin')); + if ($admin === false) { + $output->writeln($this->translator->trans('Administrator not found.')); + + return Command::INVALID; + } + + $stats = $this->importer->importFromCsv( + file: new UploadedFile($file, basename($file), null, null, true), + options: new SubscriberImportOptions( + updateExisting: !$input->getOption('no-update'), + listIds: $listIds, + dryRun: (bool) $input->getOption('dry-run'), + notify: (bool) $input->getOption('notify'), + ), + admin: $admin, + ); + + foreach ($stats['errors'] as $error) { + $output->writeln($error); + } + $output->writeln($this->translator->trans( + 'Created: %created%, updated: %updated%, skipped: %skipped%, blacklisted: %blacklisted%', + [ + '%created%' => $stats['created'], + '%updated%' => $stats['updated'], + '%skipped%' => $stats['skipped'], + '%blacklisted%' => $stats['blacklisted'], + ] + )); + + return Command::SUCCESS; + } + + /** @return Administrator|false|null false when an id was given but not found */ + private function resolveAdmin(mixed $adminId): Administrator|false|null + { + if ($adminId === null) { + return null; + } + + return ctype_digit((string) $adminId) + ? ($this->administratorRepository->find((int) $adminId) ?? false) + : false; + } +} diff --git a/src/Domain/Subscription/Model/Dto/SubscriberImportOptions.php b/src/Domain/Subscription/Model/Dto/SubscriberImportOptions.php index 01f92ec2..95a7a1c2 100644 --- a/src/Domain/Subscription/Model/Dto/SubscriberImportOptions.php +++ b/src/Domain/Subscription/Model/Dto/SubscriberImportOptions.php @@ -11,6 +11,7 @@ public function __construct( public readonly array $listIds = [], public readonly bool $dryRun = false, public readonly bool $skipInvalidEmail = true, + public readonly bool $notify = true, ) { } } diff --git a/src/Domain/Subscription/Service/SubscriberCsvImporter.php b/src/Domain/Subscription/Service/SubscriberCsvImporter.php index 18ee26a1..4b7e8cbd 100644 --- a/src/Domain/Subscription/Service/SubscriberCsvImporter.php +++ b/src/Domain/Subscription/Service/SubscriberCsvImporter.php @@ -266,7 +266,7 @@ private function prepareConfirmationMessage( ImportSubscriberDto $dto, bool $addedNewSubscriberToList ): ?SubscriptionConfirmationMessage { - if ($dto->sendConfirmation && $addedNewSubscriberToList) { + if ($options->notify && $dto->sendConfirmation && $addedNewSubscriberToList) { return new SubscriptionConfirmationMessage( email: $subscriber->getEmail(), uniqueId: $subscriber->getUniqueId(), diff --git a/tests/Unit/Domain/Messaging/Command/SendCampaignsCommandTest.php b/tests/Unit/Domain/Messaging/Command/SendCampaignsCommandTest.php new file mode 100644 index 00000000..ac557faf --- /dev/null +++ b/tests/Unit/Domain/Messaging/Command/SendCampaignsCommandTest.php @@ -0,0 +1,161 @@ +messageRepository = $this->createMock(MessageRepository::class); + $this->messageBus = $this->createMock(MessageBusInterface::class); + $this->lock = $this->createMock(SharedLockInterface::class); + $this->configProvider = $this->createMock(ConfigProvider::class); + $lockFactory = $this->createMock(LockFactory::class); + $lockFactory->method('createLock')->with('queue_processor')->willReturn($this->lock); + + $translator = $this->createMock(TranslatorInterface::class); + $translator->method('trans')->willReturnArgument(0); + + $this->tester = new CommandTester(new SendCampaignsCommand( + $this->messageRepository, + $lockFactory, + $this->createMock(MessageProcessingPreparator::class), + $this->messageBus, + $this->configProvider, + $translator, + $this->createMock(EntityManagerInterface::class), + )); + } + + private function campaign(int $id): Message&MockObject + { + $campaign = $this->createMock(Message::class); + $campaign->method('getId')->willReturn($id); + + return $campaign; + } + + public function testFailsWhenLocked(): void + { + $this->lock->method('acquire')->willReturn(false); + $this->messageBus->expects($this->never())->method('dispatch'); + + $this->tester->execute([]); + + $this->assertSame(1, $this->tester->getStatusCode()); + } + + public function testStopsInMaintenanceModeAndReleasesLock(): void + { + $this->lock->method('acquire')->willReturn(true); + $this->lock->expects($this->once())->method('release'); + $this->configProvider->method('isEnabled')->willReturn(true); + $this->messageBus->expects($this->never())->method('dispatch'); + + $this->tester->execute([]); + + $this->assertSame(1, $this->tester->getStatusCode()); + } + + public function testRejectsInvalidCampaignOption(): void + { + $this->lock->expects($this->never())->method('acquire'); + + $this->tester->execute(['--campaign' => 'abc']); + + $this->assertSame(2, $this->tester->getStatusCode()); + } + + public function testSendsAllDueCampaignsSynchronously(): void + { + $this->lock->method('acquire')->willReturn(true); + $this->lock->expects($this->once())->method('release'); + $this->messageRepository->method('getByStatusAndEmbargo') + ->willReturn([$this->campaign(1), $this->campaign(2)]); + + $ids = []; + $this->messageBus->expects($this->exactly(2))->method('dispatch') + ->willReturnCallback(function (SyncCampaignProcessorMessage $message) use (&$ids) { + $ids[] = $message->getMessageId(); + + return new Envelope($message); + }); + + $this->tester->execute([]); + + $this->assertSame([1, 2], $ids); + $this->assertSame(0, $this->tester->getStatusCode()); + } + + public function testCampaignOptionLimitsToOneCampaign(): void + { + $this->lock->method('acquire')->willReturn(true); + $this->messageRepository->method('getByStatusAndEmbargo') + ->willReturn([$this->campaign(1), $this->campaign(2)]); + + $this->messageBus->expects($this->once())->method('dispatch') + ->with($this->callback(fn (SyncCampaignProcessorMessage $m) => $m->getMessageId() === 2)) + ->willReturn(new Envelope(new SyncCampaignProcessorMessage(2))); + + $this->tester->execute(['--campaign' => '2']); + + $this->assertSame(0, $this->tester->getStatusCode()); + } + + public function testUnknownCampaignFails(): void + { + $this->lock->method('acquire')->willReturn(true); + $this->lock->expects($this->once())->method('release'); + $this->messageRepository->method('getByStatusAndEmbargo')->willReturn([$this->campaign(1)]); + $this->messageBus->expects($this->never())->method('dispatch'); + + $this->tester->execute(['--campaign' => '9']); + + $this->assertSame(1, $this->tester->getStatusCode()); + } + + public function testDispatchFailureContinuesAndReturnsFailure(): void + { + $this->lock->method('acquire')->willReturn(true); + $this->messageRepository->method('getByStatusAndEmbargo') + ->willReturn([$this->campaign(1), $this->campaign(2)]); + $this->messageBus->expects($this->exactly(2))->method('dispatch') + ->willReturnCallback(function (SyncCampaignProcessorMessage $message) { + if ($message->getMessageId() === 1) { + throw new Exception('boom'); + } + + return new Envelope($message); + }); + + $this->tester->execute([]); + + $this->assertSame(1, $this->tester->getStatusCode()); + $this->assertStringContainsString('boom', $this->tester->getDisplay()); + } +} diff --git a/tests/Unit/Domain/Messaging/Command/SendCommandTest.php b/tests/Unit/Domain/Messaging/Command/SendCommandTest.php new file mode 100644 index 00000000..ce4f317c --- /dev/null +++ b/tests/Unit/Domain/Messaging/Command/SendCommandTest.php @@ -0,0 +1,83 @@ +creator = $this->createMock(CliCampaignCreator::class); + $this->entityManager = $this->createMock(EntityManagerInterface::class); + $translator = $this->createMock(TranslatorInterface::class); + $translator->method('trans')->willReturnCallback( + static fn (string $id, array $params = []) => strtr($id, $params) + ); + $this->tester = new CommandTester(new SendCommand($this->creator, $translator, $this->entityManager)); + } + + public function testRequiresSubjectAndList(): void + { + $this->creator->expects($this->never())->method('create'); + + $this->tester->execute(['--subject' => 'Hi']); + + $this->assertSame(2, $this->tester->getStatusCode()); + } + + public function testRejectsEmptyBody(): void + { + $this->creator->expects($this->never())->method('create'); + + $this->tester->setInputs([]); + $this->tester->execute(['--subject' => 'Hi', '--list' => ['1']]); + + $this->assertSame(2, $this->tester->getStatusCode()); + } + + public function testCreatesAndQueuesCampaignFromStdin(): void + { + $campaign = $this->createMock(Message::class); + $campaign->method('getId')->willReturn(7); + + $this->creator->expects($this->once())->method('create') + ->with('Hi', "Hello world\n", ['1', 'News'], 'Me ', null) + ->willReturn($campaign); + + $this->tester->setInputs(['Hello world']); + $this->tester->execute([ + '--subject' => 'Hi', + '--list' => ['1', 'News'], + '--from' => 'Me ', + ]); + + $this->assertSame(0, $this->tester->getStatusCode()); + $this->assertStringContainsString('id 7', $this->tester->getDisplay()); + } + + public function testUnknownListFails(): void + { + $this->creator->method('create')->willThrowException(new InvalidArgumentException('List "x" not found.')); + + $this->tester->setInputs(['body']); + $this->tester->execute(['--subject' => 'Hi', '--list' => ['x']]); + + $this->assertSame(1, $this->tester->getStatusCode()); + $this->assertStringContainsString('not found', $this->tester->getDisplay()); + } +} diff --git a/tests/Unit/Domain/Messaging/Service/CliCampaignCreatorTest.php b/tests/Unit/Domain/Messaging/Service/CliCampaignCreatorTest.php new file mode 100644 index 00000000..938ea227 --- /dev/null +++ b/tests/Unit/Domain/Messaging/Service/CliCampaignCreatorTest.php @@ -0,0 +1,158 @@ +messageManager = $this->createMock(MessageManager::class); + $this->listMessageManager = $this->createMock(ListMessageManager::class); + $this->listRepository = $this->createMock(SubscriberListRepository::class); + $this->administratorRepository = $this->createMock(AdministratorRepository::class); + $this->configProvider = $this->createMock(ConfigProvider::class); + + $this->creator = new CliCampaignCreator( + $this->messageManager, + $this->listMessageManager, + $this->listRepository, + $this->administratorRepository, + $this->configProvider, + ); + } + + private function list(int $id): SubscriberList&MockObject + { + $list = $this->createMock(SubscriberList::class); + $list->method('getId')->willReturn($id); + + return $list; + } + + public function testCreatesAndSubmitsCampaignWithListsFromIdAndName(): void + { + $byId = $this->list(1); + $byName = $this->list(2); + $admin = $this->createMock(Administrator::class); + $message = $this->createMock(Message::class); + + $this->listRepository->method('findById')->with(1)->willReturn($byId); + $this->listRepository->method('findOneBy')->with(['name' => 'Weekly'])->willReturn($byName); + $this->administratorRepository->method('findOneBy')->with([], ['id' => 'ASC'])->willReturn($admin); + $this->configProvider->method('getValue')->willReturnMap([ + [ConfigOption::MessageFooter, 'the footer'], + [ConfigOption::MessageFromName, 'News'], + [ConfigOption::MessageFromAddress, 'news@example.com'], + ]); + + $this->messageManager->expects($this->once())->method('createMessage') + ->with( + $this->callback(function (CreateMessageDto $dto): bool { + $this->assertSame('Subject', $dto->getContent()->subject); + $this->assertSame('

Body

', $dto->getContent()->text); + $this->assertSame('the footer', $dto->getContent()->footer); + $this->assertSame('News news@example.com', $dto->getOptions()->fromField); + $this->assertSame('now', $dto->getSchedule()->embargo); + + return true; + }), + $admin + ) + ->willReturn($message); + $this->listMessageManager->expects($this->once())->method('associateMessageWithLists') + ->with($message, [$byId, $byName]); + $this->messageManager->expects($this->once())->method('updateStatus') + ->with($message, MessageStatus::Submitted); + + $result = $this->creator->create('Subject', '

Body

', ['1', 'Weekly']); + + $this->assertSame($message, $result); + } + + public function testUsesGivenFromAndAdmin(): void + { + $admin = $this->createMock(Administrator::class); + $this->listRepository->method('findById')->willReturn($this->list(1)); + $this->administratorRepository->expects($this->once())->method('find')->with(5)->willReturn($admin); + $this->administratorRepository->expects($this->never())->method('findOneBy'); + $this->messageManager->method('createMessage') + ->with( + $this->callback(fn (CreateMessageDto $dto) => $dto->getOptions()->fromField === 'Me '), + $admin + ) + ->willReturn($this->createMock(Message::class)); + + $this->creator->create('S', 'B', ['1'], 'Me ', 5); + } + + public function testDuplicateListReferencesAreAssociatedOnce(): void + { + $list = $this->list(1); + $this->listRepository->method('findById')->willReturn($list); + $this->listRepository->method('findOneBy')->willReturn($list); + $this->administratorRepository->method('findOneBy')->willReturn($this->createMock(Administrator::class)); + $this->messageManager->method('createMessage')->willReturn($this->createMock(Message::class)); + + $this->listMessageManager->expects($this->once())->method('associateMessageWithLists') + ->with($this->anything(), [$list]); + + $this->creator->create('S', 'B', ['1', 'Same']); + } + + public function testUnknownListThrowsAndCreatesNothing(): void + { + $this->listRepository->method('findOneBy')->willReturn(null); + $this->messageManager->expects($this->never())->method('createMessage'); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('List "Nope" not found.'); + + $this->creator->create('S', 'B', ['Nope']); + } + + public function testNoListsThrows(): void + { + $this->messageManager->expects($this->never())->method('createMessage'); + + $this->expectException(InvalidArgumentException::class); + + $this->creator->create('S', 'B', []); + } + + public function testMissingAdministratorThrowsAndCreatesNothing(): void + { + $this->listRepository->method('findById')->willReturn($this->list(1)); + $this->administratorRepository->method('findOneBy')->willReturn(null); + $this->messageManager->expects($this->never())->method('createMessage'); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('No administrator found'); + + $this->creator->create('S', 'B', ['1']); + } +} diff --git a/tests/Unit/Domain/Subscription/Command/BlacklistEmailCommandTest.php b/tests/Unit/Domain/Subscription/Command/BlacklistEmailCommandTest.php new file mode 100644 index 00000000..47d58c9c --- /dev/null +++ b/tests/Unit/Domain/Subscription/Command/BlacklistEmailCommandTest.php @@ -0,0 +1,150 @@ +subscribers = $this->createMock(SubscriberRepository::class); + $this->manager = $this->createMock(SubscriberBlacklistManager::class); + $this->service = $this->createMock(SubscriberBlacklistService::class); + $this->entityManager = $this->createMock(EntityManagerInterface::class); + $translator = $this->createMock(TranslatorInterface::class); + $translator->method('trans')->willReturnArgument(0); + $this->tester = new CommandTester(new BlacklistEmailCommand( + $this->subscribers, + $this->manager, + $this->service, + $this->entityManager, + $translator, + )); + } + + private function subscriber(string $email): Subscriber&MockObject + { + $subscriber = $this->createMock(Subscriber::class); + $subscriber->method('getEmail')->willReturn($email); + + return $subscriber; + } + + public function testFailsWithoutEmailOrKnownSubscriber(): void + { + $this->subscribers->method('findOneByUniqueId')->willReturn(null); + $this->service->expects($this->never())->method('blacklist'); + + $this->tester->execute(['--uid' => 'unknown']); + + $this->assertSame(1, $this->tester->getStatusCode()); + $this->assertStringContainsString('FAIL', $this->tester->getDisplay()); + } + + public function testRejectsInvalidEmail(): void + { + $this->service->expects($this->never())->method('blacklist'); + + $this->tester->execute(['--email' => 'not-an-email']); + + $this->assertSame(2, $this->tester->getStatusCode()); + } + + public function testRejectsInvalidDate(): void + { + $this->service->expects($this->never())->method('blacklist'); + + $this->tester->execute(['--email' => 'a@example.com', '--date' => 'not a date at all']); + + $this->assertSame(2, $this->tester->getStatusCode()); + } + + public function testBlacklistsKnownSubscriberFoundByUid(): void + { + $subscriber = $this->subscriber('a@example.com'); + $this->subscribers->method('findOneByUniqueId')->with('uid1')->willReturn($subscriber); + $this->manager->method('isEmailBlacklisted')->willReturn(false); + $this->service->expects($this->once())->method('blacklist') + ->with($subscriber, 'blacklisted due to spam complaints'); + + $this->tester->execute(['--uid' => 'uid1']); + + $this->assertSame(0, $this->tester->getStatusCode()); + $this->assertStringContainsString('OK a@example.com', $this->tester->getDisplay()); + } + + public function testBlacklistsUnknownAddressWithEntryOnly(): void + { + $this->subscribers->method('findOneByEmail')->willReturn(null); + $this->manager->method('isEmailBlacklisted')->willReturn(false); + $this->service->expects($this->never())->method('blacklist'); + $this->manager->expects($this->once())->method('addEmailToBlacklist') + ->with('b@example.com', 'blacklisted due to spam complaints'); + + $this->tester->execute(['--email' => 'b@example.com']); + + $this->assertSame(0, $this->tester->getStatusCode()); + $this->assertStringContainsString('OK b@example.com', $this->tester->getDisplay()); + } + + public function testAlreadyBlacklistedOnlyEnsuresFlag(): void + { + $subscriber = $this->subscriber('a@example.com'); + $subscriber->expects($this->once())->method('setBlacklisted')->with(true); + $this->subscribers->method('findOneByEmail')->willReturn($subscriber); + $this->manager->method('isEmailBlacklisted')->willReturn(true); + $this->service->expects($this->never())->method('blacklist'); + $this->manager->expects($this->never())->method('addEmailToBlacklist'); + + $this->tester->execute(['--email' => 'a@example.com']); + + $this->assertSame(0, $this->tester->getStatusCode()); + $this->assertStringContainsString('OK a@example.com', $this->tester->getDisplay()); + } + + public function testDateIsAppliedToBlacklistEntry(): void + { + $this->subscribers->method('findOneByEmail')->willReturn(null); + $this->manager->method('isEmailBlacklisted')->willReturn(false); + $entry = $this->createMock(UserBlacklist::class); + $entry->expects($this->once())->method('setAdded') + ->with($this->callback(fn (\DateTime $d) => $d->format('Y-m-d') === '2024-02-03')); + $this->manager->method('getBlacklistInfo')->with('b@example.com')->willReturn($entry); + + $this->tester->execute(['--email' => 'b@example.com', '--date' => '2024-02-03']); + + $this->assertSame(0, $this->tester->getStatusCode()); + } + + public function testFailureIsReported(): void + { + $this->subscribers->method('findOneByEmail')->willReturn(null); + $this->manager->method('isEmailBlacklisted')->willReturn(false); + $this->manager->method('addEmailToBlacklist')->willThrowException(new Exception('db down')); + + $this->tester->execute(['--email' => 'b@example.com']); + + $this->assertSame(1, $this->tester->getStatusCode()); + $this->assertStringContainsString('db down', $this->tester->getDisplay()); + } +} diff --git a/tests/Unit/Domain/Subscription/Command/ExportSubscribersCommandTest.php b/tests/Unit/Domain/Subscription/Command/ExportSubscribersCommandTest.php new file mode 100644 index 00000000..8e44f6d6 --- /dev/null +++ b/tests/Unit/Domain/Subscription/Command/ExportSubscribersCommandTest.php @@ -0,0 +1,106 @@ +exporter = $this->createMock(SubscriberCsvExporter::class); + $this->definitions = $this->createMock(SubscriberAttributeDefinitionRepository::class); + $translator = $this->createMock(TranslatorInterface::class); + $translator->method('trans')->willReturnCallback(static fn (string $id, array $p = []) => strtr($id, $p)); + $this->tester = new CommandTester( + new ExportSubscribersCommand($this->exporter, $this->definitions, $translator) + ); + } + + private function csvResponse(string $contents): BinaryFileResponse + { + $path = tempnam(sys_get_temp_dir(), 'exp'); + file_put_contents($path, $contents); + + return new BinaryFileResponse($path); + } + + public function testInvalidListIsRejected(): void + { + $this->exporter->expects($this->never())->method('exportToCsv'); + + $this->tester->execute(['--list' => 'x']); + + $this->assertSame(2, $this->tester->getStatusCode()); + } + + public function testUnwritableOutputIsRejected(): void + { + $this->exporter->expects($this->never())->method('exportToCsv'); + + $this->tester->execute(['--output' => '/no/such/dir/out.csv']); + + $this->assertSame(2, $this->tester->getStatusCode()); + } + + public function testExportsAllColumnsIncludingAttributesToStdout(): void + { + $definition = $this->createMock(SubscriberAttributeDefinition::class); + $definition->method('getName')->willReturn('Country'); + $this->definitions->method('findAll')->willReturn([$definition]); + + $this->exporter->expects($this->once())->method('exportToCsv') + ->with($this->callback(function (SubscriberFilter $f): bool { + return $f->getListId() === 4 + && in_array('email', $f->getColumns(), true) + && in_array('Country', $f->getColumns(), true); + })) + ->willReturn($this->csvResponse("id,email\n1,a@example.com\n")); + + $this->tester->execute(['--list' => '4']); + + $this->assertSame(0, $this->tester->getStatusCode()); + $this->assertSame("id,email\n1,a@example.com\n", $this->tester->getDisplay()); + } + + public function testWritesToOutputFile(): void + { + $this->definitions->method('findAll')->willReturn([]); + $this->exporter->method('exportToCsv')->willReturn($this->csvResponse("id\n1\n")); + $target = tempnam(sys_get_temp_dir(), 'out'); + + $this->tester->execute(['--output' => $target]); + + $this->assertSame(0, $this->tester->getStatusCode()); + $this->assertSame("id\n1\n", file_get_contents($target)); + if (is_file($target)) { + unlink($target); + } + } + + public function testNonFileResponseFails(): void + { + $this->definitions->method('findAll')->willReturn([]); + $this->exporter->method('exportToCsv')->willReturn(new Response()); + + $this->tester->execute([]); + + $this->assertSame(1, $this->tester->getStatusCode()); + } +} diff --git a/tests/Unit/Domain/Subscription/Command/ImportSubscribersCommandTest.php b/tests/Unit/Domain/Subscription/Command/ImportSubscribersCommandTest.php new file mode 100644 index 00000000..d5b7dead --- /dev/null +++ b/tests/Unit/Domain/Subscription/Command/ImportSubscribersCommandTest.php @@ -0,0 +1,117 @@ +importer = $this->createMock(SubscriberCsvImporter::class); + $this->adminRepository = $this->createMock(AdministratorRepository::class); + $translator = $this->createMock(TranslatorInterface::class); + $translator->method('trans')->willReturnCallback(static fn (string $id, array $p = []) => strtr($id, $p)); + $this->tester = new CommandTester( + new ImportSubscribersCommand($this->importer, $this->adminRepository, $translator) + ); + $this->csv = tempnam(sys_get_temp_dir(), 'imp'); + file_put_contents($this->csv, "email\na@example.com\n"); + } + + protected function tearDown(): void + { + if (is_file($this->csv)) { + unlink($this->csv); + } + } + + private function stats(array $override = []): array + { + return $override + ['created' => 1, 'updated' => 0, 'skipped' => 0, 'blacklisted' => 0, + 'invalid_email' => 0, 'errors' => []]; + } + + public function testMissingFileIsInvalid(): void + { + $this->importer->expects($this->never())->method('importFromCsv'); + + $this->tester->execute(['--file' => '/no/such/file.csv', '--list' => '1']); + + $this->assertSame(2, $this->tester->getStatusCode()); + } + + public function testMissingListsIsInvalid(): void + { + $this->importer->expects($this->never())->method('importFromCsv'); + + $this->tester->execute(['--file' => $this->csv, '--list' => 'abc,0']); + + $this->assertSame(2, $this->tester->getStatusCode()); + } + + public function testUnknownAdminIsInvalid(): void + { + $this->adminRepository->method('find')->with(9)->willReturn(null); + $this->importer->expects($this->never())->method('importFromCsv'); + + $this->tester->execute(['--file' => $this->csv, '--list' => '1', '--admin' => '9']); + + $this->assertSame(2, $this->tester->getStatusCode()); + } + + public function testImportsWithLegacyCliDefaults(): void + { + $this->importer->expects($this->once())->method('importFromCsv') + ->with( + $this->callback(fn (UploadedFile $f) => $f->getRealPath() === realpath($this->csv)), + $this->callback(function (SubscriberImportOptions $o): bool { + return $o->listIds === [1, 2] && $o->updateExisting && $o->skipInvalidEmail + && !$o->notify && !$o->dryRun; + }), + null + ) + ->willReturn($this->stats()); + + $this->tester->execute(['--file' => $this->csv, '--list' => '1, 2,2']); + + $this->assertSame(0, $this->tester->getStatusCode()); + $this->assertStringContainsString('Created: 1', $this->tester->getDisplay()); + } + + public function testFlagsAndAdminArePassedAndErrorsPrinted(): void + { + $admin = $this->createMock(Administrator::class); + $this->adminRepository->method('find')->with(3)->willReturn($admin); + $this->importer->expects($this->once())->method('importFromCsv') + ->with( + $this->anything(), + $this->callback(fn (SubscriberImportOptions $o) => !$o->updateExisting && $o->notify && $o->dryRun), + $admin + ) + ->willReturn($this->stats(['errors' => ['Line 2: bad']])); + + $this->tester->execute([ + '--file' => $this->csv, '--list' => '1', '--admin' => '3', + '--no-update' => true, '--notify' => true, '--dry-run' => true, + ]); + + $this->assertStringContainsString('Line 2: bad', $this->tester->getDisplay()); + } +} From bd85fa14635d65d173b12e79d69244a43f6c3093 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Wed, 25 Nov 2026 17:09:24 +0400 Subject: [PATCH 03/14] feat: add EmailTldValidator and TldListService for email domain validatio --- config/services/services.yml | 8 + resources/tlds-alpha-by-domain.txt | 1436 +++++++++++++++++ .../Configuration/Model/ConfigOption.php | 2 + .../Command/UpdateTldsCommand.php | 52 + .../Model/Dto/TldRefreshResult.php | 28 + .../Service/EmailTldValidator.php | 37 + .../Service/SubscriberCsvImporter.php | 3 +- .../Subscription/Service/TldListService.php | 185 +++ .../Command/UpdateTldsCommandTest.php | 60 + .../Service/EmailTldValidatorTest.php | 46 + .../Service/SubscriberCsvImporterTest.php | 104 ++ .../Service/TldListServiceTest.php | 178 ++ 12 files changed, 2138 insertions(+), 1 deletion(-) create mode 100644 resources/tlds-alpha-by-domain.txt create mode 100644 src/Domain/Subscription/Command/UpdateTldsCommand.php create mode 100644 src/Domain/Subscription/Model/Dto/TldRefreshResult.php create mode 100644 src/Domain/Subscription/Service/EmailTldValidator.php create mode 100644 src/Domain/Subscription/Service/TldListService.php create mode 100644 tests/Unit/Domain/Subscription/Command/UpdateTldsCommandTest.php create mode 100644 tests/Unit/Domain/Subscription/Service/EmailTldValidatorTest.php create mode 100644 tests/Unit/Domain/Subscription/Service/TldListServiceTest.php diff --git a/config/services/services.yml b/config/services/services.yml index ebe9d982..7b97a054 100644 --- a/config/services/services.yml +++ b/config/services/services.yml @@ -9,6 +9,14 @@ services: autoconfigure: true public: true + PhpList\Core\Domain\Subscription\Service\TldListService: + autowire: true + autoconfigure: true + + PhpList\Core\Domain\Subscription\Service\EmailTldValidator: + autowire: true + autoconfigure: true + PhpList\Core\Domain\Subscription\Service\SubscriberCsvImporter: autowire: true autoconfigure: true diff --git a/resources/tlds-alpha-by-domain.txt b/resources/tlds-alpha-by-domain.txt new file mode 100644 index 00000000..5c3160e7 --- /dev/null +++ b/resources/tlds-alpha-by-domain.txt @@ -0,0 +1,1436 @@ +# Version 2026112302, Last Updated Tue Nov 24 07:07:02 2026 UTC +AAA +AARP +ABB +ABBOTT +ABBVIE +ABC +ABLE +ABOGADO +ABUDHABI +AC +ACADEMY +ACCENTURE +ACCOUNTANT +ACCOUNTANTS +ACO +ACTOR +AD +ADS +ADULT +AE +AEG +AERO +AETNA +AF +AFL +AFRICA +AG +AGAKHAN +AGENCY +AI +AIG +AIRBUS +AIRFORCE +AIRTEL +AKDN +AL +ALIBABA +ALIPAY +ALLFINANZ +ALLSTATE +ALLY +ALSACE +ALSTOM +AM +AMAZON +AMERICANEXPRESS +AMERICANFAMILY +AMEX +AMFAM +AMICA +AMSTERDAM +ANALYTICS +ANDROID +ANQUAN +ANZ +AO +AOL +APARTMENTS +APP +APPLE +AQ +AQUARELLE +AR +ARAB +ARAMCO +ARCHI +ARMY +ARPA +ART +ARTE +AS +ASDA +ASIA +ASSOCIATES +AT +ATHLETA +ATTORNEY +AU +AUCTION +AUDI +AUDIBLE +AUDIO +AUSPOST +AUTHOR +AUTO +AUTOS +AW +AWS +AX +AXA +AZ +AZURE +BA +BABY +BAIDU +BANAMEX +BAND +BANK +BAR +BARCELONA +BARCLAYCARD +BARCLAYS +BAREFOOT +BARGAINS +BASEBALL +BASKETBALL +BAUHAUS +BAYERN +BB +BBC +BBT +BBVA +BCG +BCN +BD +BE +BEATS +BEAUTY +BEER +BERLIN +BEST +BESTBUY +BET +BF +BG +BH +BHARTI +BI +BIBLE +BID +BIKE +BING +BINGO +BIO +BIZ +BJ +BLACK +BLACKFRIDAY +BLOCKBUSTER +BLOG +BLOOMBERG +BLUE +BM +BMS +BMW +BN +BNPPARIBAS +BO +BOATS +BOEHRINGER +BOFA +BOM +BOND +BOO +BOOK +BOOKING +BOSCH +BOSTIK +BOSTON +BOT +BOUTIQUE +BOX +BR +BRADESCO +BRIDGESTONE +BROADWAY +BROKER +BROTHER +BRUSSELS +BS +BT +BUILD +BUILDERS +BUSINESS +BUY +BUZZ +BV +BW +BY +BZ +BZH +CA +CAB +CAFE +CAL +CALL +CALVINKLEIN +CAM +CAMERA +CAMP +CANON +CAPETOWN +CAPITAL +CAPITALONE +CAR +CARAVAN +CARDS +CARE +CAREER +CAREERS +CARS +CASA +CASE +CASH +CASINO +CAT +CATERING +CATHOLIC +CBA +CBN +CBRE +CC +CD +CENTER +CEO +CERN +CF +CFA +CFD +CG +CH +CHANEL +CHANNEL +CHARITY +CHASE +CHAT +CHEAP +CHINTAI +CHRISTMAS +CHROME +CHURCH +CI +CIPRIANI +CIRCLE +CISCO +CITADEL +CITI +CITIC +CITY +CK +CL +CLAIMS +CLEANING +CLICK +CLINIC +CLINIQUE +CLOTHING +CLOUD +CLUB +CLUBMED +CM +CN +CO +COACH +CODES +COFFEE +COLLEGE +COLOGNE +COM +COMMBANK +COMMUNITY +COMPANY +COMPARE +COMPUTER +COMSEC +CONDOS +CONSTRUCTION +CONSULTING +CONTACT +CONTRACTORS +COOKING +COOL +COOP +CORSICA +COUNTRY +COUPON +COUPONS +COURSES +CPA +CR +CREDIT +CREDITCARD +CREDITUNION +CRICKET +CROWN +CRS +CRUISE +CRUISES +CU +CUISINELLA +CV +CW +CX +CY +CYMRU +CYOU +CZ +DAD +DANCE +DATA +DATE +DATING +DATSUN +DAY +DCLK +DDS +DE +DEAL +DEALER +DEALS +DEGREE +DELIVERY +DELL +DELOITTE +DELTA +DEMOCRAT +DENTAL +DENTIST +DESI +DESIGN +DEV +DHL +DIAMONDS +DIET +DIGITAL +DIRECT +DIRECTORY +DISCOUNT +DISCOVER +DISH +DIY +DJ +DK +DM +DNP +DO +DOCS +DOCTOR +DOG +DOMAINS +DOT +DOWNLOAD +DRIVE +DTV +DUBAI +DUPONT +DURBAN +DVAG +DVR +DZ +EARTH +EAT +EC +ECO +EDEKA +EDU +EDUCATION +EE +EG +EMAIL +EMERCK +ENERGY +ENGINEER +ENGINEERING +ENTERPRISES +EPSON +EQUIPMENT +ER +ERICSSON +ERNI +ES +ESQ +ESTATE +ET +EU +EUROVISION +EUS +EVENTS +EXCHANGE +EXPERT +EXPOSED +EXPRESS +EXTRASPACE +FAGE +FAIL +FAIRWINDS +FAITH +FAMILY +FAN +FANS +FARM +FARMERS +FASHION +FAST +FEDEX +FEEDBACK +FERRARI +FERRERO +FI +FIDELITY +FIDO +FILM +FINAL +FINANCE +FINANCIAL +FIRE +FIRESTONE +FIRMDALE +FISH +FISHING +FIT +FITNESS +FJ +FK +FLICKR +FLIGHTS +FLIR +FLORIST +FLOWERS +FLY +FM +FO +FOO +FOOD +FOOTBALL +FORD +FOREX +FORSALE +FORUM +FOUNDATION +FOX +FR +FREE +FRESENIUS +FRL +FROGANS +FRONTIER +FTR +FUJITSU +FUN +FUND +FURNITURE +FUTBOL +FYI +GA +GAL +GALLERY +GALLO +GALLUP +GAME +GAMES +GAP +GARDEN +GAY +GB +GBIZ +GD +GDN +GE +GEA +GENT +GENTING +GEORGE +GF +GG +GGEE +GH +GI +GIFT +GIFTS +GIVES +GIVING +GL +GLASS +GLE +GLOBAL +GLOBO +GM +GMAIL +GMBH +GMO +GMX +GN +GODADDY +GOLD +GOLDPOINT +GOLF +GOODYEAR +GOOG +GOOGLE +GOP +GOT +GOV +GP +GQ +GR +GRAINGER +GRAPHICS +GRATIS +GREEN +GRIPE +GROCERY +GROUP +GS +GT +GU +GUCCI +GUGE +GUIDE +GUITARS +GURU +GW +GY +HAIR +HAMBURG +HANGOUT +HAUS +HBO +HDFC +HDFCBANK +HEALTH +HEALTHCARE +HELP +HERE +HERMES +HIPHOP +HISAMITSU +HITACHI +HIV +HK +HKT +HM +HN +HOCKEY +HOLDINGS +HOLIDAY +HOMEDEPOT +HOMEGOODS +HOMES +HOMESENSE +HONDA +HORSE +HOSPITAL +HOST +HOSTING +HOT +HOTELS +HOTMAIL +HOUSE +HOW +HR +HSBC +HT +HU +HUGHES +HYATT +HYUNDAI +IBM +ICBC +ICE +ICU +ID +IE +IEEE +IFM +IKANO +IL +IM +IMAMAT +IMDB +IMMO +IMMOBILIEN +IN +INC +INDUSTRIES +INFINITI +INFO +ING +INK +INSTITUTE +INSURANCE +INSURE +INT +INTERNATIONAL +INTUIT +INVESTMENTS +IO +IPIRANGA +IQ +IR +IRISH +IS +ISMAILI +IST +ISTANBUL +IT +ITAU +ITV +JAGUAR +JAVA +JCB +JE +JEEP +JETZT +JEWELRY +JIO +JLL +JM +JMP +JNJ +JO +JOBS +JOBURG +JOT +JOY +JP +JPMORGAN +JPRS +JUEGOS +KAUFEN +KDDI +KE +KERRYHOTELS +KERRYPROPERTIES +KFH +KG +KH +KI +KIA +KIDS +KIM +KINDLE +KITCHEN +KIWI +KM +KN +KOELN +KOMATSU +KOSHER +KP +KPMG +KPN +KR +KRD +KRED +KUOKGROUP +KW +KY +KYOTO +KZ +LA +LACAIXA +LAMBORGHINI +LAMER +LAND +LANDROVER +LANXESS +LASALLE +LAT +LATINO +LATROBE +LAW +LAWYER +LB +LC +LDS +LEASE +LECLERC +LEFRAK +LEGAL +LEGO +LEXUS +LGBT +LI +LIDL +LIFE +LIFEINSURANCE +LIFESTYLE +LIGHTING +LIKE +LILLY +LIMITED +LIMO +LINCOLN +LINK +LIVE +LIVING +LK +LLC +LLP +LOAN +LOANS +LOCKER +LOCUS +LOL +LONDON +LOTTE +LOTTO +LOVE +LPL +LPLFINANCIAL +LR +LS +LT +LTD +LTDA +LU +LUNDBECK +LUXE +LUXURY +LV +LY +MA +MADRID +MAIF +MAISON +MAKEUP +MAN +MANAGEMENT +MANGO +MAP +MARKET +MARKETING +MARKETS +MARRIOTT +MARSHALLS +MATTEL +MBA +MC +MCKINSEY +MD +ME +MED +MEDIA +MEET +MELBOURNE +MEME +MEMORIAL +MEN +MENU +MERCK +MERCKMSD +MG +MH +MIAMI +MICROSOFT +MIL +MINI +MINT +MIT +MITSUBISHI +MK +ML +MLB +MLS +MM +MMA +MN +MO +MOBI +MOBILE +MODA +MOE +MOI +MOM +MONASH +MONEY +MONSTER +MORMON +MORTGAGE +MOSCOW +MOTO +MOTORCYCLES +MOV +MOVIE +MP +MQ +MR +MS +MSD +MT +MTN +MTR +MU +MUSEUM +MUSIC +MV +MW +MX +MY +MZ +NA +NAB +NAGOYA +NAME +NAVY +NBA +NC +NE +NEC +NET +NETBANK +NETFLIX +NETWORK +NEUSTAR +NEW +NEWS +NEXT +NEXTDIRECT +NEXUS +NF +NFL +NG +NGO +NHK +NI +NICO +NIKE +NIKON +NINJA +NISSAN +NISSAY +NL +NO +NOKIA +NORTON +NOW +NOWRUZ +NOWTV +NP +NR +NRA +NRW +NTT +NU +NYC +NZ +OBI +OBSERVER +OFFICE +OKINAWA +OLAYAN +OLAYANGROUP +OLLO +OM +OMEGA +ONE +ONG +ONL +ONLINE +OOO +OPEN +ORACLE +ORANGE +ORG +ORGANIC +ORIGINS +OSAKA +OTSUKA +OTT +OVH +PA +PAGE +PANASONIC +PARIS +PARS +PARTNERS +PARTS +PARTY +PAY +PCCW +PE +PET +PF +PFIZER +PG +PH +PHARMACY +PHD +PHILIPS +PHONE +PHOTO +PHOTOGRAPHY +PHOTOS +PHYSIO +PICS +PICTET +PICTURES +PID +PIN +PING +PINK +PIONEER +PIZZA +PK +PL +PLACE +PLAY +PLAYSTATION +PLUMBING +PLUS +PM +PN +PNC +POHL +POKER +POLITIE +PORN +POST +PR +PRAXI +PRESS +PRIME +PRO +PROD +PRODUCTIONS +PROF +PROGRESSIVE +PROMO +PROPERTIES +PROPERTY +PROTECTION +PRU +PRUDENTIAL +PS +PT +PUB +PW +PWC +PY +QA +QPON +QUEBEC +QUEST +RACING +RADIO +RE +READ +REALESTATE +REALTOR +REALTY +RECIPES +RED +REDUMBRELLA +REHAB +REISE +REISEN +REIT +RELIANCE +REN +RENT +RENTALS +REPAIR +REPORT +REPUBLICAN +REST +RESTAURANT +REVIEW +REVIEWS +REXROTH +RICH +RICHARDLI +RICOH +RIL +RIO +RIP +RO +ROCKS +RODEO +ROGERS +ROOM +RS +RSVP +RU +RUGBY +RUHR +RUN +RW +RWE +RYUKYU +SA +SAARLAND +SAFE +SAFETY +SAKURA +SALE +SALON +SAMSCLUB +SAMSUNG +SANDVIK +SANDVIKCOROMANT +SANOFI +SAP +SARL +SAS +SAVE +SAXO +SB +SBI +SBS +SC +SCB +SCHAEFFLER +SCHMIDT +SCHOLARSHIPS +SCHOOL +SCHULE +SCHWARZ +SCIENCE +SCOT +SD +SE +SEARCH +SEAT +SECURE +SECURITY +SEEK +SELECT +SENER +SERVICES +SEVEN +SEW +SEX +SEXY +SFR +SG +SH +SHANGRILA +SHARP +SHELL +SHIA +SHIKSHA +SHOES +SHOP +SHOPPING +SHOUJI +SHOW +SI +SILK +SINA +SINGLES +SITE +SJ +SK +SKI +SKIN +SKY +SKYPE +SL +SLING +SM +SMART +SMILE +SN +SNCF +SO +SOCCER +SOCIAL +SOFTBANK +SOFTWARE +SOHU +SOLAR +SOLUTIONS +SONG +SONY +SOY +SPA +SPACE +SPORT +SPOT +SR +SRL +SS +ST +STADA +STAPLES +STAR +STATEBANK +STATEFARM +STC +STCGROUP +STOCKHOLM +STORAGE +STORE +STREAM +STUDIO +STUDY +STYLE +SU +SUCKS +SUPPLIES +SUPPLY +SUPPORT +SURF +SURGERY +SUZUKI +SV +SWATCH +SWISS +SX +SY +SYDNEY +SYSTEMS +SZ +TAB +TAIPEI +TALK +TAOBAO +TARGET +TATAMOTORS +TATAR +TATTOO +TAX +TAXI +TC +TCI +TD +TDK +TEAM +TECH +TECHNOLOGY +TEL +TEMASEK +TENNIS +TEVA +TF +TG +TH +THD +THEATER +THEATRE +TIAA +TICKETS +TIENDA +TIPS +TIRES +TIROL +TJ +TJMAXX +TJX +TK +TKMAXX +TL +TM +TMALL +TN +TO +TODAY +TOKYO +TOOLS +TOP +TORAY +TOSHIBA +TOTAL +TOURS +TOWN +TOYOTA +TOYS +TR +TRADE +TRADING +TRAINING +TRAVEL +TRAVELERS +TRAVELERSINSURANCE +TRUST +TRV +TT +TUBE +TUI +TUNES +TUSHU +TV +TVS +TW +TZ +UA +UBANK +UBS +UG +UK +UNICOM +UNIVERSITY +UNO +UOL +UPS +US +UY +UZ +VA +VACATIONS +VANA +VANGUARD +VC +VE +VEGAS +VENTURES +VERISIGN +VERSICHERUNG +VET +VG +VI +VIAJES +VIDEO +VIG +VIKING +VILLAS +VIN +VIP +VIRGIN +VISA +VISION +VIVA +VIVO +VLAANDEREN +VN +VODKA +VOLVO +VOTE +VOTING +VOTO +VOYAGE +VU +WALES +WALMART +WALTER +WANG +WANGGOU +WATCH +WATCHES +WEATHER +WEATHERCHANNEL +WEB +WEBCAM +WEBER +WEBSITE +WED +WEDDING +WEIBO +WEIR +WF +WHOSWHO +WIEN +WIKI +WILLIAMHILL +WIN +WINDOWS +WINE +WINNERS +WME +WOODSIDE +WORK +WORKS +WORLD +WOW +WS +WTC +WTF +XBOX +XEROX +XIN +XN--11B4C3D +XN--1CK2E1B +XN--1QQW23A +XN--2SCRJ9C +XN--30RR7Y +XN--3BST00M +XN--3DS443G +XN--3E0B707E +XN--3HCRJ9C +XN--3PXU8K +XN--42C2D9A +XN--45BR5CYL +XN--45BRJ9C +XN--45Q11C +XN--4DBRK0CE +XN--4GBRIM +XN--54B7FTA0CC +XN--55QW42G +XN--55QX5D +XN--5SU34J936BGSG +XN--5TZM5G +XN--6FRZ82G +XN--6QQ986B3XL +XN--80ADXHKS +XN--80AO21A +XN--80AQECDR1A +XN--80ASEHDB +XN--80ASWG +XN--8Y0A063A +XN--90A3AC +XN--90AE +XN--90AIS +XN--9DBQ2A +XN--9ET52U +XN--9KRT00A +XN--B4W605FERD +XN--BCK1B9A5DRE4C +XN--C1AVG +XN--C2BR7G +XN--CCK2B3B +XN--CCKWCXETD +XN--CG4BKI +XN--CLCHC0EA0B2G2A9GCD +XN--CZR694B +XN--CZRS0T +XN--CZRU2D +XN--D1ACJ3B +XN--D1ALF +XN--E1A4C +XN--ECKVDTC9D +XN--EFVY88H +XN--FCT429K +XN--FHBEI +XN--FIQ228C5HS +XN--FIQ64B +XN--FIQS8S +XN--FIQZ9S +XN--FJQ720A +XN--FLW351E +XN--FPCRJ9C3D +XN--FZC2C9E2C +XN--FZYS8D69UVGM +XN--G2XX48C +XN--GCKR3F0F +XN--GECRJ9C +XN--GK3AT1E +XN--H2BREG3EVE +XN--H2BRJ9C +XN--H2BRJ9C8C +XN--HXT814E +XN--I1B6B1A6A2E +XN--IMR513N +XN--IO0A7I +XN--J1AEF +XN--J1AMH +XN--J6W193G +XN--JLQ480N2RG +XN--JVR189M +XN--KCRX77D1X4A +XN--KPRW13D +XN--KPRY57D +XN--KPUT3I +XN--L1ACC +XN--LGBBAT1AD8J +XN--MGB9AWBF +XN--MGBA3A3EJT +XN--MGBA3A4F16A +XN--MGBA7C0BBN0A +XN--MGBAAM7A8H +XN--MGBAB2BD +XN--MGBAH1A3HJKRD +XN--MGBAI9AZGQP6J +XN--MGBAYH7GPA +XN--MGBBH1A +XN--MGBBH1A71E +XN--MGBC0A9AZCG +XN--MGBCA7DZDO +XN--MGBCPQ6GPA1A +XN--MGBERP4A5D4AR +XN--MGBGU82A +XN--MGBI4ECEXP +XN--MGBPL2FH +XN--MGBT3DHD +XN--MGBTX2B +XN--MGBX4CD0AB +XN--MIX891F +XN--MK1BU44C +XN--MXTQ1M +XN--NGBC5AZD +XN--NGBE9E0A +XN--NGBRX +XN--NODE +XN--NQV7F +XN--NQV7FS00EMA +XN--NYQY26A +XN--O3CW4H +XN--OGBPF8FL +XN--OTU796D +XN--P1ACF +XN--P1AI +XN--PGBS0DH +XN--PSSY2U +XN--Q7CE6A +XN--Q9JYB4C +XN--QCKA1PMC +XN--QXA6A +XN--QXAM +XN--RHQV96G +XN--ROVU88B +XN--RVC1E0AM3E +XN--S9BRJ9C +XN--SES554G +XN--T60B56A +XN--TCKWE +XN--TIQ49XQYJ +XN--UNUP4Y +XN--VERMGENSBERATER-CTB +XN--VERMGENSBERATUNG-PWB +XN--VHQUV +XN--VUQ861B +XN--W4R85EL8FHU5DNRA +XN--W4RS40L +XN--WGBH1C +XN--WGBL6A +XN--XHQ521B +XN--XKC2AL3HYE2A +XN--XKC2DL3A5EE0H +XN--Y9A3AQ +XN--YFRO4I67O +XN--YGBI2AMMX +XN--ZFR164B +XXX +XYZ +YACHTS +YAHOO +YAMAXUN +YANDEX +YE +YODOBASHI +YOGA +YOKOHAMA +YOU +YOUTUBE +YT +YUN +ZA +ZAPPOS +ZARA +ZERO +ZIP +ZM +ZONE +ZUERICH +ZW diff --git a/src/Domain/Configuration/Model/ConfigOption.php b/src/Domain/Configuration/Model/ConfigOption.php index dda10f8f..6dc4b4a9 100644 --- a/src/Domain/Configuration/Model/ConfigOption.php +++ b/src/Domain/Configuration/Model/ConfigOption.php @@ -48,4 +48,6 @@ enum ConfigOption: string case RemoteProcessingSecret = 'remote_processing_secret'; case NotifyAdminLogin = 'notify_admin_login'; case XorMask = 'xormask'; + case InternetTlds = 'internet_tlds'; + case TldLastSync = 'tld_last_sync'; } diff --git a/src/Domain/Subscription/Command/UpdateTldsCommand.php b/src/Domain/Subscription/Command/UpdateTldsCommand.php new file mode 100644 index 00000000..7e11180f --- /dev/null +++ b/src/Domain/Subscription/Command/UpdateTldsCommand.php @@ -0,0 +1,52 @@ +addOption('force', 'f', InputOption::VALUE_NONE, 'Refresh even if it was done in the last 30 days'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $result = $this->tldListService->refresh((bool) $input->getOption('force')); + + if ($result->remoteFailed()) { + $output->writeln($this->translator->trans('Could not download the list of top level domains.')); + } + $output->writeln($this->translator->trans( + 'Now we have %count% top level domains', + ['%count%' => $result->count] + )); + + return $result->remoteFailed() ? Command::FAILURE : Command::SUCCESS; + } +} diff --git a/src/Domain/Subscription/Model/Dto/TldRefreshResult.php b/src/Domain/Subscription/Model/Dto/TldRefreshResult.php new file mode 100644 index 00000000..39d4bc74 --- /dev/null +++ b/src/Domain/Subscription/Model/Dto/TldRefreshResult.php @@ -0,0 +1,28 @@ +source === self::SOURCE_BUNDLED || $this->source === self::SOURCE_KEPT; + } +} diff --git a/src/Domain/Subscription/Service/EmailTldValidator.php b/src/Domain/Subscription/Service/EmailTldValidator.php new file mode 100644 index 00000000..9fb7b68d --- /dev/null +++ b/src/Domain/Subscription/Service/EmailTldValidator.php @@ -0,0 +1,37 @@ +tldListService->isKnownTld($tld); + } +} diff --git a/src/Domain/Subscription/Service/SubscriberCsvImporter.php b/src/Domain/Subscription/Service/SubscriberCsvImporter.php index 4b7e8cbd..3528c2db 100644 --- a/src/Domain/Subscription/Service/SubscriberCsvImporter.php +++ b/src/Domain/Subscription/Service/SubscriberCsvImporter.php @@ -46,6 +46,7 @@ public function __construct( private readonly MessageBusInterface $messageBus, private readonly SubscriberHistoryManager $subscriberHistoryManager, private readonly UserBlacklistRepository $blacklistRepository, + private readonly EmailTldValidator $emailTldValidator, ) { } @@ -230,7 +231,7 @@ private function handleInvalidEmail( SubscriberImportOptions $options, array &$stats ): bool { - if (!filter_var($dto->email, FILTER_VALIDATE_EMAIL)) { + if (!filter_var($dto->email, FILTER_VALIDATE_EMAIL) || !$this->emailTldValidator->hasKnownTld($dto->email)) { if ($options->skipInvalidEmail) { $stats['skipped']++; $stats['invalid_email']++; diff --git a/src/Domain/Subscription/Service/TldListService.php b/src/Domain/Subscription/Service/TldListService.php new file mode 100644 index 00000000..ec667289 --- /dev/null +++ b/src/Domain/Subscription/Service/TldListService.php @@ -0,0 +1,185 @@ +|null */ + private ?array $knownTlds = null; + + public function __construct( + private readonly HttpClientInterface $httpClient, + private readonly ConfigRepository $configRepository, + private readonly EntityManagerInterface $entityManager, + private readonly LoggerInterface $logger, + #[Autowire('%kernel.project_dir%/resources/tlds-alpha-by-domain.txt')] + private readonly string $bundledListPath, + private readonly string $sourceUrl = self::SOURCE_URL, + ) { + } + + /** + * Downloads the list unless it was refreshed in the last 30 days (or $force is set). + * As in phplist3 the sync time is stored before downloading, so a failing download is not retried + * on every call. + */ + public function refresh(bool $force = false): TldRefreshResult + { + $stored = $this->storedTlds(); + $lastSync = (int) $this->configRepository->findValueByItem(ConfigOption::TldLastSync->value); + if (!$force && $stored !== [] && $lastSync + self::REFETCH_TIMEOUT_SECONDS > time()) { + return new TldRefreshResult(count($stored), TldRefreshResult::SOURCE_SKIPPED); + } + + $this->saveConfig(ConfigOption::TldLastSync, (string) time()); + $this->entityManager->flush(); + + $remote = $this->fetchRemote(); + if ($remote !== null) { + $this->storeList($remote); + + return new TldRefreshResult(count($remote), TldRefreshResult::SOURCE_REMOTE); + } + + if ($stored === []) { + $bundled = $this->bundledTlds(); + $this->storeList($bundled); + + return new TldRefreshResult(count($bundled), TldRefreshResult::SOURCE_BUNDLED); + } + + return new TldRefreshResult(count($stored), TldRefreshResult::SOURCE_KEPT); + } + + /** @return list lowercase TLDs, from the stored list or else the bundled one */ + public function getTlds(): array + { + $stored = $this->storedTlds(); + if ($stored !== []) { + return $stored; + } + + return $this->bundledTlds(); + } + + public function isKnownTld(string $tld): bool + { + if ($this->knownTlds === null) { + $this->knownTlds = array_fill_keys($this->getTlds(), true); + } + + return isset($this->knownTlds[strtolower($tld)]); + } + + /** + * Parses IANA's file format: "# comment" header line, then one TLD per line. + * + * @return list unique lowercase TLDs + */ + public function parseList(string $content): array + { + $tlds = []; + foreach (preg_split('/\R/', $content) ?: [] as $line) { + $line = strtolower(trim($line)); + if ($line === '' || $line[0] === '#') { + continue; + } + if (preg_match('/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/', $line) === 1) { + $tlds[$line] = true; + } + } + + return array_keys($tlds); + } + + /** @return list|null null when the download failed or does not look like a TLD list */ + private function fetchRemote(): ?array + { + try { + $response = $this->httpClient->request('GET', $this->sourceUrl, ['timeout' => 30]); + if ($response->getStatusCode() !== 200) { + $this->logger->warning('TLD list download returned a non-200 status', [ + 'status' => $response->getStatusCode(), + ]); + + return null; + } + $tlds = $this->parseList($response->getContent()); + } catch (Throwable $throwable) { + $this->logger->warning('TLD list download failed', ['error' => $throwable->getMessage()]); + + return null; + } + + if (count($tlds) < self::MIN_PLAUSIBLE_TLDS) { + $this->logger->warning('Downloaded TLD list is too short, ignoring it', ['count' => count($tlds)]); + + return null; + } + + return $tlds; + } + + /** @return list */ + private function bundledTlds(): array + { + $content = is_readable($this->bundledListPath) ? file_get_contents($this->bundledListPath) : false; + if ($content === false) { + $this->logger->error('Bundled TLD list is missing or unreadable', ['path' => $this->bundledListPath]); + + return []; + } + + return $this->parseList($content); + } + + /** @return list */ + private function storedTlds(): array + { + $value = (string) $this->configRepository->findValueByItem(ConfigOption::InternetTlds->value); + + return $value === '' ? [] : array_values(array_filter(explode('|', strtolower($value)))); + } + + /** @param list $tlds */ + private function storeList(array $tlds): void + { + $this->saveConfig(ConfigOption::InternetTlds, implode('|', $tlds)); + $this->entityManager->flush(); + $this->knownTlds = null; + } + + private function saveConfig(ConfigOption $option, string $value): void + { + $config = $this->configRepository->findByKey($option->value); + if ($config === null) { + $config = (new Config()) + ->setKey($option->value) + ->setEditable(false) + ->setType('textarea'); + $this->configRepository->persist($config); + } + $config->setValue($value); + } +} diff --git a/tests/Unit/Domain/Subscription/Command/UpdateTldsCommandTest.php b/tests/Unit/Domain/Subscription/Command/UpdateTldsCommandTest.php new file mode 100644 index 00000000..2ab9396a --- /dev/null +++ b/tests/Unit/Domain/Subscription/Command/UpdateTldsCommandTest.php @@ -0,0 +1,60 @@ +service = $this->createMock(TldListService::class); + $translator = $this->createMock(TranslatorInterface::class); + $translator->method('trans')->willReturnCallback(static fn (string $id, array $p = []) => strtr($id, $p)); + $this->tester = new CommandTester(new UpdateTldsCommand($this->service, $translator)); + } + + public function testReportsCountOnSuccess(): void + { + $this->service->expects($this->once())->method('refresh')->with(false) + ->willReturn(new TldRefreshResult(1436, TldRefreshResult::SOURCE_REMOTE)); + + $this->tester->execute([]); + + $this->assertSame(0, $this->tester->getStatusCode()); + $this->assertStringContainsString('Now we have 1436 top level domains', $this->tester->getDisplay()); + } + + public function testForceOptionIsPassedOn(): void + { + $this->service->expects($this->once())->method('refresh')->with(true) + ->willReturn(new TldRefreshResult(10, TldRefreshResult::SOURCE_SKIPPED)); + + $this->tester->execute(['--force' => true]); + + $this->assertSame(0, $this->tester->getStatusCode()); + } + + public function testFailsWhenDownloadFailed(): void + { + $this->service->method('refresh') + ->willReturn(new TldRefreshResult(1400, TldRefreshResult::SOURCE_KEPT)); + + $this->tester->execute([]); + + $this->assertSame(1, $this->tester->getStatusCode()); + $this->assertStringContainsString('Could not download', $this->tester->getDisplay()); + $this->assertStringContainsString('1400', $this->tester->getDisplay()); + } +} diff --git a/tests/Unit/Domain/Subscription/Service/EmailTldValidatorTest.php b/tests/Unit/Domain/Subscription/Service/EmailTldValidatorTest.php new file mode 100644 index 00000000..6dd03adf --- /dev/null +++ b/tests/Unit/Domain/Subscription/Service/EmailTldValidatorTest.php @@ -0,0 +1,46 @@ +tlds = $this->createMock(TldListService::class); + $this->tlds->method('isKnownTld')->willReturnCallback( + static fn (string $tld): bool => in_array($tld, ['com', 'org', 'xn--p1ai'], true) + ); + $this->validator = new EmailTldValidator($this->tlds); + } + + /** @dataProvider provider */ + public function testHasKnownTld(string $email, bool $expected): void + { + $this->assertSame($expected, $this->validator->hasKnownTld($email)); + } + + public static function provider(): array + { + return [ + 'known tld' => ['a@example.com', true], + 'subdomain' => ['a@mail.example.org', true], + 'trailing dot' => ['a@example.com.', true], + 'unknown tld' => ['a@example.invalidtld', false], + 'no dot in domain' => ['a@localhost', false], + 'no at sign' => ['example.com', false], + 'empty tld' => ['a@example.', false], + 'last at sign wins' => ['a@b@example.com', true], + 'idn tld converted to punycode' => ['a@example.рф', true], + ]; + } +} diff --git a/tests/Unit/Domain/Subscription/Service/SubscriberCsvImporterTest.php b/tests/Unit/Domain/Subscription/Service/SubscriberCsvImporterTest.php index ec46f9c1..ab5e02fd 100644 --- a/tests/Unit/Domain/Subscription/Service/SubscriberCsvImporterTest.php +++ b/tests/Unit/Domain/Subscription/Service/SubscriberCsvImporterTest.php @@ -13,6 +13,7 @@ use PhpList\Core\Domain\Subscription\Repository\SubscriberAttributeDefinitionRepository; use PhpList\Core\Domain\Subscription\Repository\SubscriberRepository; use PhpList\Core\Domain\Subscription\Service\CsvToDtoImporter; +use PhpList\Core\Domain\Subscription\Service\EmailTldValidator; use PhpList\Core\Domain\Subscription\Service\Manager\SubscriberAttributeManager; use PhpList\Core\Domain\Subscription\Service\Manager\SubscriberHistoryManager; use PhpList\Core\Domain\Subscription\Service\Manager\SubscriberManager; @@ -35,6 +36,7 @@ class SubscriberCsvImporterTest extends TestCase private UserBlacklistRepository&MockObject $blacklistRepositoryMock; private SubscriptionManager&MockObject $subscriptionManagerMock; private MessageBusInterface&MockObject $messageBusMock; + private EmailTldValidator&MockObject $emailTldValidatorMock; private SubscriberCsvImporter $subject; protected function setUp(): void @@ -48,6 +50,8 @@ protected function setUp(): void $this->messageBusMock = $this->createMock(MessageBusInterface::class); $entityManager = $this->createMock(EntityManagerInterface::class); $this->blacklistRepositoryMock = $this->createMock(UserBlacklistRepository::class); + $this->emailTldValidatorMock = $this->createMock(EmailTldValidator::class); + $this->emailTldValidatorMock->method('hasKnownTld')->willReturn(true); $this->subject = new SubscriberCsvImporter( subscriberManager: $this->subscriberManagerMock, @@ -60,6 +64,7 @@ protected function setUp(): void messageBus: $this->messageBusMock, subscriberHistoryManager: $this->createMock(SubscriberHistoryManager::class), blacklistRepository: $this->blacklistRepositoryMock, + emailTldValidator: $this->emailTldValidatorMock, ); } @@ -582,4 +587,103 @@ public function testImportIgnoresBlacklistedFlagWhenEmailIsNotInBlacklistTable() unlink($tempFile); } + + public function testImportSkipsEmailWithUnknownTopLevelDomain(): void + { + $tempFile = tempnam(sys_get_temp_dir(), 'csv_test_tld'); + file_put_contents( + $tempFile, + "email,confirmed,html_email,blacklisted,disabled\nuser@example.invalidtld,1,1,0,0\n" + ); + + $uploadedFile = $this->createMock(UploadedFile::class); + $uploadedFile->method('getRealPath')->willReturn($tempFile); + + $dto = new ImportSubscriberDto( + email: 'user@example.invalidtld', + confirmed: true, + htmlEmail: true, + disabled: false, + ); + $this->csvImporterMock->method('parseAndValidate')->willReturn(['valid' => [$dto], 'errors' => []]); + + $validator = $this->createMock(EmailTldValidator::class); + $validator->expects($this->once())->method('hasKnownTld') + ->with('user@example.invalidtld')->willReturn(false); + $subject = $this->subjectWith($validator); + + $this->subscriberManagerMock->expects($this->never())->method('createFromImport'); + + $result = $subject->importFromCsv($uploadedFile, new SubscriberImportOptions(listIds: [1])); + + $this->assertSame(0, $result['created']); + $this->assertSame(1, $result['skipped']); + $this->assertSame(1, $result['invalid_email']); + $this->assertSame(['Invalid email: user@example.invalidtld'], $result['errors']); + + unlink($tempFile); + } + + public function testImportKeepsUnknownTopLevelDomainEmailWithInvalidPrefixWhenNotSkipping(): void + { + $tempFile = tempnam(sys_get_temp_dir(), 'csv_test_tld_keep'); + file_put_contents( + $tempFile, + "email,confirmed,html_email,blacklisted,disabled\nuser@example.invalidtld,1,1,0,0\n" + ); + + $uploadedFile = $this->createMock(UploadedFile::class); + $uploadedFile->method('getRealPath')->willReturn($tempFile); + + $dto = new ImportSubscriberDto( + email: 'user@example.invalidtld', + confirmed: false, + htmlEmail: true, + disabled: false, + ); + $this->csvImporterMock->method('parseAndValidate')->willReturn(['valid' => [$dto], 'errors' => []]); + $this->subscriberRepositoryMock->method('findOneByEmail')->willReturn(null); + + $validator = $this->createMock(EmailTldValidator::class); + $validator->method('hasKnownTld')->willReturn(false); + $subject = $this->subjectWith($validator); + + $created = $this->createMock(Subscriber::class); + $created->method('getId')->willReturn(9); + $created->method('getEmail')->willReturn('invalid_user@example.invalidtld'); + $this->subscriberManagerMock->expects($this->once())->method('createFromImport') + ->with($this->callback( + fn (ImportSubscriberDto $d) => $d->email === 'invalid_user@example.invalidtld' + && $d->sendConfirmation === false + )) + ->willReturn($created); + $this->messageBusMock->expects($this->never())->method('dispatch'); + + $result = $subject->importFromCsv( + $uploadedFile, + new SubscriberImportOptions(listIds: [1], skipInvalidEmail: false) + ); + + $this->assertSame(1, $result['created']); + $this->assertSame(0, $result['invalid_email']); + + unlink($tempFile); + } + + private function subjectWith(EmailTldValidator $validator): SubscriberCsvImporter + { + return new SubscriberCsvImporter( + subscriberManager: $this->subscriberManagerMock, + attributeManager: $this->attributeManagerMock, + subscriptionManager: $this->subscriptionManagerMock, + subscriberRepository: $this->subscriberRepositoryMock, + csvToDtoImporter: $this->csvImporterMock, + entityManager: $this->createMock(EntityManagerInterface::class), + translator: new Translator('en'), + messageBus: $this->messageBusMock, + subscriberHistoryManager: $this->createMock(SubscriberHistoryManager::class), + blacklistRepository: $this->blacklistRepositoryMock, + emailTldValidator: $validator, + ); + } } diff --git a/tests/Unit/Domain/Subscription/Service/TldListServiceTest.php b/tests/Unit/Domain/Subscription/Service/TldListServiceTest.php new file mode 100644 index 00000000..d29a3284 --- /dev/null +++ b/tests/Unit/Domain/Subscription/Service/TldListServiceTest.php @@ -0,0 +1,178 @@ + */ + private array $configs = []; + private string $bundled; + + protected function setUp(): void + { + $this->bundled = tempnam(sys_get_temp_dir(), 'tlds'); + file_put_contents($this->bundled, "# Version 1\nCOM\nORG\nNET\n"); + + $this->configs = []; + $this->configRepository = $this->createMock(ConfigRepository::class); + $this->configRepository->method('findValueByItem') + ->willReturnCallback(fn (string $key) => $this->config($key)?->getValue()); + $this->configRepository->method('findByKey') + ->willReturnCallback(fn (string $key) => $this->config($key)); + $this->configRepository->method('persist') + ->willReturnCallback(function (Config $config): void { + $this->configs[$config->getKey()] = $config; + }); + $this->entityManager = $this->createMock(EntityManagerInterface::class); + } + + protected function tearDown(): void + { + if (is_file($this->bundled)) { + unlink($this->bundled); + } + } + + private function service(MockResponse|array $responses): TldListService + { + return new TldListService( + httpClient: new MockHttpClient($responses), + configRepository: $this->configRepository, + entityManager: $this->entityManager, + logger: new NullLogger(), + bundledListPath: $this->bundled, + sourceUrl: 'https://example.test/tlds.txt', + ); + } + + private function remoteList(int $count = 150): string + { + $lines = ['# Version 2, Last Updated now']; + for ($i = 0; $i < $count; $i++) { + $lines[] = 'T' . $i . 'X'; + } + $lines[] = 'XN--P1AI'; + + return implode("\n", $lines) . "\n"; + } + + private function config(string $key): ?Config + { + return $this->configs[$key] ?? null; + } + + private function stored(string $key): ?string + { + return $this->config($key)?->getValue(); + } + + public function testParseListSkipsCommentsBlankAndInvalidLinesAndKeepsPunycode(): void + { + $content = "# header\r\nCOM\n\n Org \nxn--p1ai\nbad_one\n-bad\nbad-\nnot a tld\ncom\n"; + $tlds = $this->service([])->parseList($content); + + $this->assertSame(['com', 'org', 'xn--p1ai'], $tlds); + } + + public function testGetTldsFallsBackToBundledListWhenNothingStored(): void + { + $service = $this->service([]); + + $this->assertSame(['com', 'org', 'net'], $service->getTlds()); + $this->assertTrue($service->isKnownTld('COM')); + $this->assertFalse($service->isKnownTld('invalidtld')); + } + + public function testRefreshStoresDownloadedList(): void + { + $service = $this->service(new MockResponse($this->remoteList())); + $this->entityManager->expects($this->atLeastOnce())->method('flush'); + + $result = $service->refresh(); + + $this->assertSame(TldRefreshResult::SOURCE_REMOTE, $result->source); + $this->assertSame(151, $result->count); + $this->assertFalse($result->remoteFailed()); + $this->assertNotNull($this->stored('tld_last_sync')); + $this->assertStringContainsString('t0x|t1x', (string) $this->stored('internet_tlds')); + $this->assertTrue($service->isKnownTld('xn--p1ai')); + $this->assertFalse($service->isKnownTld('com')); + } + + public function testRefreshIsSkippedWhenDoneRecentlyUnlessForced(): void + { + $this->service(new MockResponse($this->remoteList()))->refresh(); + + $skipped = $this->service([])->refresh(); + $this->assertSame(TldRefreshResult::SOURCE_SKIPPED, $skipped->source); + $this->assertSame(151, $skipped->count); + + $forced = $this->service(new MockResponse($this->remoteList(120)))->refresh(true); + $this->assertSame(TldRefreshResult::SOURCE_REMOTE, $forced->source); + $this->assertSame(121, $forced->count); + } + + public function testRefreshIsDueAgainAfterThirtyDays(): void + { + $this->service(new MockResponse($this->remoteList()))->refresh(); + $this->config('tld_last_sync')?->setValue((string) (time() - 2592001)); + + $result = $this->service(new MockResponse($this->remoteList(120)))->refresh(); + + $this->assertSame(TldRefreshResult::SOURCE_REMOTE, $result->source); + $this->assertSame(121, $result->count); + } + + public function testFailedDownloadSeedsBundledListWhenNothingStored(): void + { + $result = $this->service(new MockResponse('', ['http_code' => 500]))->refresh(); + + $this->assertSame(TldRefreshResult::SOURCE_BUNDLED, $result->source); + $this->assertSame(3, $result->count); + $this->assertTrue($result->remoteFailed()); + $this->assertSame('com|org|net', $this->stored('internet_tlds')); + } + + public function testFailedDownloadKeepsExistingList(): void + { + $this->service(new MockResponse($this->remoteList()))->refresh(); + $before = $this->stored('internet_tlds'); + + $result = $this->service(new MockResponse('', ['http_code' => 503]))->refresh(true); + + $this->assertSame(TldRefreshResult::SOURCE_KEPT, $result->source); + $this->assertTrue($result->remoteFailed()); + $this->assertSame($before, $this->stored('internet_tlds')); + } + + public function testImplausiblyShortDownloadIsIgnored(): void + { + $result = $this->service(new MockResponse("# Version\nCOM\nORG\n"))->refresh(); + + $this->assertSame(TldRefreshResult::SOURCE_BUNDLED, $result->source); + $this->assertSame('com|org|net', $this->stored('internet_tlds')); + } + + public function testSyncTimeIsStoredEvenWhenDownloadFails(): void + { + $this->service(new MockResponse('', ['http_code' => 500]))->refresh(); + + $this->assertNotNull($this->stored('tld_last_sync')); + $this->assertEqualsWithDelta(time(), (int) $this->stored('tld_last_sync'), 5); + } +} From e823f6868b598d334145c0179c754cde8452ce7b Mon Sep 17 00:00:00 2001 From: Tatevik Date: Thu, 26 Nov 2026 12:53:25 +0400 Subject: [PATCH 04/14] fix: locking --- .../Messaging/Command/ProcessQueueCommand.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Domain/Messaging/Command/ProcessQueueCommand.php b/src/Domain/Messaging/Command/ProcessQueueCommand.php index 09d3b5aa..248bd653 100644 --- a/src/Domain/Messaging/Command/ProcessQueueCommand.php +++ b/src/Domain/Messaging/Command/ProcessQueueCommand.php @@ -50,13 +50,6 @@ public function __construct( protected function execute(InputInterface $input, OutputInterface $output): int { - $lock = $this->lockFactory->createLock('queue_processor'); - if (!$lock->acquire()) { - $output->writeln($this->translator->trans('Queue is already being processed by another instance.')); - - return Command::FAILURE; - } - if ($this->configProvider->isEnabled(ConfigOption::MaintenanceMode)) { $output->writeln( $this->translator->trans('The system is in maintenance mode, stopping. Try again later.') @@ -65,6 +58,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int return Command::FAILURE; } + $lock = $this->lockFactory->createLock('queue_processor'); + if (!$lock->acquire()) { + $output->writeln($this->translator->trans('Queue is already being processed by another instance.')); + + return Command::FAILURE; + } + try { $this->messagePreparator->ensureSubscribersHaveUuid($output); $this->messagePreparator->ensureCampaignsHaveUuid($output); From 92b70d9893bd32992bd2e1f60ffb2bceb0935791 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Thu, 26 Nov 2026 12:58:34 +0400 Subject: [PATCH 05/14] feat: implement Symfony Scheduler for recurring command execution --- .env.dist | 7 +++ composer.json | 3 +- config/parameters.yml | 11 ++++ config/services/messenger.yml | 9 +++ docs/Scheduling.md | 38 +++++++++++++ .../Common/Schedule/PhpListSchedule.php | 54 ++++++++++++++++++ .../Command/CleanUpOldSessionTokens.php | 2 +- .../Messaging/Command/ProcessQueueCommand.php | 9 --- .../Common/Schedule/PhpListScheduleTest.php | 56 +++++++++++++++++++ 9 files changed, 178 insertions(+), 11 deletions(-) create mode 100644 docs/Scheduling.md create mode 100644 src/Domain/Common/Schedule/PhpListSchedule.php create mode 100644 tests/Unit/Domain/Common/Schedule/PhpListScheduleTest.php diff --git a/.env.dist b/.env.dist index 80161df9..c85086d9 100644 --- a/.env.dist +++ b/.env.dist @@ -57,6 +57,13 @@ BOUNCE_IMAP_PURGE_UNPROCESSED=0 MESSENGER_TRANSPORT_DSN=doctrine://default?auto_setup=true SEARCH_TRANSPORT_DSN=doctrine://default?queue_name=search_index +# Scheduler (run `bin/console messenger:consume scheduler_default`, see docs/Scheduling.md). +# Relative intervals; set to an empty value to disable an entry. +PHPLIST_SCHEDULE_QUEUE="1 minute" +PHPLIST_SCHEDULE_BOUNCES="1 day" +PHPLIST_SCHEDULE_TLDS="1 month" +PHPLIST_SCHEDULE_CLEANUP="1 day" + # Elasticsearch configuration # Set to false to fall back to reading/writing these tables straight from MySQL - no Elasticsearch # cluster required. See docs/ElasticsearchSearch.md. diff --git a/composer.json b/composer.json index a7a9c48a..bd74450a 100644 --- a/composer.json +++ b/composer.json @@ -90,7 +90,8 @@ "guzzlehttp/guzzle": "^7.4.5", "symfony/dotenv": "^7.4", "symfony/doctrine-messenger": "^7.4", - "elasticsearch/elasticsearch": "^8.9" + "elasticsearch/elasticsearch": "^8.9", + "symfony/scheduler": "^7.4" }, "require-dev": { "phpunit/phpunit": "^9.5", diff --git a/config/parameters.yml b/config/parameters.yml index d902b639..1c330119 100644 --- a/config/parameters.yml +++ b/config/parameters.yml @@ -55,6 +55,17 @@ parameters: app.messenger_transport_dsn: '%env(MESSENGER_TRANSPORT_DSN)%' app.search_transport_dsn: '%env(SEARCH_TRANSPORT_DSN)%' + # Scheduler intervals (relative strings, empty disables), see docs/Scheduling.md + # The env() lines are the defaults for installs whose .env predates these variables. + env(PHPLIST_SCHEDULE_QUEUE): '1 minute' + env(PHPLIST_SCHEDULE_BOUNCES): '1 day' + env(PHPLIST_SCHEDULE_TLDS): '1 month' + env(PHPLIST_SCHEDULE_CLEANUP): '1 day' + app.schedule.queue_interval: '%env(PHPLIST_SCHEDULE_QUEUE)%' + app.schedule.bounce_interval: '%env(PHPLIST_SCHEDULE_BOUNCES)%' + app.schedule.tld_interval: '%env(PHPLIST_SCHEDULE_TLDS)%' + app.schedule.cleanup_interval: '%env(PHPLIST_SCHEDULE_CLEANUP)%' + # Elasticsearch configuration elasticsearch.enabled: '%env(bool:ELASTICSEARCH_ENABLED)%' elasticsearch.hosts: '%env(csv:ELASTICSEARCH_HOSTS)%' diff --git a/config/services/messenger.yml b/config/services/messenger.yml index 40d70b93..92333c6c 100644 --- a/config/services/messenger.yml +++ b/config/services/messenger.yml @@ -24,3 +24,12 @@ services: PhpList\Core\Domain\Messaging\MessageHandler\CampaignProcessorTestMessageHandler: autowire: true autoconfigure: true + + PhpList\Core\Domain\Common\Schedule\PhpListSchedule: + autowire: true + autoconfigure: true + arguments: + $queueInterval: '%app.schedule.queue_interval%' + $bounceInterval: '%app.schedule.bounce_interval%' + $tldInterval: '%app.schedule.tld_interval%' + $cleanupInterval: '%app.schedule.cleanup_interval%' diff --git a/docs/Scheduling.md b/docs/Scheduling.md new file mode 100644 index 00000000..f27f09a3 --- /dev/null +++ b/docs/Scheduling.md @@ -0,0 +1,38 @@ +# Scheduling + +Core ships a Symfony Scheduler schedule (`PhpList\Core\Domain\Common\Schedule\PhpListSchedule`) +that runs the recurring commands for you. + +## Default: Scheduler worker + +Run one long-lived worker (supervisor/systemd), next to the `async_email` consumer: + +```bash +bin/console messenger:consume scheduler_default +``` + +| Command | Default | Env variable | +|----------------------------------------|-----------|-----------------------------| +| `phplist:process-queue` | 1 minute | `PHPLIST_SCHEDULE_QUEUE` | +| `phplist:bounces:process` | 1 day | `PHPLIST_SCHEDULE_BOUNCES` | +| `phplist:update-tlds` | 1 month | `PHPLIST_SCHEDULE_TLDS` | +| `phplist:clean-up-old-session-tokens` | 1 day | `PHPLIST_SCHEDULE_CLEANUP` | + +Values are relative interval strings (`"5 minutes"`, `"1 day"`); an empty value disables that entry. The +defaults are (queue every minute, bounces daily). + +Overlapping runs are prevented: the schedule is locked, and `phplist:process-queue` / +`phplist:bounces:process` keep their own locks, so a slow run makes the next one exit instead of piling up. + +## Alternative: system crontab + +On hosts where a long-running worker is not possible, disable the scheduler and use cron: + +```cron +* * * * * php /path/to/bin/console phplist:process-queue +0 3 * * * php /path/to/bin/console phplist:bounces:process +0 4 1 * * php /path/to/bin/console phplist:update-tlds +30 4 * * * php /path/to/bin/console phplist:clean-up-old-session-tokens +``` + +Running both is harmless because of the locks, but pointless. diff --git a/src/Domain/Common/Schedule/PhpListSchedule.php b/src/Domain/Common/Schedule/PhpListSchedule.php new file mode 100644 index 00000000..aab62c2b --- /dev/null +++ b/src/Domain/Common/Schedule/PhpListSchedule.php @@ -0,0 +1,54 @@ +lock($this->lockFactory->createLock('phplist_schedule')); + + $jobs = [ + [$this->queueInterval, 'phplist:process-queue'], + [$this->bounceInterval, 'phplist:bounces:process'], + [$this->tldInterval, 'phplist:update-tlds'], + [$this->cleanupInterval, 'phplist:clean-up-old-session-tokens'], + ]; + + foreach ($jobs as [$interval, $command]) { + if (trim($interval) === '') { + continue; + } + $schedule->add(RecurringMessage::every(trim($interval), new RunCommandMessage($command))); + } + + return $schedule; + } +} diff --git a/src/Domain/Identity/Command/CleanUpOldSessionTokens.php b/src/Domain/Identity/Command/CleanUpOldSessionTokens.php index 5505ca73..3994916f 100644 --- a/src/Domain/Identity/Command/CleanUpOldSessionTokens.php +++ b/src/Domain/Identity/Command/CleanUpOldSessionTokens.php @@ -24,7 +24,7 @@ * elsewhere in core * user_message_view rows: legacy only deletes them together with their message or subscriber (lib.php, * inc/userlib.php) and never prunes them by age, so an age based cleanup would be new behaviour, not a port. - * Also add the new commands to the scheduling TODO on ProcessQueueCommand. + * Also add the new commands to PhpListSchedule. */ #[AsCommand( name: 'phplist:clean-up-old-session-tokens', diff --git a/src/Domain/Messaging/Command/ProcessQueueCommand.php b/src/Domain/Messaging/Command/ProcessQueueCommand.php index 248bd653..f2b6a868 100644 --- a/src/Domain/Messaging/Command/ProcessQueueCommand.php +++ b/src/Domain/Messaging/Command/ProcessQueueCommand.php @@ -21,15 +21,6 @@ use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; -/** - * TODO: scheduling. phplist3 documents putting processqueue and processbounces in the system cron, and core has - * no schedule definition, so users have to write the crontab themselves. Close this with either: - * - a documented crontab example (e.g. in docs/), or - * - a Symfony Scheduler schedule (symfony/scheduler is not installed yet) covering the recurring commands: - * phplist:process-queue, phplist:bounces:process, phplist:update-tlds (monthly) and the cleanup commands such - * as phplist:clean-up-old-session-tokens. - * Keep the existing "queue_processor" lock in mind: a schedule must not start overlapping runs. - */ #[AsCommand( name: 'phplist:process-queue', description: 'Processes the email campaign queue.' diff --git a/tests/Unit/Domain/Common/Schedule/PhpListScheduleTest.php b/tests/Unit/Domain/Common/Schedule/PhpListScheduleTest.php new file mode 100644 index 00000000..cff71845 --- /dev/null +++ b/tests/Unit/Domain/Common/Schedule/PhpListScheduleTest.php @@ -0,0 +1,56 @@ + */ + private function commands(PhpListSchedule $provider): array + { + $commands = []; + /** @var RecurringMessage $recurring */ + foreach ($provider->getSchedule()->getRecurringMessages() as $recurring) { + $now = new \DateTimeImmutable('2026-01-01 00:00:00'); + $context = new MessageContext('default', $recurring->getId(), $recurring->getTrigger(), $now); + foreach ($recurring->getProvider()->getMessages($context) as $message) { + self::assertInstanceOf(RunCommandMessage::class, $message); + $commands[] = $message->input; + } + } + + return $commands; + } + + public function testDefaultScheduleContainsAllRecurringCommands(): void + { + $provider = new PhpListSchedule(new LockFactory(new InMemoryStore())); + + self::assertSame( + [ + 'phplist:process-queue', + 'phplist:bounces:process', + 'phplist:update-tlds', + 'phplist:clean-up-old-session-tokens', + ], + $this->commands($provider) + ); + } + + public function testEmptyIntervalDisablesEntry(): void + { + $provider = new PhpListSchedule(new LockFactory(new InMemoryStore()), bounceInterval: ''); + + self::assertNotContains('phplist:bounces:process', $this->commands($provider)); + self::assertContains('phplist:process-queue', $this->commands($provider)); + } +} From 892ed64b751fb164cffc8584478ada247b587eec Mon Sep 17 00:00:00 2001 From: Tatevik Date: Thu, 26 Nov 2026 13:24:42 +0400 Subject: [PATCH 06/14] ref: update autowire parameters for consistency and clarity --- config/config.yml | 2 +- config/parameters.yml | 87 ++++++++++--------- config/services/processor.yml | 6 +- config/services/services.yml | 38 ++++---- src/Domain/Common/IspRestrictionsProvider.php | 2 +- .../Common/Service/ExternalImageService.php | 2 +- src/Domain/Common/Service/UploadService.php | 2 +- .../Common/Storage/LocalUploadStorage.php | 2 +- .../Common/Validator/UploadValidator.php | 6 +- .../Service/MessagePlaceholderProcessor.php | 2 +- .../Placeholder/FooterValueResolver.php | 2 +- .../Identity/Service/AdminCopyEmailSender.php | 2 +- ...tachmentRepositoryNotificationProvider.php | 2 +- .../MailerDisabledNotificationProvider.php | 2 +- .../CampaignProcessorTestMessageHandler.php | 2 +- .../Messaging/Service/AttachmentAdder.php | 4 +- .../Service/AttachmentDownloadService.php | 2 +- .../CampaignMailContentBuilder.php | 2 +- src/Domain/Messaging/Service/EmailService.php | 4 +- .../Service/ForwardContentService.php | 2 +- .../Service/ForwardDeliveryService.php | 2 +- .../Messaging/Service/ForwardingGuard.php | 4 +- .../Service/ForwardingStatsService.php | 2 +- .../Service/MessageForwardService.php | 2 +- .../Service/SystemNotificationMailer.php | 2 +- 25 files changed, 93 insertions(+), 92 deletions(-) diff --git a/config/config.yml b/config/config.yml index ee324464..808cdc22 100644 --- a/config/config.yml +++ b/config/config.yml @@ -46,4 +46,4 @@ framework: php_errors: log: true mailer: - dsn: '%app.mailer_dsn%' + dsn: '%mailer.dsn%' diff --git a/config/parameters.yml b/config/parameters.yml index 1c330119..150f79aa 100644 --- a/config/parameters.yml +++ b/config/parameters.yml @@ -6,6 +6,7 @@ # The environment variables themselves are defined in the ".env" file (see ".env.dist" for the template) # and/or in the actual environment (e.g. Apache host configuration, command line). parameters: + # Database database.driver: '%env(PHPLIST_DATABASE_DRIVER)%' database.path: '%env(PHPLIST_DATABASE_PATH)%' database.host: '%env(PHPLIST_DATABASE_HOST)%' @@ -16,6 +17,7 @@ parameters: database.prefix: '%env(DATABASE_PREFIX)%' database.list_table_prefix: '%env(LIST_TABLE_PREFIX)%' + # Application app.dev_version: '%env(APP_DEV_VERSION)%' app.dev_email: '%env(APP_DEV_EMAIL)%' app.powered_by_phplist: '%env(APP_POWERED_BY_PHPLIST)%' @@ -26,34 +28,37 @@ parameters: # falls back to empty so existing .env files without APP_WEBSITE keep working (the value may live in the database) env(APP_WEBSITE): '' app.website: '%env(APP_WEBSITE)%' - app.parallel_use_with_phplist3: '%env(PARALLEL_USE_WITH_PHPLIST3)%' - - # Email configuration - app.mailer_from: '%env(MAILER_FROM)%' - app.mailer_dsn: '%env(MAILER_DSN)%' app.confirmation_url: '%env(CONFIRMATION_URL)%' app.subscription_confirmation_url: '%env(SUBSCRIPTION_CONFIRMATION_URL)%' app.password_reset_url: '%env(PASSWORD_RESET_URL)%' app.show_unsubscribe_link: '%env(SHOW_UNSUBSCRIBELINK)%' + app.verify_ssl: '%env(VERIFY_SSL)%' + app.public_schema: '%env(PUBLIC_SCHEMA)%' + # A secret key that's used to generate certain security-related tokens + app.secret: '%env(PHPLIST_SECRET)%' + + # Mailer + mailer.from: '%env(MAILER_FROM)%' + mailer.dsn: '%env(MAILER_DSN)%' - # bounce email settings - imap_bounce.email: '%env(BOUNCE_EMAIL)%' - imap_bounce.password: '%env(BOUNCE_IMAP_PASS)%' - imap_bounce.host: '%env(BOUNCE_IMAP_HOST)%' - imap_bounce.port: '%env(BOUNCE_IMAP_PORT)%' - imap_bounce.encryption: '%env(BOUNCE_IMAP_ENCRYPTION)%' - imap_bounce.mailbox: '%env(BOUNCE_IMAP_MAILBOX)%' - imap_bounce.mailbox_name: '%env(BOUNCE_IMAP_MAILBOX_NAME)%' - imap_bounce.protocol: '%env(BOUNCE_IMAP_PROTOCOL)%' - imap_bounce.unsubscribe_threshold: '%env(BOUNCE_IMAP_UNSUBSCRIBE_THRESHOLD)%' - imap_bounce.blacklist_threshold: '%env(BOUNCE_IMAP_BLACKLIST_THRESHOLD)%' - imap_bounce.purge: '%env(BOUNCE_IMAP_PURGE)%' - imap_bounce.purge_unprocessed: '%env(BOUNCE_IMAP_PURGE_UNPROCESSED)%' + # Bounce mailbox settings + bounce.email: '%env(BOUNCE_EMAIL)%' + bounce.imap.password: '%env(BOUNCE_IMAP_PASS)%' + bounce.imap.host: '%env(BOUNCE_IMAP_HOST)%' + bounce.imap.port: '%env(BOUNCE_IMAP_PORT)%' + bounce.imap.encryption: '%env(BOUNCE_IMAP_ENCRYPTION)%' + bounce.imap.mailbox: '%env(BOUNCE_IMAP_MAILBOX)%' + bounce.imap.mailbox_name: '%env(BOUNCE_IMAP_MAILBOX_NAME)%' + bounce.imap.protocol: '%env(BOUNCE_IMAP_PROTOCOL)%' + bounce.unsubscribe_threshold: '%env(BOUNCE_IMAP_UNSUBSCRIBE_THRESHOLD)%' + bounce.blacklist_threshold: '%env(BOUNCE_IMAP_BLACKLIST_THRESHOLD)%' + bounce.purge: '%env(BOUNCE_IMAP_PURGE)%' + bounce.purge_unprocessed: '%env(BOUNCE_IMAP_PURGE_UNPROCESSED)%' - # Messenger configuration for asynchronous processing - app.messenger_transport_dsn: '%env(MESSENGER_TRANSPORT_DSN)%' - app.search_transport_dsn: '%env(SEARCH_TRANSPORT_DSN)%' + # Messenger (asynchronous processing) + messenger.transport_dsn: '%env(MESSENGER_TRANSPORT_DSN)%' + messenger.search_transport_dsn: '%env(SEARCH_TRANSPORT_DSN)%' # Scheduler intervals (relative strings, empty disables), see docs/Scheduling.md # The env() lines are the defaults for installs whose .env predates these variables. @@ -66,7 +71,7 @@ parameters: app.schedule.tld_interval: '%env(PHPLIST_SCHEDULE_TLDS)%' app.schedule.cleanup_interval: '%env(PHPLIST_SCHEDULE_CLEANUP)%' - # Elasticsearch configuration + # Elasticsearch elasticsearch.enabled: '%env(bool:ELASTICSEARCH_ENABLED)%' elasticsearch.hosts: '%env(csv:ELASTICSEARCH_HOSTS)%' elasticsearch.username: '%env(ELASTICSEARCH_USERNAME)%' @@ -76,16 +81,19 @@ parameters: elasticsearch.request_timeout: '%env(int:ELASTICSEARCH_REQUEST_TIMEOUT)%' elasticsearch.purge.subscriber_history_retention: '%env(ELASTICSEARCH_PURGE_SUBSCRIBER_HISTORY_RETENTION)%' - # A secret key that's used to generate certain security-related tokens - app.secret: '%env(PHPLIST_SECRET)%' - phplist.verify_ssl: '%env(VERIFY_SSL)%' - + # Graylog graylog.host: 'graylog.phplist.local' graylog.port: 12201 - app.phplist_isp_conf_path: '%env(APP_PHPLIST_ISP_CONF_PATH)%' + # Uploads + uploads.images_dir: '%env(UPLOADIMAGES_DIR)%' + uploads.allowed_mime_types: ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'] + uploads.allowed_extensions: ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'] + uploads.max_size: '%env(PHPLIST_UPLOADS_MAX_SIZE)%' + uploads.max_avatar_size: '%env(MAX_AVATAR_SIZE)%' # Message sending + messaging.isp_conf_path: '%env(APP_PHPLIST_ISP_CONF_PATH)%' messaging.mail_queue_batch_size: '%env(MAILQUEUE_BATCH_SIZE)%' messaging.mail_queue_period: '%env(MAILQUEUE_BATCH_PERIOD)%' messaging.mail_queue_throttle: '%env(MAILQUEUE_THROTTLE)%' @@ -108,23 +116,16 @@ parameters: messaging.external_image_max_age: '%env(EXTERNALIMAGE_MAXAGE)%' messaging.external_image_timeout: '%env(EXTERNALIMAGE_TIMEOUT)%' messaging.external_image_max_size: '%env(EXTERNALIMAGE_MAXSIZE)%' - messaging.forward_alternative_content: '%env(FORWARD_ALTERNATIVE_CONTENT)%' messaging.email_text_credits: '%env(EMAILTEXTCREDITS)%' messaging.always_add_user_track: '%env(ALWAYS_ADD_USERTRACK)%' messaging.send_list_admin_copy: '%env(SEND_LISTADMIN_COPY)%' - phplist.forward_email_period: '%env(FORWARD_EMAIL_PERIOD)%' - phplist.forward_email_count: '%env(FORWARD_EMAIL_COUNT)%' - phplist.forward_personal_note_size: '%env(FORWARD_PERSONAL_NOTE_SIZE)%' - phplist.forward_friend_count_attribute: '%env(FORWARD_FRIEND_COUNT_ATTRIBUTE)%' - phplist.keep_forwarded_attributes: '%env(KEEPFORWARDERATTRIBUTES)%' - - phplist.upload_images_dir: '%env(UPLOADIMAGES_DIR)%' - phplist.uploads.allowed_mime_types: ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'] - phplist.uploads.allowed_extensions: ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'] - phplist.uploads.max_size: '%env(PHPLIST_UPLOADS_MAX_SIZE)%' - - phplist.public_schema: '%env(PUBLIC_SCHEMA)%' - phplist.attachment_download_url: '%env(PHPLIST_ATTACHMENT_DOWNLOAD_URL)%' - phplist.attachment_repository_path: '%env(PHPLIST_ATTACHMENT_REPOSITORY_PATH)%' - phplist.max_avatar_size: '%env(MAX_AVATAR_SIZE)%' + # Forwarding and attachments + messaging.forward.alternative_content: '%env(FORWARD_ALTERNATIVE_CONTENT)%' + messaging.forward.email_period: '%env(FORWARD_EMAIL_PERIOD)%' + messaging.forward.email_count: '%env(FORWARD_EMAIL_COUNT)%' + messaging.forward.personal_note_size: '%env(FORWARD_PERSONAL_NOTE_SIZE)%' + messaging.forward.friend_count_attribute: '%env(FORWARD_FRIEND_COUNT_ATTRIBUTE)%' + messaging.forward.keep_attributes: '%env(KEEPFORWARDERATTRIBUTES)%' + messaging.attachment.download_url: '%env(PHPLIST_ATTACHMENT_DOWNLOAD_URL)%' + messaging.attachment.repository_path: '%env(PHPLIST_ATTACHMENT_REPOSITORY_PATH)%' diff --git a/config/services/processor.yml b/config/services/processor.yml index 8ff38bf4..8615d8fe 100644 --- a/config/services/processor.yml +++ b/config/services/processor.yml @@ -6,9 +6,9 @@ services: PhpList\Core\Domain\Messaging\Service\Processor\PopBounceProcessor: arguments: - $host: '%imap_bounce.host%' - $port: '%imap_bounce.port%' - $mailboxNames: '%imap_bounce.mailbox_name%' + $host: '%bounce.imap.host%' + $port: '%bounce.imap.port%' + $mailboxNames: '%bounce.imap.mailbox_name%' tags: ['phplist.bounce_protocol_processor'] PhpList\Core\Domain\Messaging\Service\Processor\MboxBounceProcessor: diff --git a/config/services/services.yml b/config/services/services.yml index 7b97a054..25fa898b 100644 --- a/config/services/services.yml +++ b/config/services/services.yml @@ -174,10 +174,10 @@ services: arguments: $documentRoot: '%kernel.project_dir%/public' # Reuse upload_images_dir for editorImagesDir if a dedicated parameter is absent - $editorImagesDir: '%phplist.upload_images_dir%' + $editorImagesDir: '%uploads.images_dir%' $embedExternalImages: '%messaging.embed_external_images%' $embedUploadedImages: '%messaging.embed_uploaded_images%' - $uploadImagesDir: '%phplist.upload_images_dir%' + $uploadImagesDir: '%uploads.images_dir%' PhpList\Core\Domain\Messaging\Service\RateLimitedCampaignMailer: autowire: true @@ -187,8 +187,8 @@ services: autowire: true autoconfigure: true arguments: - $unsubscribeThreshold: '%imap_bounce.unsubscribe_threshold%' - $blacklistThreshold: '%imap_bounce.blacklist_threshold%' + $unsubscribeThreshold: '%bounce.unsubscribe_threshold%' + $blacklistThreshold: '%bounce.blacklist_threshold%' Webklex\PHPIMAP\ClientManager: ~ @@ -196,32 +196,32 @@ services: autowire: true autoconfigure: true arguments: - $mailbox: '%imap_bounce.mailbox%'# e.g. "{imap.example.com:993/imap/ssl}INBOX" or "/var/mail/user" - $host: '%imap_bounce.host%' - $port: '%imap_bounce.port%' - $encryption: '%imap_bounce.encryption%' - $username: '%imap_bounce.email%' - $password: '%imap_bounce.password%' - $protocol: '%imap_bounce.protocol%' + $mailbox: '%bounce.imap.mailbox%'# e.g. "{imap.example.com:993/imap/ssl}INBOX" or "/var/mail/user" + $host: '%bounce.imap.host%' + $port: '%bounce.imap.port%' + $encryption: '%bounce.imap.encryption%' + $username: '%bounce.email%' + $password: '%bounce.imap.password%' + $protocol: '%bounce.imap.protocol%' PhpList\Core\Domain\Common\Mail\NativeImapMailReader: arguments: - $username: '%imap_bounce.email%' - $password: '%imap_bounce.password%' + $username: '%bounce.email%' + $password: '%bounce.imap.password%' PhpList\Core\Domain\Messaging\Service\NativeBounceProcessingService: autowire: true autoconfigure: true arguments: - $purgeProcessed: '%imap_bounce.purge%' - $purgeUnprocessed: '%imap_bounce.purge_unprocessed%' + $purgeProcessed: '%bounce.purge%' + $purgeUnprocessed: '%bounce.purge_unprocessed%' PhpList\Core\Domain\Messaging\Service\WebklexBounceProcessingService: autowire: true autoconfigure: true arguments: - $purgeProcessed: '%imap_bounce.purge%' - $purgeUnprocessed: '%imap_bounce.purge_unprocessed%' + $purgeProcessed: '%bounce.purge%' + $purgeUnprocessed: '%bounce.purge_unprocessed%' PhpList\Core\Domain\Messaging\Service\LockService: autowire: true @@ -339,8 +339,8 @@ services: autoconfigure: true arguments: $useManualTextPart: '%messaging.use_manual_text_part%' - $uploadImageDir: '%phplist.upload_images_dir%' - $publicSchema: '%phplist.public_schema%' + $uploadImageDir: '%uploads.images_dir%' + $publicSchema: '%app.public_schema%' PhpList\Core\Domain\Common\Service\UploadService: autowire: true diff --git a/src/Domain/Common/IspRestrictionsProvider.php b/src/Domain/Common/IspRestrictionsProvider.php index 9708f8ea..f55908bb 100644 --- a/src/Domain/Common/IspRestrictionsProvider.php +++ b/src/Domain/Common/IspRestrictionsProvider.php @@ -12,7 +12,7 @@ class IspRestrictionsProvider { public function __construct( private readonly LoggerInterface $logger, - #[Autowire('%app.phplist_isp_conf_path%')]private readonly string $confPath, + #[Autowire('%messaging.isp_conf_path%')]private readonly string $confPath, ) { } diff --git a/src/Domain/Common/Service/ExternalImageService.php b/src/Domain/Common/Service/ExternalImageService.php index 4f2314e2..26dd301c 100644 --- a/src/Domain/Common/Service/ExternalImageService.php +++ b/src/Domain/Common/Service/ExternalImageService.php @@ -19,7 +19,7 @@ public function __construct( private readonly string $tempDir, private readonly int $externalImageMaxAge, private readonly int $externalImageMaxSize, - #[Autowire('%phplist.verify_ssl%')] private readonly bool $verifySsl = true, + #[Autowire('%app.verify_ssl%')] private readonly bool $verifySsl = true, private readonly ?int $externalImageTimeout = 30, ) { $this->externalCacheDir = $this->tempDir . '/external_cache'; diff --git a/src/Domain/Common/Service/UploadService.php b/src/Domain/Common/Service/UploadService.php index db73d1fb..7cb50102 100644 --- a/src/Domain/Common/Service/UploadService.php +++ b/src/Domain/Common/Service/UploadService.php @@ -20,7 +20,7 @@ public function __construct( private readonly UploadValidator $validator, private readonly UploadStorageInterface $storage, private readonly RequestStack $requestStack, - #[Autowire('%phplist.upload_images_dir%')] + #[Autowire('%uploads.images_dir%')] private readonly string $uploadDirectory, private readonly TranslatorInterface $translator, ) { diff --git a/src/Domain/Common/Storage/LocalUploadStorage.php b/src/Domain/Common/Storage/LocalUploadStorage.php index 52a6cc32..8c38dfdf 100644 --- a/src/Domain/Common/Storage/LocalUploadStorage.php +++ b/src/Domain/Common/Storage/LocalUploadStorage.php @@ -16,7 +16,7 @@ class LocalUploadStorage implements UploadStorageInterface public function __construct( #[Autowire('%kernel.application_dir%')] private readonly string $projectDir, - #[Autowire('%phplist.upload_images_dir%')] + #[Autowire('%uploads.images_dir%')] private readonly string $uploadDirectory, private readonly TranslatorInterface $translator, ) { diff --git a/src/Domain/Common/Validator/UploadValidator.php b/src/Domain/Common/Validator/UploadValidator.php index 55447afd..9fbe4902 100644 --- a/src/Domain/Common/Validator/UploadValidator.php +++ b/src/Domain/Common/Validator/UploadValidator.php @@ -20,11 +20,11 @@ class UploadValidator * @param string[] $allowedExtensions */ public function __construct( - #[Autowire('%phplist.uploads.allowed_mime_types%')] + #[Autowire('%uploads.allowed_mime_types%')] private readonly array $allowedMimeTypes, - #[Autowire('%phplist.uploads.allowed_extensions%')] + #[Autowire('%uploads.allowed_extensions%')] private readonly array $allowedExtensions, - #[Autowire('%phplist.uploads.max_size%')] + #[Autowire('%uploads.max_size%')] private readonly string $maxSize, private readonly TranslatorInterface $translator, ) { diff --git a/src/Domain/Configuration/Service/MessagePlaceholderProcessor.php b/src/Domain/Configuration/Service/MessagePlaceholderProcessor.php index f0443f4a..ee10c9a3 100644 --- a/src/Domain/Configuration/Service/MessagePlaceholderProcessor.php +++ b/src/Domain/Configuration/Service/MessagePlaceholderProcessor.php @@ -30,7 +30,7 @@ public function __construct( /** @var iterable */ private readonly iterable $supportingResolvers, #[Autowire('%messaging.always_add_user_track%')] private readonly bool $alwaysAddUserTrack, - #[Autowire('%phplist.keep_forwarded_attributes%')] private readonly bool $keepForwardedAttributes, + #[Autowire('%messaging.forward.keep_attributes%')] private readonly bool $keepForwardedAttributes, ) { } diff --git a/src/Domain/Configuration/Service/Placeholder/FooterValueResolver.php b/src/Domain/Configuration/Service/Placeholder/FooterValueResolver.php index 96e66e77..1239a7d9 100644 --- a/src/Domain/Configuration/Service/Placeholder/FooterValueResolver.php +++ b/src/Domain/Configuration/Service/Placeholder/FooterValueResolver.php @@ -13,7 +13,7 @@ final class FooterValueResolver implements PlaceholderValueResolverInterface { public function __construct( private readonly ConfigProvider $config, - #[Autowire('%messaging.forward_alternative_content%')] private readonly bool $forwardAlternativeContent, + #[Autowire('%messaging.forward.alternative_content%')] private readonly bool $forwardAlternativeContent, ) { } diff --git a/src/Domain/Identity/Service/AdminCopyEmailSender.php b/src/Domain/Identity/Service/AdminCopyEmailSender.php index 64e94645..c8c69079 100644 --- a/src/Domain/Identity/Service/AdminCopyEmailSender.php +++ b/src/Domain/Identity/Service/AdminCopyEmailSender.php @@ -23,7 +23,7 @@ public function __construct( private readonly MailerInterface $mailer, private readonly LoggerInterface $logger, #[Autowire('%messaging.send_list_admin_copy%')] private readonly bool $sendListAdminCopy, - #[Autowire('%imap_bounce.email%')] private readonly string $bounceEmail, + #[Autowire('%bounce.email%')] private readonly string $bounceEmail, private readonly string $installationName = 'phpList', ) { } diff --git a/src/Domain/Identity/Service/Notification/AttachmentRepositoryNotificationProvider.php b/src/Domain/Identity/Service/Notification/AttachmentRepositoryNotificationProvider.php index dbe951a6..b5adf653 100644 --- a/src/Domain/Identity/Service/Notification/AttachmentRepositoryNotificationProvider.php +++ b/src/Domain/Identity/Service/Notification/AttachmentRepositoryNotificationProvider.php @@ -17,7 +17,7 @@ class AttachmentRepositoryNotificationProvider implements AdminNotificationProvi { public function __construct( private readonly TranslatorInterface $translator, - #[Autowire('%phplist.attachment_repository_path%')] private readonly string $attachmentRepositoryPath = '/tmp', + #[Autowire('%messaging.attachment.repository_path%')] private readonly string $attachmentRepositoryPath = '/tmp', ) { } diff --git a/src/Domain/Identity/Service/Notification/MailerDisabledNotificationProvider.php b/src/Domain/Identity/Service/Notification/MailerDisabledNotificationProvider.php index 8109d4e4..c2270504 100644 --- a/src/Domain/Identity/Service/Notification/MailerDisabledNotificationProvider.php +++ b/src/Domain/Identity/Service/Notification/MailerDisabledNotificationProvider.php @@ -18,7 +18,7 @@ class MailerDisabledNotificationProvider implements AdminNotificationProviderInt { public function __construct( private readonly TranslatorInterface $translator, - #[Autowire('%app.mailer_dsn%')] private readonly string $mailerDsn, + #[Autowire('%mailer.dsn%')] private readonly string $mailerDsn, ) { } diff --git a/src/Domain/Messaging/MessageHandler/CampaignProcessorTestMessageHandler.php b/src/Domain/Messaging/MessageHandler/CampaignProcessorTestMessageHandler.php index 21895457..99965118 100644 --- a/src/Domain/Messaging/MessageHandler/CampaignProcessorTestMessageHandler.php +++ b/src/Domain/Messaging/MessageHandler/CampaignProcessorTestMessageHandler.php @@ -50,7 +50,7 @@ public function __construct( private readonly EmailBuilder $campaignEmailBuilder, private readonly MailSizeChecker $mailSizeChecker, private readonly ConfigProvider $configProvider, - #[Autowire('%imap_bounce.email%')] private readonly string $bounceEmail, + #[Autowire('%bounce.email%')] private readonly string $bounceEmail, ) { } diff --git a/src/Domain/Messaging/Service/AttachmentAdder.php b/src/Domain/Messaging/Service/AttachmentAdder.php index d6309992..a63b6a35 100644 --- a/src/Domain/Messaging/Service/AttachmentAdder.php +++ b/src/Domain/Messaging/Service/AttachmentAdder.php @@ -23,8 +23,8 @@ public function __construct( private readonly EventLogManager $eventLogManager, private readonly OnceCacheGuard $onceCacheGuard, private readonly FileHelper $fileHelper, - #[Autowire('%phplist.attachment_download_url%')] private readonly string $attachmentDownloadUrl, - #[Autowire('%phplist.attachment_repository_path%')] private readonly string $attachmentRepositoryPath = '/tmp', + #[Autowire('%messaging.attachment.download_url%')] private readonly string $attachmentDownloadUrl, + #[Autowire('%messaging.attachment.repository_path%')] private readonly string $attachmentRepositoryPath = '/tmp', ) { } diff --git a/src/Domain/Messaging/Service/AttachmentDownloadService.php b/src/Domain/Messaging/Service/AttachmentDownloadService.php index ecf32b60..fd045312 100644 --- a/src/Domain/Messaging/Service/AttachmentDownloadService.php +++ b/src/Domain/Messaging/Service/AttachmentDownloadService.php @@ -20,7 +20,7 @@ class AttachmentDownloadService public function __construct( private readonly SubscriberRepository $subscriberRepository, private readonly TranslatorInterface $translator, - #[Autowire('%phplist.attachment_repository_path%')] private readonly string $attachmentRepositoryPath = '/tmp', + #[Autowire('%messaging.attachment.repository_path%')] private readonly string $attachmentRepositoryPath = '/tmp', ) { } diff --git a/src/Domain/Messaging/Service/Constructor/CampaignMailContentBuilder.php b/src/Domain/Messaging/Service/Constructor/CampaignMailContentBuilder.php index 3d752bb2..d0b9ba7e 100644 --- a/src/Domain/Messaging/Service/Constructor/CampaignMailContentBuilder.php +++ b/src/Domain/Messaging/Service/Constructor/CampaignMailContentBuilder.php @@ -30,7 +30,7 @@ public function __construct( private readonly TextParser $textParser, private readonly MessagePlaceholderProcessor $placeholderProcessor, private readonly LinkTrackService $linkTrackService, - #[Autowire('%phplist.forward_personal_note_size%')] private readonly int $forwardPersonalNoteSize = 0, + #[Autowire('%messaging.forward.personal_note_size%')] private readonly int $forwardPersonalNoteSize = 0, ) { } diff --git a/src/Domain/Messaging/Service/EmailService.php b/src/Domain/Messaging/Service/EmailService.php index bced6a8b..7d18488b 100644 --- a/src/Domain/Messaging/Service/EmailService.php +++ b/src/Domain/Messaging/Service/EmailService.php @@ -17,8 +17,8 @@ class EmailService public function __construct( private readonly MailerInterface $mailer, private readonly MessageBusInterface $messageBus, - #[Autowire('%app.mailer_from%')] private readonly string $defaultFromEmail, - #[Autowire('%imap_bounce.email%')] private readonly string $bounceEmail, + #[Autowire('%mailer.from%')] private readonly string $defaultFromEmail, + #[Autowire('%bounce.email%')] private readonly string $bounceEmail, ) { } diff --git a/src/Domain/Messaging/Service/ForwardContentService.php b/src/Domain/Messaging/Service/ForwardContentService.php index 01d27388..28102be2 100644 --- a/src/Domain/Messaging/Service/ForwardContentService.php +++ b/src/Domain/Messaging/Service/ForwardContentService.php @@ -22,7 +22,7 @@ public function __construct( private readonly CacheInterface $cache, private readonly ForwardEmailBuilder $forwardEmailBuilder, private readonly MessagePrecacheService $precacheService, - #[Autowire('%messaging.forward_alternative_content%')] private readonly bool $forwardAlternativeContent = false, + #[Autowire('%messaging.forward.alternative_content%')] private readonly bool $forwardAlternativeContent = false, ) { } diff --git a/src/Domain/Messaging/Service/ForwardDeliveryService.php b/src/Domain/Messaging/Service/ForwardDeliveryService.php index 9bec169e..78de4586 100644 --- a/src/Domain/Messaging/Service/ForwardDeliveryService.php +++ b/src/Domain/Messaging/Service/ForwardDeliveryService.php @@ -19,7 +19,7 @@ class ForwardDeliveryService public function __construct( private readonly MailerInterface $mailer, private readonly UserMessageForwardManager $messageForwardManager, - #[Autowire('%imap_bounce.email%')] private readonly string $bounceEmail, + #[Autowire('%bounce.email%')] private readonly string $bounceEmail, ) { } diff --git a/src/Domain/Messaging/Service/ForwardingGuard.php b/src/Domain/Messaging/Service/ForwardingGuard.php index 51264dc2..28ca9720 100644 --- a/src/Domain/Messaging/Service/ForwardingGuard.php +++ b/src/Domain/Messaging/Service/ForwardingGuard.php @@ -20,8 +20,8 @@ public function __construct( private readonly SubscriberRepository $subscriberRepository, private readonly UserMessageRepository $userMessageRepository, private readonly UserMessageForwardRepository $forwardRepository, - #[Autowire('%phplist.forward_email_count%')] private readonly int $forwardMessageCount, - #[Autowire('%phplist.forward_email_period%')] private readonly string $forwardEmailPeriod, + #[Autowire('%messaging.forward.email_count%')] private readonly int $forwardMessageCount, + #[Autowire('%messaging.forward.email_period%')] private readonly string $forwardEmailPeriod, ) { } diff --git a/src/Domain/Messaging/Service/ForwardingStatsService.php b/src/Domain/Messaging/Service/ForwardingStatsService.php index 0e7ed518..5589ee6b 100644 --- a/src/Domain/Messaging/Service/ForwardingStatsService.php +++ b/src/Domain/Messaging/Service/ForwardingStatsService.php @@ -25,7 +25,7 @@ class ForwardingStatsService public function __construct( private readonly SubscriberAttributeValueRepository $subscriberAttributeValueRepo, private readonly SubscriberAttributeManager $subscriberAttributeManager, - #[Autowire('%phplist.forward_friend_count_attribute%')] string $forwardFriendCountAttr, + #[Autowire('%messaging.forward.friend_count_attribute%')] string $forwardFriendCountAttr, ) { $forwardFriendCountAttr = trim($forwardFriendCountAttr); $this->forwardFriendCountAttribute = $forwardFriendCountAttr !== '' ? $forwardFriendCountAttr : null; diff --git a/src/Domain/Messaging/Service/MessageForwardService.php b/src/Domain/Messaging/Service/MessageForwardService.php index ec4062cb..d97c2efd 100644 --- a/src/Domain/Messaging/Service/MessageForwardService.php +++ b/src/Domain/Messaging/Service/MessageForwardService.php @@ -27,7 +27,7 @@ public function __construct( private readonly MessagePrecacheService $precacheService, private readonly AdminNotifier $adminNotifier, private readonly ForwardingStatsService $forwardingStatsService, - #[Autowire('%messaging.forward_alternative_content%')] private readonly bool $forwardAlternativeContent = false, + #[Autowire('%messaging.forward.alternative_content%')] private readonly bool $forwardAlternativeContent = false, ) { } diff --git a/src/Domain/Messaging/Service/SystemNotificationMailer.php b/src/Domain/Messaging/Service/SystemNotificationMailer.php index 160ad669..1b28f378 100644 --- a/src/Domain/Messaging/Service/SystemNotificationMailer.php +++ b/src/Domain/Messaging/Service/SystemNotificationMailer.php @@ -20,7 +20,7 @@ class SystemNotificationMailer public function __construct( private readonly SystemEmailBuilder $systemEmailBuilder, private readonly MailerInterface $mailer, - #[Autowire('%imap_bounce.email%')] private readonly string $bounceEmail, + #[Autowire('%bounce.email%')] private readonly string $bounceEmail, ) { } From ef7bbc0b7f1846db0168a888a92558db56da3ba0 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Thu, 26 Nov 2026 13:38:07 +0400 Subject: [PATCH 07/14] ref: update Symfony CLI installation path in CI configuration --- .github/workflows/ci.yml | 3 ++- .../AttachmentRepositoryNotificationProvider.php | 3 ++- src/Domain/Messaging/Service/AttachmentAdder.php | 6 ++++-- src/Domain/Messaging/Service/AttachmentDownloadService.php | 3 ++- 4 files changed, 10 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 986afd9c..e7be80bc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,7 +46,8 @@ jobs: - name: Install Symfony CLI run: | curl -sS https://get.symfony.com/cli/installer | bash - mv $HOME/.symfony*/bin/symfony /usr/local/bin/symfony + echo "$HOME/.config/symfony-cli/bin" >> "$GITHUB_PATH" + export PATH="$HOME/.config/symfony-cli/bin:$PATH" symfony version - name: Start mysql service run: sudo /etc/init.d/mysql start diff --git a/src/Domain/Identity/Service/Notification/AttachmentRepositoryNotificationProvider.php b/src/Domain/Identity/Service/Notification/AttachmentRepositoryNotificationProvider.php index b5adf653..cd702367 100644 --- a/src/Domain/Identity/Service/Notification/AttachmentRepositoryNotificationProvider.php +++ b/src/Domain/Identity/Service/Notification/AttachmentRepositoryNotificationProvider.php @@ -17,7 +17,8 @@ class AttachmentRepositoryNotificationProvider implements AdminNotificationProvi { public function __construct( private readonly TranslatorInterface $translator, - #[Autowire('%messaging.attachment.repository_path%')] private readonly string $attachmentRepositoryPath = '/tmp', + #[Autowire('%messaging.attachment.repository_path%')] + private readonly string $attachmentRepositoryPath = '/tmp', ) { } diff --git a/src/Domain/Messaging/Service/AttachmentAdder.php b/src/Domain/Messaging/Service/AttachmentAdder.php index a63b6a35..72d487a4 100644 --- a/src/Domain/Messaging/Service/AttachmentAdder.php +++ b/src/Domain/Messaging/Service/AttachmentAdder.php @@ -23,8 +23,10 @@ public function __construct( private readonly EventLogManager $eventLogManager, private readonly OnceCacheGuard $onceCacheGuard, private readonly FileHelper $fileHelper, - #[Autowire('%messaging.attachment.download_url%')] private readonly string $attachmentDownloadUrl, - #[Autowire('%messaging.attachment.repository_path%')] private readonly string $attachmentRepositoryPath = '/tmp', + #[Autowire('%messaging.attachment.download_url%')] + private readonly string $attachmentDownloadUrl, + #[Autowire('%messaging.attachment.repository_path%')] + private readonly string $attachmentRepositoryPath = '/tmp', ) { } diff --git a/src/Domain/Messaging/Service/AttachmentDownloadService.php b/src/Domain/Messaging/Service/AttachmentDownloadService.php index fd045312..eb359f3a 100644 --- a/src/Domain/Messaging/Service/AttachmentDownloadService.php +++ b/src/Domain/Messaging/Service/AttachmentDownloadService.php @@ -20,7 +20,8 @@ class AttachmentDownloadService public function __construct( private readonly SubscriberRepository $subscriberRepository, private readonly TranslatorInterface $translator, - #[Autowire('%messaging.attachment.repository_path%')] private readonly string $attachmentRepositoryPath = '/tmp', + #[Autowire('%messaging.attachment.repository_path%')] + private readonly string $attachmentRepositoryPath = '/tmp', ) { } From d93c2c8328efda0f5bce13e31e6a5eefae6efff5 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Thu, 26 Nov 2026 14:14:58 +0400 Subject: [PATCH 08/14] ref: update cache key format to use dot notation for consistency --- .../Service/Provider/ConfigProvider.php | 13 +++++++++++-- .../Messaging/Service/CampaignSendingLoop.php | 1 - .../Service/Provider/ConfigProviderTest.php | 12 ++++++------ 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/src/Domain/Configuration/Service/Provider/ConfigProvider.php b/src/Domain/Configuration/Service/Provider/ConfigProvider.php index ed182c0b..ddfaafeb 100644 --- a/src/Domain/Configuration/Service/Provider/ConfigProvider.php +++ b/src/Domain/Configuration/Service/Provider/ConfigProvider.php @@ -58,7 +58,7 @@ public function getValue(ConfigOption $key): ?string if (in_array($key, $this->booleanValues)) { throw new InvalidArgumentException('Key is a boolean value, use isEnabled instead'); } - $cacheKey = 'cfg:' . $key->value; + $cacheKey = $this->cacheKey($key->value); $value = $this->cache->get($cacheKey); if ($value === null) { $value = $this->configRepository->findValueByItem($key->value); @@ -88,6 +88,15 @@ private function replaceBuiltInPlaceholders(string $value, ConfigOption $key): s return $value; } + /** + * PSR-6/PSR-16 reserve the characters {}()/\@: in cache keys, but config keys may contain them + * (e.g. "subscribemessage:1"), so they are replaced. + */ + private function cacheKey(string $configKey): string + { + return 'cfg.' . preg_replace('/[{}()\/\\\\@:]/', '.', $configKey); + } + public function getValueWithNamespace(ConfigOption|string $key): ?string { if ($key instanceof ConfigOption) { @@ -95,7 +104,7 @@ public function getValueWithNamespace(ConfigOption|string $key): ?string $keyValue = $key->value; } else { $keyValue = $key; - $cacheKey = 'cfg:' . $keyValue; + $cacheKey = $this->cacheKey($keyValue); $full = $this->cache->get($cacheKey); if ($full === null) { $full = $this->configRepository->findValueByItem($keyValue); diff --git a/src/Domain/Messaging/Service/CampaignSendingLoop.php b/src/Domain/Messaging/Service/CampaignSendingLoop.php index 0f12cfc8..3a6c605c 100644 --- a/src/Domain/Messaging/Service/CampaignSendingLoop.php +++ b/src/Domain/Messaging/Service/CampaignSendingLoop.php @@ -113,7 +113,6 @@ public function run(Message $campaign, array $subscribers, string $cacheKey): bo 'campaign_id' => $campaign->getId(), 'subscriber_id' => $subscriber->getId(), ]); - // todo: maybe catch exception and return false to stop early? $this->emailSender->send($campaign, $subscriber, $userMessage, $messagePrecacheDto); } diff --git a/tests/Unit/Domain/Configuration/Service/Provider/ConfigProviderTest.php b/tests/Unit/Domain/Configuration/Service/Provider/ConfigProviderTest.php index d51d33f9..db5b9b0f 100644 --- a/tests/Unit/Domain/Configuration/Service/Provider/ConfigProviderTest.php +++ b/tests/Unit/Domain/Configuration/Service/Provider/ConfigProviderTest.php @@ -119,7 +119,7 @@ public function testGetValueRejectsBooleanKeys(): void public function testGetValueReturnsFromCacheWhenPresent(): void { $key = $this->pickNonBooleanCase(); - $cacheKey = 'cfg:' . $key->value; + $cacheKey = 'cfg.' . $key->value; $this->cache ->expects($this->once()) @@ -137,7 +137,7 @@ public function testGetValueReturnsFromCacheWhenPresent(): void public function testGetValueLoadsFromRepoAndCachesWhenCacheMiss(): void { $key = $this->pickNonBooleanCase(); - $cacheKey = 'cfg:' . $key->value; + $cacheKey = 'cfg.' . $key->value; $this->cache ->expects($this->once()) @@ -165,7 +165,7 @@ public function testGetValueLoadsFromRepoAndCachesWhenCacheMiss(): void public function testGetValueFallsBackToDefaultConfigsWhenNoCacheAndNoRepo(): void { $key = $this->pickNonBooleanCase(); - $cacheKey = 'cfg:' . $key->value; + $cacheKey = 'cfg.' . $key->value; $this->cache ->expects($this->once()) @@ -202,7 +202,7 @@ public function testGetValueFallsBackToDefaultConfigsWhenNoCacheAndNoRepo(): voi public function testGetValueReturnsNullWhenNoCacheNoRepoNoDefault(): void { $key = $this->pickNonBooleanCase(); - $cacheKey = 'cfg:' . $key->value; + $cacheKey = 'cfg.' . $key->value; $this->cache->expects($this->once())->method('get')->with($cacheKey)->willReturn(null); $this->repo->expects($this->once())->method('findValueByItem')->with($key->value)->willReturn(null); @@ -230,8 +230,8 @@ public function testGetValueWithNamespaceSupportsStringNamespacedKey(): void $this->cache ->method('get') ->willReturnMap([ - ['cfg:subscribemessage:1', null], - ['cfg:subscribemessage', 'PARENT'], + ['cfg.subscribemessage.1', null], + ['cfg.subscribemessage', 'PARENT'], ]); $this->repo From 664e49b006d541f56dcc62ee4c12bd03d6ebb844 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Thu, 26 Nov 2026 19:52:31 +0400 Subject: [PATCH 09/14] feat: add locale support for subscriber emails --- config/services/resolvers.yml | 2 + resources/translations/messages.de.xlf | 64 +++++++++++++ resources/translations/messages.es.xlf | 64 +++++++++++++ resources/translations/messages.fr.xlf | 64 +++++++++++++ .../Service/Manager/PasswordManager.php | 12 ++- .../Message/PasswordResetMessage.php | 12 ++- .../Message/SubscriberConfirmationMessage.php | 13 ++- .../PasswordResetMessageHandler.php | 18 ++-- .../SubscriberConfirmationMessageHandler.php | 35 +++++-- .../Resolver/SubscriberLocaleResolver.php | 96 +++++++++++++++++++ .../Identity/Service/PasswordManagerTest.php | 24 +++++ .../SubscriberConfirmationMessageTest.php | 6 ++ .../PasswordResetMessageHandlerTest.php | 22 +++++ ...bscriberConfirmationMessageHandlerTest.php | 75 ++++++++++++++- .../Resolver/SubscriberLocaleResolverTest.php | 88 +++++++++++++++++ 15 files changed, 576 insertions(+), 19 deletions(-) create mode 100644 resources/translations/messages.de.xlf create mode 100644 resources/translations/messages.es.xlf create mode 100644 resources/translations/messages.fr.xlf create mode 100644 src/Domain/Subscription/Service/Resolver/SubscriberLocaleResolver.php create mode 100644 tests/Unit/Domain/Subscription/Service/Resolver/SubscriberLocaleResolverTest.php diff --git a/config/services/resolvers.yml b/config/services/resolvers.yml index 64c97389..591febb4 100644 --- a/config/services/resolvers.yml +++ b/config/services/resolvers.yml @@ -28,3 +28,5 @@ services: PhpList\Core\Domain\Configuration\Service\Placeholder\: resource: '../../src/Domain/Configuration/Service/Placeholder/*' + + PhpList\Core\Domain\Subscription\Service\Resolver\SubscriberLocaleResolver: ~ diff --git a/resources/translations/messages.de.xlf b/resources/translations/messages.de.xlf new file mode 100644 index 00000000..005deab6 --- /dev/null +++ b/resources/translations/messages.de.xlf @@ -0,0 +1,64 @@ + + + +
+ +
+ + + Please confirm your subscription + Bitte bestätigen Sie Ihr Abonnement + + + Thank you for subscribing! + +Please confirm your subscription by clicking the link below: + +%confirmation_link% + +If you did not request this subscription, please ignore this email. + Vielen Dank für Ihre Anmeldung! + +Bitte bestätigen Sie Ihr Abonnement, indem Sie auf den folgenden Link klicken: + +%confirmation_link% + +Wenn Sie dieses Abonnement nicht angefordert haben, ignorieren Sie diese E-Mail bitte. + + + <p>Thank you for subscribing!</p><p>Please confirm your subscription by clicking the link below:</p><p><a href="%confirmation_link%">Confirm Subscription</a></p><p>If you did not request this subscription, please ignore this email.</p> + <p>Vielen Dank für Ihre Anmeldung!</p><p>Bitte bestätigen Sie Ihr Abonnement, indem Sie auf den folgenden Link klicken:</p><p><a href="%confirmation_link%">Abonnement bestätigen</a></p><p>Wenn Sie dieses Abonnement nicht angefordert haben, ignorieren Sie diese E-Mail bitte.</p> + + + Password Reset Request + Passwort zurücksetzen + + + Hello, + +A password reset has been requested for your account. +Please use the following token to reset your password: + +%token% + +If you did not request this password reset, please ignore this email. + +Thank you. + Hallo, + +Für Ihr Konto wurde das Zurücksetzen des Passworts angefordert. +Bitte verwenden Sie das folgende Token, um Ihr Passwort zurückzusetzen: + +%token% + +Wenn Sie das Zurücksetzen nicht angefordert haben, ignorieren Sie diese E-Mail bitte. + +Vielen Dank. + + + <p>Password Reset Request!</p><p>Hello! A password reset has been requested for your account.</p><p>Please use the following token to reset your password:</p><p><a href="%confirmation_link%">Reset Password</a></p><p>If you did not request this password reset, please ignore this email.</p><p>Thank you.</p> + <p>Anfrage zum Zurücksetzen des Passworts!</p><p>Hallo! Für Ihr Konto wurde das Zurücksetzen des Passworts angefordert.</p><p>Bitte verwenden Sie das folgende Token, um Ihr Passwort zurückzusetzen:</p><p><a href="%confirmation_link%">Passwort zurücksetzen</a></p><p>Wenn Sie das Zurücksetzen nicht angefordert haben, ignorieren Sie diese E-Mail bitte.</p><p>Vielen Dank.</p> + + +
+
diff --git a/resources/translations/messages.es.xlf b/resources/translations/messages.es.xlf new file mode 100644 index 00000000..19802b77 --- /dev/null +++ b/resources/translations/messages.es.xlf @@ -0,0 +1,64 @@ + + + +
+ +
+ + + Please confirm your subscription + Por favor, confirme su suscripción + + + Thank you for subscribing! + +Please confirm your subscription by clicking the link below: + +%confirmation_link% + +If you did not request this subscription, please ignore this email. + ¡Gracias por suscribirse! + +Por favor, confirme su suscripción haciendo clic en el siguiente enlace: + +%confirmation_link% + +Si no solicitó esta suscripción, ignore este correo electrónico. + + + <p>Thank you for subscribing!</p><p>Please confirm your subscription by clicking the link below:</p><p><a href="%confirmation_link%">Confirm Subscription</a></p><p>If you did not request this subscription, please ignore this email.</p> + <p>¡Gracias por suscribirse!</p><p>Por favor, confirme su suscripción haciendo clic en el siguiente enlace:</p><p><a href="%confirmation_link%">Confirmar suscripción</a></p><p>Si no solicitó esta suscripción, ignore este correo electrónico.</p> + + + Password Reset Request + Restablecimiento de contraseña + + + Hello, + +A password reset has been requested for your account. +Please use the following token to reset your password: + +%token% + +If you did not request this password reset, please ignore this email. + +Thank you. + Hola, + +Se ha solicitado restablecer la contraseña de su cuenta. +Utilice el siguiente token para restablecer su contraseña: + +%token% + +Si no solicitó este restablecimiento, ignore este correo electrónico. + +Gracias. + + + <p>Password Reset Request!</p><p>Hello! A password reset has been requested for your account.</p><p>Please use the following token to reset your password:</p><p><a href="%confirmation_link%">Reset Password</a></p><p>If you did not request this password reset, please ignore this email.</p><p>Thank you.</p> + <p>¡Solicitud de restablecimiento de contraseña!</p><p>¡Hola! Se ha solicitado restablecer la contraseña de su cuenta.</p><p>Utilice el siguiente token para restablecer su contraseña:</p><p><a href="%confirmation_link%">Restablecer contraseña</a></p><p>Si no solicitó este restablecimiento, ignore este correo electrónico.</p><p>Gracias.</p> + + +
+
diff --git a/resources/translations/messages.fr.xlf b/resources/translations/messages.fr.xlf new file mode 100644 index 00000000..527454f2 --- /dev/null +++ b/resources/translations/messages.fr.xlf @@ -0,0 +1,64 @@ + + + +
+ +
+ + + Please confirm your subscription + Veuillez confirmer votre inscription + + + Thank you for subscribing! + +Please confirm your subscription by clicking the link below: + +%confirmation_link% + +If you did not request this subscription, please ignore this email. + Merci de votre inscription ! + +Veuillez confirmer votre inscription en cliquant sur le lien ci-dessous : + +%confirmation_link% + +Si vous n'avez pas demandé cette inscription, veuillez ignorer cet e-mail. + + + <p>Thank you for subscribing!</p><p>Please confirm your subscription by clicking the link below:</p><p><a href="%confirmation_link%">Confirm Subscription</a></p><p>If you did not request this subscription, please ignore this email.</p> + <p>Merci de votre inscription !</p><p>Veuillez confirmer votre inscription en cliquant sur le lien ci-dessous :</p><p><a href="%confirmation_link%">Confirmer l'inscription</a></p><p>Si vous n'avez pas demandé cette inscription, veuillez ignorer cet e-mail.</p> + + + Password Reset Request + Réinitialisation du mot de passe + + + Hello, + +A password reset has been requested for your account. +Please use the following token to reset your password: + +%token% + +If you did not request this password reset, please ignore this email. + +Thank you. + Bonjour, + +Une réinitialisation du mot de passe a été demandée pour votre compte. +Veuillez utiliser le jeton suivant pour réinitialiser votre mot de passe : + +%token% + +Si vous n'avez pas demandé cette réinitialisation, veuillez ignorer cet e-mail. + +Merci. + + + <p>Password Reset Request!</p><p>Hello! A password reset has been requested for your account.</p><p>Please use the following token to reset your password:</p><p><a href="%confirmation_link%">Reset Password</a></p><p>If you did not request this password reset, please ignore this email.</p><p>Thank you.</p> + <p>Demande de réinitialisation du mot de passe !</p><p>Bonjour ! Une réinitialisation du mot de passe a été demandée pour votre compte.</p><p>Veuillez utiliser le jeton suivant pour réinitialiser votre mot de passe :</p><p><a href="%confirmation_link%">Réinitialiser le mot de passe</a></p><p>Si vous n'avez pas demandé cette réinitialisation, veuillez ignorer cet e-mail.</p><p>Merci.</p> + + +
+
diff --git a/src/Domain/Identity/Service/Manager/PasswordManager.php b/src/Domain/Identity/Service/Manager/PasswordManager.php index 28b5bbbe..9cbd1583 100644 --- a/src/Domain/Identity/Service/Manager/PasswordManager.php +++ b/src/Domain/Identity/Service/Manager/PasswordManager.php @@ -13,6 +13,7 @@ use PhpList\Core\Domain\Identity\Service\HashGenerator; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Messenger\MessageBusInterface; +use Symfony\Contracts\Translation\LocaleAwareInterface; use Symfony\Contracts\Translation\TranslatorInterface; class PasswordManager @@ -67,7 +68,11 @@ public function generatePasswordResetToken(string $email): string $this->passwordRequestRepository->persist($passwordRequest); - $message = new PasswordResetMessage(email: $email, token: $token); + $message = new PasswordResetMessage( + email: $email, + token: $token, + locale: $this->requestLocale(), + ); $this->messageBus->dispatch($message); return $token; @@ -134,4 +139,9 @@ public function cleanupExpiredTokens(): void } } } + + private function requestLocale(): ?string + { + return $this->translator instanceof LocaleAwareInterface ? $this->translator->getLocale() : null; + } } diff --git a/src/Domain/Messaging/Message/PasswordResetMessage.php b/src/Domain/Messaging/Message/PasswordResetMessage.php index 3c2aee17..696bb9d8 100644 --- a/src/Domain/Messaging/Message/PasswordResetMessage.php +++ b/src/Domain/Messaging/Message/PasswordResetMessage.php @@ -8,11 +8,13 @@ class PasswordResetMessage { private string $email; private string $token; + private ?string $locale; - public function __construct(string $email, string $token) + public function __construct(string $email, string $token, ?string $locale = null) { $this->email = $email; $this->token = $token; + $this->locale = $locale; } public function getEmail(): string @@ -24,4 +26,12 @@ public function getToken(): string { return $this->token; } + + /** + * Locale of the request that asked for the reset; null means the default locale. + */ + public function getLocale(): ?string + { + return $this->locale; + } } diff --git a/src/Domain/Messaging/Message/SubscriberConfirmationMessage.php b/src/Domain/Messaging/Message/SubscriberConfirmationMessage.php index 58623020..37311009 100644 --- a/src/Domain/Messaging/Message/SubscriberConfirmationMessage.php +++ b/src/Domain/Messaging/Message/SubscriberConfirmationMessage.php @@ -12,15 +12,18 @@ class SubscriberConfirmationMessage private string $email; private string $uniqueId; private bool $htmlEmail; + private ?string $locale; public function __construct( string $email, string $uniqueId, - bool $htmlEmail = false + bool $htmlEmail = false, + ?string $locale = null ) { $this->email = $email; $this->uniqueId = $uniqueId; $this->htmlEmail = $htmlEmail; + $this->locale = $locale; } public function getEmail(): string @@ -37,4 +40,12 @@ public function hasHtmlEmail(): bool { return $this->htmlEmail; } + + /** + * Explicit email locale; when null the handler resolves it from the subscriber's subscribe page. + */ + public function getLocale(): ?string + { + return $this->locale; + } } diff --git a/src/Domain/Messaging/MessageHandler/PasswordResetMessageHandler.php b/src/Domain/Messaging/MessageHandler/PasswordResetMessageHandler.php index 927e4f98..ebac4548 100644 --- a/src/Domain/Messaging/MessageHandler/PasswordResetMessageHandler.php +++ b/src/Domain/Messaging/MessageHandler/PasswordResetMessageHandler.php @@ -22,16 +22,15 @@ public function __construct( } /** - * Process a subscriber confirmation message by sending the confirmation email + * Process a password reset message by sending the reset email */ public function __invoke(PasswordResetMessage $message): void { $confirmationLink = $this->generateLink($message->getToken()); - // todo: email locale. This runs in a queue worker, where the request locale is not available, so the - // default locale is always used. Resolve the recipient's language (phplist3 uses the subscriber/admin - // language) and pass it as the $locale argument of trans() for the subject and both bodies. - $subject = $this->translator->trans('Password Reset Request'); + $locale = $message->getLocale(); + + $subject = $this->translator->trans('Password Reset Request', [], null, $locale); $textContent = $this->translator->trans( "Hello,\n\n" . @@ -40,7 +39,9 @@ public function __invoke(PasswordResetMessage $message): void "%token%\n\n" . "If you did not request this password reset, please ignore this email.\n\n" . 'Thank you.', - ['%token%' => $message->getToken()] + ['%token%' => $message->getToken()], + null, + $locale ); $htmlContent = $this->translator->trans( @@ -52,10 +53,11 @@ public function __invoke(PasswordResetMessage $message): void '

Thank you.

', [ '%confirmation_link%' => $confirmationLink, - ] + ], + null, + $locale ); - $email = (new Email()) ->to($message->getEmail()) ->subject($subject) diff --git a/src/Domain/Messaging/MessageHandler/SubscriberConfirmationMessageHandler.php b/src/Domain/Messaging/MessageHandler/SubscriberConfirmationMessageHandler.php index 5e609abc..f098c12a 100644 --- a/src/Domain/Messaging/MessageHandler/SubscriberConfirmationMessageHandler.php +++ b/src/Domain/Messaging/MessageHandler/SubscriberConfirmationMessageHandler.php @@ -6,6 +6,8 @@ use PhpList\Core\Domain\Messaging\Message\SubscriberConfirmationMessage; use PhpList\Core\Domain\Messaging\Service\EmailService; +use PhpList\Core\Domain\Subscription\Repository\SubscriberRepository; +use PhpList\Core\Domain\Subscription\Service\Resolver\SubscriberLocaleResolver; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\Messenger\Attribute\AsMessageHandler; use Symfony\Component\Mime\Email; @@ -20,6 +22,8 @@ class SubscriberConfirmationMessageHandler public function __construct( private readonly EmailService $emailService, private readonly TranslatorInterface $translator, + private readonly SubscriberRepository $subscriberRepository, + private readonly SubscriberLocaleResolver $localeResolver, #[Autowire('%app.confirmation_url%')]private readonly string $confirmationUrl ) { } @@ -31,10 +35,9 @@ public function __invoke(SubscriberConfirmationMessage $message): void { $confirmationLink = $this->generateConfirmationLink($message->getUniqueId()); - // todo: email locale. This runs in a queue worker, where the request locale is not available, so the - // default locale is always used. Resolve the subscriber's language (phplist3 uses the subscriber/list - // language) and pass it as the $locale argument of trans() for the subject and both bodies. - $subject = $this->translator->trans('Please confirm your subscription'); + $locale = $this->resolveLocale($message); + + $subject = $this->translator->trans('Please confirm your subscription', [], null, $locale); $textContent = $this->translator->trans( "Thank you for subscribing!\n\n" . @@ -43,7 +46,9 @@ public function __invoke(SubscriberConfirmationMessage $message): void 'If you did not request this subscription, please ignore this email.', [ '%confirmation_link%' => $confirmationLink - ] + ], + null, + $locale ); $htmlContent = ''; @@ -55,7 +60,9 @@ public function __invoke(SubscriberConfirmationMessage $message): void '

If you did not request this subscription, please ignore this email.

', [ '%confirmation_link%' => $confirmationLink, - ] + ], + null, + $locale ); } @@ -71,6 +78,22 @@ public function __invoke(SubscriberConfirmationMessage $message): void $this->emailService->sendEmail($email); } + /** + * phplist3 has no per-subscriber language: it uses the language of the subscribe page the subscriber used. + * A locale set explicitly on the message wins, otherwise it is resolved from that page (default locale as + * fallback), since the request locale is not available in a queue worker. + */ + private function resolveLocale(SubscriberConfirmationMessage $message): ?string + { + if ($message->getLocale() !== null) { + return $message->getLocale(); + } + + $subscriber = $this->subscriberRepository->findOneByUniqueId($message->getUniqueId()); + + return $subscriber === null ? null : $this->localeResolver->resolve($subscriber); + } + /** * Generate a confirmation link for the subscriber */ diff --git a/src/Domain/Subscription/Service/Resolver/SubscriberLocaleResolver.php b/src/Domain/Subscription/Service/Resolver/SubscriberLocaleResolver.php new file mode 100644 index 00000000..ddbcc759 --- /dev/null +++ b/src/Domain/Subscription/Service/Resolver/SubscriberLocaleResolver.php @@ -0,0 +1,96 @@ + locale. */ + private const LANGUAGE_FILE_LOCALES = [ + 'afrikaans' => 'af', + 'albanian' => 'sq', + 'arabic' => 'ar', + 'belgianflemish' => 'nl_BE', + 'bosnian' => 'bs', + 'bulgarian' => 'bg', + 'catalan' => 'ca', + 'croatian' => 'hr', + 'czech' => 'cs', + 'danish' => 'da', + 'dutch' => 'nl', + 'english' => 'en', + 'english-gaelic' => 'ga', + 'english-usa' => 'en_US', + 'usa' => 'en_US', + 'estonian' => 'et', + 'finnish' => 'fi', + 'french' => 'fr', + 'german' => 'de', + 'greek' => 'el', + 'hebrew' => 'he', + 'hungarian' => 'hu', + 'indonesian' => 'id', + 'italian' => 'it', + 'japanese' => 'ja', + 'latinamerican' => 'es_419', + 'norwegian' => 'nb', + 'persian' => 'fa', + 'polish' => 'pl', + 'portuguese' => 'pt_BR', + 'portuguese_pt' => 'pt_PT', + 'romanian' => 'ro', + 'russian' => 'ru', + 'serbian' => 'sr', + 'slovenian' => 'sl', + 'spanish' => 'es', + 'swedish' => 'sv', + 'swissgerman' => 'de_CH', + 'tchinese' => 'zh_TW', + 'turkish' => 'tr', + 'ukrainian' => 'uk', + 'vietnamese' => 'vi', + ]; + + public function __construct( + private readonly SubscriberPageDataRepository $pageDataRepository, + #[Autowire('%locale%')] private readonly string $defaultLocale, + ) { + } + + public function resolve(Subscriber $subscriber): string + { + $pageId = $subscriber->getSubscribePage(); + if ($pageId === null) { + return $this->defaultLocale; + } + + $data = $this->pageDataRepository->findOneBy(['id' => $pageId, 'name' => self::LANGUAGE_FILE_KEY]); + + return $this->localeFromLanguageFile($data?->getData()) ?? $this->defaultLocale; + } + + public function localeFromLanguageFile(?string $languageFile): ?string + { + if ($languageFile === null || trim($languageFile) === '') { + return null; + } + + $key = preg_replace('/\.inc$/i', '', strtolower(basename(trim($languageFile)))) ?? ''; + + return self::LANGUAGE_FILE_LOCALES[$key] ?? null; + } +} diff --git a/tests/Unit/Domain/Identity/Service/PasswordManagerTest.php b/tests/Unit/Domain/Identity/Service/PasswordManagerTest.php index d212ca1e..98d92d83 100644 --- a/tests/Unit/Domain/Identity/Service/PasswordManagerTest.php +++ b/tests/Unit/Domain/Identity/Service/PasswordManagerTest.php @@ -17,6 +17,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Messenger\Envelope; use Symfony\Component\Messenger\MessageBusInterface; +use Symfony\Component\Translation\Translator; use Symfony\Contracts\Translation\TranslatorInterface; class PasswordManagerTest extends TestCase @@ -99,6 +100,29 @@ public function testGeneratePasswordResetTokenCleansUpExistingRequests(): void $this->assertNotEmpty($token); } + public function testGeneratePasswordResetTokenCapturesRequestLocale(): void + { + $subject = new PasswordManager( + passwordRequestRepository: $this->passwordRequestRepository, + administratorRepository: $this->administratorRepository, + hashGenerator: $this->hashGenerator, + messageBus: $this->messageBus, + translator: new Translator('de') + ); + $this->administratorRepository->method('findOneBy')->willReturn($this->createMock(Administrator::class)); + $this->passwordRequestRepository->method('findByAdmin')->willReturn([]); + + $this->messageBus->expects($this->once()) + ->method('dispatch') + ->with($this->callback(function (PasswordResetMessage $message) { + $this->assertSame('de', $message->getLocale()); + return true; + })) + ->willReturn(new Envelope(new PasswordResetMessage('a@example.com', 'token'))); + + $subject->generatePasswordResetToken('a@example.com'); + } + public function testValidatePasswordResetTokenReturnsNullIfTokenNotFound(): void { $token = 'nonexistent-token'; diff --git a/tests/Unit/Domain/Messaging/Message/SubscriberConfirmationMessageTest.php b/tests/Unit/Domain/Messaging/Message/SubscriberConfirmationMessageTest.php index 1af63bef..ad65c797 100644 --- a/tests/Unit/Domain/Messaging/Message/SubscriberConfirmationMessageTest.php +++ b/tests/Unit/Domain/Messaging/Message/SubscriberConfirmationMessageTest.php @@ -31,4 +31,10 @@ public function testDefaultHtmlEmailIsFalse(): void $this->assertFalse($message->hasHtmlEmail()); } + + public function testLocaleDefaultsToNullAndCanBeSet(): void + { + $this->assertNull((new SubscriberConfirmationMessage('a@example.com', 'abc'))->getLocale()); + $this->assertSame('de', (new SubscriberConfirmationMessage('a@example.com', 'abc', false, 'de'))->getLocale()); + } } diff --git a/tests/Unit/Domain/Messaging/MessageHandler/PasswordResetMessageHandlerTest.php b/tests/Unit/Domain/Messaging/MessageHandler/PasswordResetMessageHandlerTest.php index 22f83bfc..5eff8534 100644 --- a/tests/Unit/Domain/Messaging/MessageHandler/PasswordResetMessageHandlerTest.php +++ b/tests/Unit/Domain/Messaging/MessageHandler/PasswordResetMessageHandlerTest.php @@ -10,6 +10,7 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\Mime\Email; +use Symfony\Component\Translation\Loader\XliffFileLoader; use Symfony\Component\Translation\Translator; class PasswordResetMessageHandlerTest extends TestCase @@ -63,6 +64,27 @@ public function testInvoke(): void $this->handler->__invoke($message); } + public function testInvokeUsesLocaleOfMessage(): void + { + $translator = new Translator('en'); + $translator->addLoader('xlf', new XliffFileLoader()); + $translator->addResource('xlf', __DIR__ . '/../../../../../resources/translations/messages.de.xlf', 'de'); + $handler = new PasswordResetMessageHandler($this->emailService, $translator, $this->passwordResetUrl); + + $this->emailService->expects($this->once()) + ->method('sendEmail') + ->with($this->callback(function (Email $email) { + $this->assertSame('Passwort zurücksetzen', $email->getSubject()); + $this->assertStringContainsString('Hallo,', $email->getTextBody()); + $this->assertStringContainsString('abc123', $email->getTextBody()); + $this->assertStringContainsString('Passwort zurücksetzen', $email->getHtmlBody()); + + return true; + })); + + $handler->__invoke(new PasswordResetMessage('user@example.com', 'abc123', 'de')); + } + /** * Helper method to extract email addresses from Address objects */ diff --git a/tests/Unit/Domain/Messaging/MessageHandler/SubscriberConfirmationMessageHandlerTest.php b/tests/Unit/Domain/Messaging/MessageHandler/SubscriberConfirmationMessageHandlerTest.php index 550a6160..5b58e73e 100644 --- a/tests/Unit/Domain/Messaging/MessageHandler/SubscriberConfirmationMessageHandlerTest.php +++ b/tests/Unit/Domain/Messaging/MessageHandler/SubscriberConfirmationMessageHandlerTest.php @@ -7,27 +7,98 @@ use PhpList\Core\Domain\Messaging\Message\SubscriberConfirmationMessage; use PhpList\Core\Domain\Messaging\MessageHandler\SubscriberConfirmationMessageHandler; use PhpList\Core\Domain\Messaging\Service\EmailService; +use PhpList\Core\Domain\Subscription\Model\Subscriber; +use PhpList\Core\Domain\Subscription\Repository\SubscriberRepository; +use PhpList\Core\Domain\Subscription\Service\Resolver\SubscriberLocaleResolver; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\Mime\Email; +use Symfony\Component\Translation\Loader\ArrayLoader; use Symfony\Component\Translation\Translator; class SubscriberConfirmationMessageHandlerTest extends TestCase { private SubscriberConfirmationMessageHandler $handler; private EmailService&MockObject $emailService; + private SubscriberRepository&MockObject $subscriberRepository; + private SubscriberLocaleResolver&MockObject $localeResolver; private string $confirmationUrl = 'https://example.com/confirm'; protected function setUp(): void { $this->emailService = $this->createMock(EmailService::class); - $this->handler = new SubscriberConfirmationMessageHandler( + $this->subscriberRepository = $this->createMock(SubscriberRepository::class); + $this->localeResolver = $this->createMock(SubscriberLocaleResolver::class); + $this->handler = $this->createHandler(new Translator('en')); + } + + private function createHandler(Translator $translator): SubscriberConfirmationMessageHandler + { + return new SubscriberConfirmationMessageHandler( emailService: $this->emailService, - translator: new Translator('en'), + translator: $translator, + subscriberRepository: $this->subscriberRepository, + localeResolver: $this->localeResolver, confirmationUrl: $this->confirmationUrl ); } + private function germanTranslator(): Translator + { + $translator = new Translator('en'); + $translator->addLoader('array', new ArrayLoader()); + $translator->addResource('array', ['Please confirm your subscription' => 'Bitte bestätigen'], 'de'); + + return $translator; + } + + public function testSubjectUsesLocaleResolvedFromSubscriber(): void + { + $subscriber = $this->createMock(Subscriber::class); + $this->subscriberRepository->method('findOneByUniqueId')->with('abc123')->willReturn($subscriber); + $this->localeResolver->method('resolve')->with($subscriber)->willReturn('de'); + $handler = $this->createHandler($this->germanTranslator()); + + $this->emailService->expects($this->once()) + ->method('sendEmail') + ->with($this->callback(function (Email $email) { + $this->assertSame('Bitte bestätigen', $email->getSubject()); + return true; + })); + + $handler->__invoke(new SubscriberConfirmationMessage('a@example.com', 'abc123')); + } + + public function testExplicitMessageLocaleWinsOverResolver(): void + { + $this->subscriberRepository->expects($this->never())->method('findOneByUniqueId'); + $handler = $this->createHandler($this->germanTranslator()); + + $this->emailService->expects($this->once()) + ->method('sendEmail') + ->with($this->callback(function (Email $email) { + $this->assertSame('Bitte bestätigen', $email->getSubject()); + return true; + })); + + $handler->__invoke(new SubscriberConfirmationMessage('a@example.com', 'abc123', false, 'de')); + } + + public function testUnknownSubscriberUsesDefaultLocale(): void + { + $this->subscriberRepository->method('findOneByUniqueId')->willReturn(null); + $this->localeResolver->expects($this->never())->method('resolve'); + + $this->emailService->expects($this->once()) + ->method('sendEmail') + ->with($this->callback(function (Email $email) { + $this->assertSame('Please confirm your subscription', $email->getSubject()); + return true; + })); + + $this->handler->__invoke(new SubscriberConfirmationMessage('a@example.com', 'abc123')); + } + public function testInvokeWithTextEmail(): void { $subscriberEmail = 'subscriber@example.com'; diff --git a/tests/Unit/Domain/Subscription/Service/Resolver/SubscriberLocaleResolverTest.php b/tests/Unit/Domain/Subscription/Service/Resolver/SubscriberLocaleResolverTest.php new file mode 100644 index 00000000..c4171dbd --- /dev/null +++ b/tests/Unit/Domain/Subscription/Service/Resolver/SubscriberLocaleResolverTest.php @@ -0,0 +1,88 @@ +repository = $this->createMock(SubscriberPageDataRepository::class); + $this->resolver = new SubscriberLocaleResolver($this->repository, 'en'); + } + + private function subscriberWithPage(?int $pageId): Subscriber + { + $subscriber = new Subscriber('a@example.com'); + $subscriber->setSubscribePage($pageId); + + return $subscriber; + } + + public function testMapsLanguageFileOfSubscribePage(): void + { + $data = (new SubscribePageData())->setId(5)->setName('language_file')->setData('german.inc'); + $this->repository->expects($this->once()) + ->method('findOneBy') + ->with(['id' => 5, 'name' => 'language_file']) + ->willReturn($data); + + $this->assertSame('de', $this->resolver->resolve($this->subscriberWithPage(5))); + } + + public function testDefaultsWhenSubscriberHasNoPage(): void + { + $this->repository->expects($this->never())->method('findOneBy'); + + $this->assertSame('en', $this->resolver->resolve($this->subscriberWithPage(null))); + } + + public function testDefaultsWhenPageHasNoLanguageFile(): void + { + $this->repository->method('findOneBy')->willReturn(null); + + $this->assertSame('en', $this->resolver->resolve($this->subscriberWithPage(5))); + } + + public function testDefaultsWhenLanguageFileIsEmptyOrUnknown(): void + { + $empty = (new SubscribePageData())->setData(''); + $unknown = (new SubscribePageData())->setData('klingon.inc'); + $this->repository->method('findOneBy')->willReturnOnConsecutiveCalls($empty, $unknown); + + $this->assertSame('en', $this->resolver->resolve($this->subscriberWithPage(5))); + } + + /** + * @dataProvider languageFileProvider + */ + public function testLocaleFromLanguageFile(?string $file, ?string $expected): void + { + $this->assertSame($expected, $this->resolver->localeFromLanguageFile($file)); + } + + public static function languageFileProvider(): array + { + return [ + 'with extension' => ['french.inc', 'fr'], + 'uppercase' => ['French.INC', 'fr'], + 'without extension' => ['spanish', 'es'], + 'hyphenated' => ['english-usa.inc', 'en_US'], + 'path is stripped' => ['../texts/dutch.inc', 'nl'], + 'unknown' => ['nope.inc', null], + 'empty' => [' ', null], + 'null' => [null, null], + ]; + } +} From f6a7ffe6d7a3e529e4dd58cb8d48a8350dd18abb Mon Sep 17 00:00:00 2001 From: Tatevik Date: Sat, 28 Nov 2026 17:06:06 +0400 Subject: [PATCH 10/14] test: add tests for route handling in ModuleFinder --- tests/Unit/Composer/ModuleFinderTest.php | 38 ++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/tests/Unit/Composer/ModuleFinderTest.php b/tests/Unit/Composer/ModuleFinderTest.php index d740d8f9..52e40661 100644 --- a/tests/Unit/Composer/ModuleFinderTest.php +++ b/tests/Unit/Composer/ModuleFinderTest.php @@ -165,4 +165,42 @@ public function testCreateBundleConfigurationYamlReturnsYamlForBundles(array $mo self::assertSame(self::YAML_COMMENT . "\n" . Yaml::dump($bundles), $result); } + + public function testFindRoutesKeepsRoutesWithTheSameNameFromDifferentModules(): void + { + $route = ['resource' => '@SomeBundle/Controller/', 'prefix' => '/']; + $this->packageRepository + ->method('findAll') + ->willReturn([ + $this->buildMockPackage( + ['phplist/core' => ['routes' => ['homepage' => $route]]], + 'phplist/web-frontend' + ), + $this->buildMockPackage(['phplist/core' => ['routes' => ['homepage' => $route]]], 'other/module'), + ]); + + $result = $this->subject->findRoutes(); + + self::assertSame(['phplist/web-frontend.homepage', 'other/module.homepage'], array_keys($result)); + } + + public function testFindRoutesReturnsRoutesInPackageOrderSoThatEarlierPackagesWin(): void + { + $this->packageRepository + ->method('findAll') + ->willReturn([ + $this->buildMockPackage( + ['phplist/core' => ['routes' => ['b' => ['prefix' => '/']]]], + 'first/package' + ), + $this->buildMockPackage( + ['phplist/core' => ['routes' => ['a' => ['prefix' => '/']]]], + 'second/package' + ), + ]); + + $result = $this->subject->findRoutes(); + + self::assertSame(['first/package.b', 'second/package.a'], array_keys($result)); + } } From ef335a0a3992861238436637220aea3084be3299 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Sat, 28 Nov 2026 17:16:22 +0400 Subject: [PATCH 11/14] feat: add Symfony requirements checker to CI and composer dependencies --- .github/workflows/ci.yml | 2 ++ composer.json | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e7be80bc..ba63de2a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -66,6 +66,8 @@ jobs: restore-keys: ${{ runner.os }}-composer- - name: Install Composer dependencies run: composer install --no-progress --prefer-dist --optimize-autoloader + - name: Check Symfony requirements + run: vendor/bin/requirements-checker - name: Validating composer.json run: composer validate --no-check-all --no-check-lock --strict; - name: Linting all php files diff --git a/composer.json b/composer.json index bd74450a..b76315fb 100644 --- a/composer.json +++ b/composer.json @@ -91,7 +91,8 @@ "symfony/dotenv": "^7.4", "symfony/doctrine-messenger": "^7.4", "elasticsearch/elasticsearch": "^8.9", - "symfony/scheduler": "^7.4" + "symfony/scheduler": "^7.4", + "symfony/requirements-checker": "^2.0" }, "require-dev": { "phpunit/phpunit": "^9.5", From e6c9c033cae1a18f5683fa5d0dafae189c570023 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Sat, 28 Nov 2026 17:21:58 +0400 Subject: [PATCH 12/14] feat: add CI workflow for database migrations validation --- .github/workflows/migrations.yml | 70 ++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 .github/workflows/migrations.yml diff --git a/.github/workflows/migrations.yml b/.github/workflows/migrations.yml new file mode 100644 index 00000000..f36b1a8e --- /dev/null +++ b/.github/workflows/migrations.yml @@ -0,0 +1,70 @@ +name: Database migrations +# Checks that the migrations in src/Migrations build, on an empty database, a schema that matches the Doctrine +# mapping. Separate from ci.yml because ci.yml loads resources/Database/Schema.sql (the legacy schema) and only +# validates the mapping with --skip-sync; this job tests the migrations themselves. +on: [push, pull_request] +jobs: + migrations: + name: Migrations build a schema matching the Doctrine mapping + runs-on: ubuntu-22.04 + env: + DB_DATABASE: phplist_migrations + DB_USERNAME: root + DB_PASSWORD: phplist + services: + mysql: + image: mysql:8.0 + env: + MYSQL_ROOT_PASSWORD: ${{ env.DB_PASSWORD }} + # created empty by the service; only this job uses it + MYSQL_DATABASE: ${{ env.DB_DATABASE }} + ports: + - 3306/tcp + options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3 + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.2' + extensions: mbstring, dom, fileinfo, mysql + coverage: none + - name: Get composer cache directory + id: composer-cache + run: echo "dir=$(composer config cache-files-dir)" >> "$GITHUB_OUTPUT" + - name: Cache composer dependencies + uses: actions/cache@v4 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} + restore-keys: ${{ runner.os }}-composer- + - name: Install Composer dependencies + run: composer install --prefer-dist --no-progress + - name: Point the application at the migrations database + run: | + { + echo "PHPLIST_DATABASE_NAME=${{ env.DB_DATABASE }}" + echo "PHPLIST_DATABASE_USER=${{ env.DB_USERNAME }}" + echo "PHPLIST_DATABASE_PASSWORD=${{ env.DB_PASSWORD }}" + echo "PHPLIST_DATABASE_HOST=127.0.0.1" + echo "PHPLIST_DATABASE_PORT=${{ job.services.mysql.ports['3306'] }}" + } >> "$GITHUB_ENV" + - name: Run the migrations + run: php bin/console doctrine:migrations:migrate --no-interaction + - name: Check the init migration created every table of its dump + run: | + tables=$(mysql --host 127.0.0.1 --port "$PHPLIST_DATABASE_PORT" -u"$PHPLIST_DATABASE_USER" -p"$PHPLIST_DATABASE_PASSWORD" -N \ + -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '$PHPLIST_DATABASE_NAME' AND table_name LIKE 'phplist\_%'") + expected=$(grep -c '^CREATE TABLE' src/Migrations/initial_schema.sql) + echo "phpList tables created by the migrations: $tables (the init dump alone creates $expected)" + if [ "$tables" -lt "$expected" ]; then + echo "::error::The migrations created only $tables of the $expected tables in the init dump." + exit 1 + fi + - name: Create the Messenger transport tables + # messenger_messages is created by Messenger's auto_setup on first use, not by a migration, but it is + # part of the schema that doctrine:schema:validate expects. + run: php bin/console messenger:setup-transports + - name: Validate the schema against the Doctrine mapping + run: php bin/console doctrine:schema:validate From 1dd1373d9d2accfcaa87b2514979735264a903b2 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Sat, 28 Nov 2026 18:46:37 +0400 Subject: [PATCH 13/14] docs: update PHP version requirement to 8.2 and add development documentation --- README.md | 167 +++----------------------------------- docs/AsyncEmailSending.md | 10 +-- docs/ClassStructure.md | 23 ++---- docs/Development.md | 67 +++++++++++++++ docs/Graylog.md | 10 +-- docs/MailerTransports.md | 8 +- docs/ModuleDevelopment.md | 92 +++++++++++++++++++++ docs/Scheduling.md | 3 +- 8 files changed, 194 insertions(+), 186 deletions(-) create mode 100644 docs/Development.md create mode 100644 docs/ModuleDevelopment.md diff --git a/README.md b/README.md index 7c2ed6f7..7cd146c1 100755 --- a/README.md +++ b/README.md @@ -32,8 +32,8 @@ This module should not be modified locally. It should be updated via Composer. ## Requirements -* PHP 8.1 or higher -* Symfony 6.4 components +* PHP 8.2 or higher +* Symfony 7.4 components * Doctrine ORM 3.3 ## Installation @@ -52,167 +52,22 @@ this code. ## Documentation +Architecture and domain: * [Class structure overview](docs/ClassStructure.md) * [Domain model diagram](docs/DomainModel/DomainModel.svg) and [description of the domain entities](docs/DomainModel/Entities.md) + +Features and configuration: * [Mailer transports](docs/MailerTransports.md) - configuring Gmail, Amazon SES, Mailchimp, and SendGrid * [Asynchronous email sending](docs/AsyncEmailSending.md) - queuing email delivery with Symfony Messenger +* [Scheduling](docs/Scheduling.md) - running recurring tasks with the Symfony Scheduler or crontab * [Graylog integration](docs/Graylog.md) - centralized log management * [Elasticsearch-backed search for big tables](docs/ElasticsearchSearch.md) - dual-write to the database and Elasticsearch, reading from Elasticsearch only -* [Generating class API docs](PHPDOC.md) - regenerating the phpDocumentor output - -## Running the web server -The phpList application is configured so that the built-in PHP web server can -run in development and testing mode, while Apache can run in production mode. - -Please first set the database credentials in `.env` (created from `.env.dist` on `composer install`/`composer update`). - -### Development - -To run the application in development mode using PHP's built-in server, -use this command: - -```bash -bin/console server:run -d public/ -``` - -The server will then listen on `http://127.0.0.1:8000` (or, if port 8000 is -already in use, on the next free port after 8000). - -You can stop the server with CTRL + C. - -### Testing - -Create test db with name phplist in your mysql DB or uncomment sqlite part in config_test.yml file to use in memory DB for functional tests. -To run the server in testing mode (which normally will only be needed for the -automated tests, provide the `--env` option: - -```bash -bin/console server:run -d public/ --env=test -``` - -### Production - -For documentation on running the application in production mode using Apache, -please see the -[phpList base distribution README](https://github.com/phpList/base-distribution). - -## Changing the database schema - -Any changes to the database schema must always be done both in phpList 3 and -later versions so that both versions always have the same schema. - -For changing the database schema, please edit `resources/Database/Schema.sql` -and adapt the corresponding domain model classes and repository classes -accordingly. - -## Developing phpList modules (plugins) - -In phpList, plugins are called **modules**. They are Composer packages which -have the type `phplist-module`. - -### Bundle and route configuration - -If your module provides any Symfony bundles, the bundle class names need to be -listed in the `extra` section of the module's `composer.json` like this: - -```json -{ - "extra": { - "phplist/core": { - "bundles": [ - "Symfony\\Bundle\\FrameworkBundle\\FrameworkBundle", - "PhpList\\Core\\EmptyStartPageBundle\\PhpListEmptyStartPageBundle" - ] - } - } -} -``` - -Please note that the key of the section with `extra` needs to always be -`phplist/core`, not the name of your module package. Please have a -look at the -[`composer.json` in the `rest-api` module](https://github.com/phpList/rest-api/blob/master/composer.json) -for an example. - -Similarly, if your module provides any routes, those also need to be listed in -the `extra` section of the module's `composer.json` like this: - -```json -{ - "extra": { - "phplist/core": { - "routes": { - "homepage": { - "resource": "@PhpListEmptyStartPageBundle/Controller/", - "type": "annotation" - } - } - } - } -} -``` - -You can also provide system configuration for your module: - -```json -{ - "extra": { - "phplist/core": { - "configuration": { - "framework": { - "templating": { - "engines": [ - "twig" - ] - } - } - } - } - } -} -``` - -It is recommended to define the routes using -[annotations](https://symfony.com/doc/current/routing.html#routing-examples) -in the controller classes so that the route configuration in the composer.json -is minimal. - -### Accessing the database - -For accessing the phpList database tables from a module, please use the -[Doctrine](http://www.doctrine-project.org/) model and repository classes -stored in `src/Domain/` in the `phplist/core` package (this -package). - -For accessing a repository, please have it injected via -[dependency injection](https://symfony.com/doc/current/components/dependency_injection.html). -Please do not get the repository directly from the entity manager as this would -skip dependency injection for that repository, causing those methods to break -that rely on other services having been injected. - -Currently, only a few database tables are mapped as models/repositories. If you -need a mode or a repository method that still is missing, please -[submit a pull request](https://github.com/phpList/core/pulls) or -[file an issue](https://github.com/phpList/core/issues). - -## Accessing the phpList data from third-party applications - -To access the phpList data from a third-party application (i.e., not from a -phpList module), please use the -[REST API](https://github.com/phpList/rest-api). - -## Translations - -To extract translation strings from the source into an XLIFF catalog: - -```bash -php bin/console translation:extract --force en --format=xlf -php bin/console messenger:setup-transports -php bin/console messenger:consume async_email --limit=1 -php bin/console phplist:search:init-indices -``` +Development: +* [Development guide](docs/Development.md) - running the web server, changing the database schema, translations +* [Developing phpList modules (plugins)](docs/ModuleDevelopment.md) - bundles, routes, database access, third-party access +* [Generating class API docs](PHPDOC.md) - regenerating the phpDocumentor output ## Copyright -phpList is copyright (C) 2000-2025 [phpList Ltd](https://www.phplist.com/). +phpList is copyright (C) 2000-2026 [phpList Ltd](https://www.phplist.com/). diff --git a/docs/AsyncEmailSending.md b/docs/AsyncEmailSending.md index 386eae49..4ab22c53 100644 --- a/docs/AsyncEmailSending.md +++ b/docs/AsyncEmailSending.md @@ -4,7 +4,7 @@ This document explains how to use the asynchronous email sending functionality i ## Overview -phpList now supports sending emails asynchronously using Symfony Messenger. This means that when you send an email, it is queued for delivery rather than being sent immediately. This has several benefits: +phpList supports sending emails asynchronously using Symfony Messenger. This means that when you send an email, it is queued for delivery rather than being sent immediately. This has several benefits: 1. **Improved Performance**: Your application doesn't have to wait for the email to be sent before continuing execution 2. **Better Reliability**: If the email server is temporarily unavailable, the message remains in the queue and will be retried automatically @@ -12,12 +12,12 @@ phpList now supports sending emails asynchronously using Symfony Messenger. This ## Configuration -The asynchronous email functionality is configured in `config/packages/messenger.yaml` and uses the `MESSENGER_TRANSPORT_DSN` environment variable defined in `config/parameters.yml`. +The asynchronous email functionality is configured in `config/packages/messenger.yaml` and uses the `MESSENGER_TRANSPORT_DSN` environment variable (set in `.env`, see `.env.dist`). By default, the system uses Doctrine (database) as the transport for queued messages: -```yaml -env(MESSENGER_TRANSPORT_DSN): 'doctrine://default?auto_setup=true' +```dotenv +MESSENGER_TRANSPORT_DSN=doctrine://default?auto_setup=true ``` You can change this to use other transports supported by Symfony Messenger, such as: @@ -104,5 +104,5 @@ If emails are not being sent: 1. Make sure the messenger worker is running 2. Check for failed messages using `bin/console messenger:failed:show` -3. Verify your mailer configuration in `config/parameters.yml` +3. Verify your mailer configuration (`MAILER_DSN` in `.env`) 4. Try sending an email synchronously to test the mailer configuration diff --git a/docs/ClassStructure.md b/docs/ClassStructure.md index 1f586515..ceba1c26 100644 --- a/docs/ClassStructure.md +++ b/docs/ClassStructure.md @@ -1,46 +1,41 @@ # Class structure -All production classes live under `src/`, and all unit/integration tests live under `tests/`. +All production classes live under `src/`, and all tests (`Unit`, `Integration`, `System`) live under `tests/`. ## Core/ Core runtime and DI wiring. - Bootstrap: entry point that bootstraps the phpList core system and configures the application. - ApplicationKernel, ApplicationStructure: Symfony kernel and structure configuration. -- Compiler passes (e.g., BounceProcessorPass, DoctrineMappingPass), environment helpers, parameter providers. - -## Bounce/ -Bounce processing feature. (This module continuously updates the database throughout the bounce-processing workflow; therefore, it is separated into its own feature block.) -- Command/: Console commands related to processing bounces. -- Service/: Services that parse, classify and handle bounces. -- Exception/: Bounce‑related exceptions. +- Compiler passes (BounceProcessorPass, DoctrineMappingPass), environment helpers, parameter providers, and Doctrine listeners (`Core/Doctrine`). ## Composer/ Integration with Composer. - ScriptHandler, ModuleFinder, PackageRepository: helpers invoked by Composer scripts and for module discovery. ## Domain/ -Domain logic organized by sub‑domains (e.g., Analytics, Common, Configuration, Identity, Messaging, Subscription). +Domain logic organized by sub‑domains (Analytics, Common, Configuration, Identity, Messaging, Search, Subscription). Each sub‑domain follows similar conventions: - Model/: Domain entities/value objects. Contains business logic; no direct DB access. - Repository/: Reading/writing models and other DB queries. - Service/: Domain services and orchestration. +- Command/, Message/, MessageHandler/, Validator/: console commands, Messenger messages and handlers, validators (where the area needs them). - Exception/: Domain‑specific exceptions. +Bounce processing lives in `Domain/Messaging` (commands and services such as `BounceActionResolver` and `ConsecutiveBounceHandler`). Authentication and password hashing (`Authentication`, `HashGenerator`) live in `Domain/Identity/Service`. + ## EmptyStartPageBundle/ A minimal Symfony bundle providing an empty start page. - Controller/: Controllers for the bundle. ## Migrations/ -Holds database migration files (Doctrine Migrations). May be empty until migrations are generated. +Doctrine Migrations, with separate MySQL and PostgreSQL versions extending `AbstractPrefixedMigration`. ## Routing/ Routing extensions and loaders. - ExtraLoader: additional/dynamic route loading. -## Security/ -Security‑related concerns. -- Authentication: authentication helpers/integration. -- HashGenerator: password hashing utilities. +## DependencyInjection/ +The `PhpListCoreExtension` that loads the bundle's service configuration (the bundle class is `PhpListCoreBundle`). ## TestingSupport/ Utilities to support tests. diff --git a/docs/Development.md b/docs/Development.md new file mode 100644 index 00000000..288331b8 --- /dev/null +++ b/docs/Development.md @@ -0,0 +1,67 @@ +# Development + +For code style, tests and the pull request workflow, see the +[contribution guide](../.github/CONTRIBUTING.md). + +## Running the web server + +The phpList application is configured so that the built-in PHP web server can +run in development and testing mode, while Apache can run in production mode. + +Please first set the database credentials in `.env` (created from `.env.dist` +on `composer install`/`composer update`). + +### Development + +```bash +APP_ENV=dev php -S 127.0.0.1:8000 -t public/ +``` + +The server will then listen on `http://127.0.0.1:8000`. You can stop it with +CTRL + C. Without `APP_ENV`, `public/index.php` runs in production mode. + +### Testing + +By default the tests use a MySQL database named `phplist`. To use an in-memory +SQLite database instead (no MySQL server needed), set this in `.env.test.local`: + +``` +PHPLIST_DATABASE_DRIVER=pdo_sqlite +PHPLIST_DATABASE_PATH=:memory: +``` + +To run the web server in the test environment, use `APP_ENV=test`. For console +commands, use `--env=test`. + +### Production + +For documentation on running the application in production mode using Apache, +please see the +[phpList base distribution README](https://github.com/phpList/base-distribution). + +## Changing the database schema + +Schema changes are made in the Doctrine models and shipped as migrations: + +1. Change the entity mapping under `src/Domain/`. +2. Add a migration in `src/Migrations/`, for both MySQL and PostgreSQL. Do not + edit existing migrations. +3. Keep the schema compatible with phpList 3, so that existing installations can + still be migrated. + +CI runs the migrations on an empty database and validates the result against +the Doctrine mapping (see `.github/workflows/migrations.yml`). + +## Translations + +To extract translation strings from the source into an XLIFF catalog: + +```bash +php bin/console translation:extract --force en --format=xlf +``` + +The catalogs live in `resources/translations/`. + +## Generating class documentation + +See [PHPDOC.md](../PHPDOC.md). diff --git a/docs/Graylog.md b/docs/Graylog.md index b5db0671..dd3f468e 100644 --- a/docs/Graylog.md +++ b/docs/Graylog.md @@ -7,18 +7,18 @@ in both environments. ## Enabling it 1. In `config/config_prod.yml`, uncomment the `graylog` handler under `monolog.handlers`. - It sends `error`-level and above logs, using the `graylog_host` and `graylog_port` + It sends `error`-level and above logs, using the `graylog.host` and `graylog.port` parameters from `config/parameters.yml` (defaults: `graylog.phplist.local:12201`). 2. In `config/config_dev.yml`, uncomment the `graylog` handler to also log in development. It sends every level except the `event` channel. -3. Update `graylog_host` and `graylog_port` in `config/parameters.yml` to point at +3. Update `graylog.host` and `graylog.port` in `config/parameters.yml` to point at your Graylog server. ```yaml # config/parameters.yml parameters: - graylog_host: 'graylog.example.com' - graylog_port: 12201 + graylog.host: 'graylog.example.com' + graylog.port: 12201 ``` ## Graylog server setup @@ -30,7 +30,7 @@ Your Graylog server needs a GELF UDP input to receive these logs: 3. Configure it with: - Title: phpList Core - Bind address: `0.0.0.0` (listen on all interfaces) - - Port: `12201` (or whatever you set as `graylog_port`) + - Port: `12201` (or whatever you set as `graylog.port`) 4. Click "Save". ## Testing the integration diff --git a/docs/MailerTransports.md b/docs/MailerTransports.md index 9488923a..6c55d41d 100644 --- a/docs/MailerTransports.md +++ b/docs/MailerTransports.md @@ -9,7 +9,7 @@ This document explains how to use the various mailer transports that are include ## Configuration -The phpList core uses Symfony Mailer for sending emails. The mailer transport is configured using the `MAILER_DSN` environment variable, which is defined in `config/parameters.yml`. +The phpList core uses Symfony Mailer for sending emails. The mailer transport is configured using the `MAILER_DSN` environment variable, which is set in `.env` (see `.env.dist`) and read by `config/parameters.yml`. ## Available Transports @@ -18,7 +18,7 @@ The phpList core uses Symfony Mailer for sending emails. The mailer transport is To use Gmail as your email transport: ``` -# Using Gmail with OAuth (recommended) +# Using Gmail with an app password MAILER_DSN=gmail://USERNAME:APP_PASSWORD@default # Using Gmail with SMTP @@ -28,7 +28,7 @@ MAILER_DSN=smtp://USERNAME:PASSWORD@smtp.gmail.com:587 Notes: - Replace `USERNAME` with your Gmail address - For OAuth setup, follow [Symfony Gmail documentation](https://symfony.com/doc/current/mailer.html#using-gmail-to-send-emails) -- For the SMTP method, you may need to enable "Less secure app access" or use an App Password +- For the SMTP method, use an App Password (Google no longer allows "Less secure app access") ### 2. Amazon SES @@ -87,7 +87,7 @@ bin/console phplist:test-email recipient@example.com You can easily switch between different mailer transports by changing the `MAILER_DSN` environment variable. This can be done in several ways: -1. Edit the `config/parameters.yml` file directly +1. Edit the `.env` file 2. Set the environment variable in your server configuration 3. Set the environment variable before running a command: ```bash diff --git a/docs/ModuleDevelopment.md b/docs/ModuleDevelopment.md new file mode 100644 index 00000000..a4aacf43 --- /dev/null +++ b/docs/ModuleDevelopment.md @@ -0,0 +1,92 @@ +# Developing phpList modules (plugins) + +In phpList, plugins are called **modules**. They are Composer packages which +have the type `phplist-module`. + +## Bundle and route configuration + +If your module provides any Symfony bundles, the bundle class names need to be +listed in the `extra` section of the module's `composer.json` like this: + +```json +{ + "extra": { + "phplist/core": { + "bundles": [ + "Symfony\\Bundle\\FrameworkBundle\\FrameworkBundle", + "PhpList\\Core\\EmptyStartPageBundle\\EmptyStartPageBundle" + ] + } + } +} +``` + +Please note that the key of the section with `extra` needs to always be +`phplist/core`, not the name of your module package. Please have a +look at the +[`composer.json` in the `rest-api` module](https://github.com/phpList/rest-api/blob/master/composer.json) +for an example. + +Similarly, if your module provides any routes, those also need to be listed in +the `extra` section of the module's `composer.json` like this: + +```json +{ + "extra": { + "phplist/core": { + "routes": { + "homepage": { + "resource": "@EmptyStartPageBundle/Controller/", + "type": "attribute" + } + } + } + } +} +``` + +You can also provide system configuration for your module: + +```json +{ + "extra": { + "phplist/core": { + "configuration": { + "framework": { + "default_locale": "en" + } + } + } + } +} +``` + +It is recommended to define the routes using +[attributes](https://symfony.com/doc/current/routing.html#creating-routes-as-attributes) +in the controller classes so that the route configuration in the composer.json +is minimal. + +## Accessing the database + +For accessing the phpList database tables from a module, please use the +[Doctrine](http://www.doctrine-project.org/) model and repository classes +stored in `src/Domain/` in the `phplist/core` package (this +package). See the [class structure](ClassStructure.md) and the +[domain entities](DomainModel/Entities.md) for an overview. + +For accessing a repository, please have it injected via +[dependency injection](https://symfony.com/doc/current/components/dependency_injection.html). +Please do not get the repository directly from the entity manager as this would +skip dependency injection for that repository, causing those methods to break +that rely on other services having been injected. + +Currently, only a few database tables are mapped as models/repositories. If you +need a model or a repository method that still is missing, please +[submit a pull request](https://github.com/phpList/core/pulls) or +[file an issue](https://github.com/phpList/core/issues). + +## Accessing the phpList data from third-party applications + +To access the phpList data from a third-party application (i.e., not from a +phpList module), please use the +[REST API](https://github.com/phpList/rest-api). diff --git a/docs/Scheduling.md b/docs/Scheduling.md index f27f09a3..1718d240 100644 --- a/docs/Scheduling.md +++ b/docs/Scheduling.md @@ -18,8 +18,7 @@ bin/console messenger:consume scheduler_default | `phplist:update-tlds` | 1 month | `PHPLIST_SCHEDULE_TLDS` | | `phplist:clean-up-old-session-tokens` | 1 day | `PHPLIST_SCHEDULE_CLEANUP` | -Values are relative interval strings (`"5 minutes"`, `"1 day"`); an empty value disables that entry. The -defaults are (queue every minute, bounces daily). +Values are relative interval strings (`"5 minutes"`, `"1 day"`); an empty value disables that entry. Overlapping runs are prevented: the schedule is locked, and `phplist:process-queue` / `phplist:bounces:process` keep their own locks, so a slow run makes the next one exit instead of piling up. From 68332e5bb4e4ed3fbe47d85d16a8466502ec97de Mon Sep 17 00:00:00 2001 From: Tatevik Date: Mon, 30 Nov 2026 10:09:33 +0400 Subject: [PATCH 14/14] feat: exclude hidden files and directories from directory listing --- .../Common/Service/DirectoryListingService.php | 3 ++- .../Service/DirectoryListingServiceTest.php | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/Domain/Common/Service/DirectoryListingService.php b/src/Domain/Common/Service/DirectoryListingService.php index d7eca1d1..06c463f4 100644 --- a/src/Domain/Common/Service/DirectoryListingService.php +++ b/src/Domain/Common/Service/DirectoryListingService.php @@ -60,7 +60,8 @@ static function (DirectoryEntryDto $file1, DirectoryEntryDto $file2): int { private function createEntry(string $directory, string $realPath, string $item): ?DirectoryEntryDto { - if ($item === '.' || $item === '..') { + // Skips ".", ".." and hidden entries such as .gitkeep. + if (str_starts_with($item, '.')) { return null; } diff --git a/tests/Unit/Domain/Common/Service/DirectoryListingServiceTest.php b/tests/Unit/Domain/Common/Service/DirectoryListingServiceTest.php index 7e4b804a..12385b83 100644 --- a/tests/Unit/Domain/Common/Service/DirectoryListingServiceTest.php +++ b/tests/Unit/Domain/Common/Service/DirectoryListingServiceTest.php @@ -22,7 +22,7 @@ protected function setUp(): void protected function tearDown(): void { - foreach (glob($this->realPath . '/*') ?: [] as $entry) { + foreach (glob($this->realPath . '/{,.}[!.]*', GLOB_BRACE) ?: [] as $entry) { is_dir($entry) ? rmdir($entry) : unlink($entry); } rmdir($this->realPath); @@ -99,6 +99,19 @@ public function testListExcludesDotAndDotDotEntries(): void self::assertSame([], $entries); } + public function testListExcludesHiddenFilesAndDirectories(): void + { + file_put_contents($this->realPath . '/.gitkeep', ''); + mkdir($this->realPath . '/.hidden-folder'); + file_put_contents($this->realPath . '/visible.txt', 'x'); + + $service = new DirectoryListingService(); + $entries = $service->list('uploads', $this->realPath); + + self::assertCount(1, $entries); + self::assertSame('visible.txt', $entries[0]->name); + } + public function testListThrowsRuntimeExceptionWhenDirectoryCannotBeRead(): void { $missingPath = $this->realPath . '/does-not-exist';