From 43d3f7b738bbe5674474167070684bda45b18069 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Mon, 23 Nov 2026 15:22:53 +0400 Subject: [PATCH 1/8] 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 2/8] 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 3/8] 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 4/8] 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 5/8] 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 6/8] 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 7/8] 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 accdf49a4c09c15543070ff698407c5725129309 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Thu, 26 Nov 2026 14:14:58 +0400 Subject: [PATCH 8/8] ref: update cache key format to use dot notation for consistency --- .../Service/Provider/ConfigProvider.php | 13 +++++++++++-- .../Service/Provider/ConfigProviderTest.php | 12 ++++++------ 2 files changed, 17 insertions(+), 8 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/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