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/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..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 @@ -60,6 +68,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/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/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/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/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/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/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/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 18ee26a1..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']++; @@ -266,7 +267,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/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/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') 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()); + } +} 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); + } +}