AutomatedEmails.php
2 months ago
NewsletterLinkRepository.php
2 months ago
Scheduler.php
2 months ago
StatsNotificationsRepository.php
2 years ago
Worker.php
3 months ago
index.php
3 years ago
AutomatedEmails.php
250 lines
| 1 | <?php // phpcs:ignore SlevomatCodingStandard.TypeHints.DeclareStrictTypes.DeclareStrictTypesMissing |
| 2 | |
| 3 | namespace MailPoet\Cron\Workers\StatsNotifications; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use MailPoet\Automation\Engine\Data\Automation; |
| 9 | use MailPoet\Automation\Engine\Storage\AutomationStorage; |
| 10 | use MailPoet\Automation\Integrations\MailPoet\Actions\SendEmailAction; |
| 11 | use MailPoet\Config\Renderer; |
| 12 | use MailPoet\Cron\Workers\SimpleWorker; |
| 13 | use MailPoet\Entities\NewsletterEntity; |
| 14 | use MailPoet\Entities\ScheduledTaskEntity; |
| 15 | use MailPoet\Mailer\MailerFactory; |
| 16 | use MailPoet\Mailer\MetaInfo; |
| 17 | use MailPoet\Newsletter\NewslettersRepository; |
| 18 | use MailPoet\Newsletter\Statistics\NewsletterStatistics; |
| 19 | use MailPoet\Newsletter\Statistics\NewsletterStatisticsRepository; |
| 20 | use MailPoet\Settings\SettingsController; |
| 21 | use MailPoet\Settings\TrackingConfig; |
| 22 | use MailPoet\WP\DateTime as WpDateTime; |
| 23 | use MailPoet\WP\Functions as WPFunctions; |
| 24 | use MailPoet\WPCOM\DotcomHelperFunctions; |
| 25 | use MailPoetVendor\Carbon\Carbon; |
| 26 | |
| 27 | class AutomatedEmails extends SimpleWorker { |
| 28 | const TASK_TYPE = 'stats_notification_automated_emails'; |
| 29 | |
| 30 | /** @var MailerFactory */ |
| 31 | private $mailerFactory; |
| 32 | |
| 33 | /** @var SettingsController */ |
| 34 | private $settings; |
| 35 | |
| 36 | /** @var Renderer */ |
| 37 | private $renderer; |
| 38 | |
| 39 | /** @var MetaInfo */ |
| 40 | private $mailerMetaInfo; |
| 41 | |
| 42 | /** @var NewslettersRepository */ |
| 43 | private $repository; |
| 44 | |
| 45 | /** @var NewsletterStatisticsRepository */ |
| 46 | private $newsletterStatisticsRepository; |
| 47 | |
| 48 | /** @var TrackingConfig */ |
| 49 | private $trackingConfig; |
| 50 | |
| 51 | /** @var WpDateTime */ |
| 52 | private $wpDateTime; |
| 53 | |
| 54 | /** @var DotcomHelperFunctions */ |
| 55 | private $dotcomHelperFunctions; |
| 56 | |
| 57 | /** @var AutomationStorage */ |
| 58 | private $automationStorage; |
| 59 | |
| 60 | public function __construct( |
| 61 | MailerFactory $mailerFactory, |
| 62 | Renderer $renderer, |
| 63 | SettingsController $settings, |
| 64 | NewslettersRepository $repository, |
| 65 | NewsletterStatisticsRepository $newsletterStatisticsRepository, |
| 66 | MetaInfo $mailerMetaInfo, |
| 67 | TrackingConfig $trackingConfig, |
| 68 | DotcomHelperFunctions $dotcomHelperFunctions, |
| 69 | AutomationStorage $automationStorage |
| 70 | ) { |
| 71 | parent::__construct(); |
| 72 | $this->mailerFactory = $mailerFactory; |
| 73 | $this->settings = $settings; |
| 74 | $this->renderer = $renderer; |
| 75 | $this->mailerMetaInfo = $mailerMetaInfo; |
| 76 | $this->repository = $repository; |
| 77 | $this->newsletterStatisticsRepository = $newsletterStatisticsRepository; |
| 78 | $this->trackingConfig = $trackingConfig; |
| 79 | $this->dotcomHelperFunctions = $dotcomHelperFunctions; |
| 80 | $this->automationStorage = $automationStorage; |
| 81 | $this->wpDateTime = new WpDateTime(); |
| 82 | } |
| 83 | |
| 84 | public function checkProcessingRequirements() { |
| 85 | $settings = $this->settings->get(Worker::SETTINGS_KEY); |
| 86 | if (!is_array($settings)) { |
| 87 | return false; |
| 88 | } |
| 89 | if (!isset($settings['automated'])) { |
| 90 | return false; |
| 91 | } |
| 92 | if (!is_string($settings['address'] ?? null) || trim($settings['address']) === '') { |
| 93 | return false; |
| 94 | } |
| 95 | if (!$this->trackingConfig->isEmailTrackingEnabled()) { |
| 96 | return false; |
| 97 | } |
| 98 | return (bool)$settings['automated']; |
| 99 | } |
| 100 | |
| 101 | public function processTaskStrategy(ScheduledTaskEntity $task, $timer) { |
| 102 | try { |
| 103 | $settings = $this->settings->get(Worker::SETTINGS_KEY); |
| 104 | $newsletters = $this->getNewsletters(); |
| 105 | if ($newsletters) { |
| 106 | $extraParams = [ |
| 107 | 'meta' => $this->mailerMetaInfo->getStatsNotificationMetaInfo(), |
| 108 | ]; |
| 109 | $this->mailerFactory->getDefaultMailer()->send($this->constructNewsletter($newsletters, $settings), $settings['address'], $extraParams); |
| 110 | } |
| 111 | } catch (\Exception $e) { |
| 112 | if (WP_DEBUG) { |
| 113 | throw $e; |
| 114 | } |
| 115 | } |
| 116 | return true; |
| 117 | } |
| 118 | |
| 119 | /** |
| 120 | * @param array<int, array{newsletter: NewsletterEntity, statistics: NewsletterStatistics}> $newsletters |
| 121 | */ |
| 122 | private function constructNewsletter(array $newsletters, array $settings): array { |
| 123 | $context = $this->prepareContext($newsletters, $settings); |
| 124 | if ($this->dotcomHelperFunctions->isGarden()) { |
| 125 | $subject = __('Your monthly automation stats are in!', 'mailpoet'); |
| 126 | } else { |
| 127 | $subject = __('Your monthly stats are in!', 'mailpoet'); |
| 128 | } |
| 129 | return [ |
| 130 | 'subject' => $subject, |
| 131 | 'body' => [ |
| 132 | 'html' => $this->renderer->render('emails/statsNotificationAutomatedEmails.html', $context), |
| 133 | 'text' => $this->renderer->render('emails/statsNotificationAutomatedEmails.txt', $context), |
| 134 | ], |
| 135 | ]; |
| 136 | } |
| 137 | |
| 138 | /** |
| 139 | * @return array<int, array{newsletter: NewsletterEntity, statistics: NewsletterStatistics}> |
| 140 | */ |
| 141 | protected function getNewsletters(): array { |
| 142 | $result = []; |
| 143 | $newsletters = $this->repository->findActiveByTypes( |
| 144 | [NewsletterEntity::TYPE_AUTOMATIC, NewsletterEntity::TYPE_WELCOME, NewsletterEntity::TYPE_AUTOMATION] |
| 145 | ); |
| 146 | $activeAutomationNewsletterIds = $this->getActiveAutomationNewsletterIds(); |
| 147 | foreach ($newsletters as $newsletter) { |
| 148 | if ( |
| 149 | $newsletter->getType() === NewsletterEntity::TYPE_AUTOMATION |
| 150 | && !in_array($newsletter->getId(), $activeAutomationNewsletterIds, true) |
| 151 | ) { |
| 152 | continue; |
| 153 | } |
| 154 | $statistics = $this->newsletterStatisticsRepository->getStatistics($newsletter); |
| 155 | if ($statistics->getTotalSentCount()) { |
| 156 | $result[] = [ |
| 157 | 'statistics' => $statistics, |
| 158 | 'newsletter' => $newsletter, |
| 159 | ]; |
| 160 | } |
| 161 | } |
| 162 | return $result; |
| 163 | } |
| 164 | |
| 165 | /** @return int[] */ |
| 166 | private function getActiveAutomationNewsletterIds(): array { |
| 167 | $ids = []; |
| 168 | $automations = $this->automationStorage->getAutomations([Automation::STATUS_ACTIVE]); |
| 169 | foreach ($automations as $automation) { |
| 170 | foreach ($automation->getSteps() as $step) { |
| 171 | if ($step->getKey() === SendEmailAction::KEY) { |
| 172 | $args = $step->getArgs(); |
| 173 | if (isset($args['email_id'])) { |
| 174 | $ids[] = (int)$args['email_id']; |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | } |
| 179 | return $ids; |
| 180 | } |
| 181 | |
| 182 | /** |
| 183 | * @param array<int, array{newsletter: NewsletterEntity, statistics: NewsletterStatistics}> $newsletters |
| 184 | * @return array |
| 185 | */ |
| 186 | private function prepareContext(array $newsletters, array $settings = []): array { |
| 187 | $context = [ |
| 188 | 'linkSettings' => WPFunctions::get()->applyFilters( |
| 189 | 'mailpoet_stats_notification_link_settings', |
| 190 | WPFunctions::get()->getSiteUrl(null, '/wp-admin/admin.php?page=mailpoet-settings#basics') |
| 191 | ), |
| 192 | 'blogName' => WPFunctions::get()->getBloginfo('name'), |
| 193 | 'recipientFirstName' => $this->getRecipientFirstName($settings['address'] ?? ''), |
| 194 | 'newsletters' => [], |
| 195 | ]; |
| 196 | foreach ($newsletters as $row) { |
| 197 | $statistics = $row['statistics']; |
| 198 | $newsletter = $row['newsletter']; |
| 199 | $totalSentCount = $statistics->getTotalSentCount() ?: 1; |
| 200 | $clicked = ($statistics->getClickCount() * 100) / $totalSentCount; |
| 201 | $opened = ($statistics->getOpenCount() * 100) / $totalSentCount; |
| 202 | $machineOpened = ($statistics->getMachineOpenCount() * 100) / $totalSentCount; |
| 203 | $unsubscribed = ($statistics->getUnsubscribeCount() * 100) / $totalSentCount; |
| 204 | $bounced = ($statistics->getBounceCount() * 100) / $totalSentCount; |
| 205 | $context['newsletters'][] = [ |
| 206 | 'linkStats' => WPFunctions::get()->applyFilters( |
| 207 | 'mailpoet_stats_notification_link_stats', |
| 208 | WPFunctions::get()->getSiteUrl(null, '/wp-admin/admin.php?page=mailpoet-newsletters#/stats/' . $newsletter->getId()), |
| 209 | $newsletter->getId() |
| 210 | ), |
| 211 | 'clicked' => $clicked, |
| 212 | 'opened' => $opened, |
| 213 | 'machineOpened' => $machineOpened, |
| 214 | 'unsubscribed' => $unsubscribed, |
| 215 | 'bounced' => $bounced, |
| 216 | 'subject' => $newsletter->getSubject(), |
| 217 | ]; |
| 218 | } |
| 219 | return $context; |
| 220 | } |
| 221 | |
| 222 | private function getRecipientFirstName(string $email): string { |
| 223 | if (empty($email)) { |
| 224 | return ''; |
| 225 | } |
| 226 | $user = WPFunctions::get()->getUserBy('email', $email); |
| 227 | if (!$user) { |
| 228 | return ''; |
| 229 | } |
| 230 | $firstName = $user->first_name; // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps |
| 231 | if (!empty($firstName)) { |
| 232 | return $firstName; |
| 233 | } |
| 234 | $displayName = $user->display_name; // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps |
| 235 | return !empty($displayName) ? $displayName : ''; |
| 236 | } |
| 237 | |
| 238 | public function getNextRunDate() { |
| 239 | $currentDateTime = $this->wpDateTime->getCurrentDateTime(); |
| 240 | $date = Carbon::instance($currentDateTime)->millisecond(0); |
| 241 | // Get first Monday of next month at midnight |
| 242 | $nextMonday = $date->endOfMonth()->next(Carbon::MONDAY)->startOfDay(); |
| 243 | // Add random time across the entire day (0-23 hours, 0-59 minutes, 0-59 seconds) |
| 244 | return $nextMonday |
| 245 | ->addHours(rand(0, 23)) |
| 246 | ->addMinutes(rand(0, 59)) |
| 247 | ->addSeconds(rand(0, 59)); |
| 248 | } |
| 249 | } |
| 250 |