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
Worker.php
244 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\Config\Renderer; |
| 9 | use MailPoet\Config\ServicesChecker; |
| 10 | use MailPoet\Cron\CronHelper; |
| 11 | use MailPoet\Entities\NewsletterEntity; |
| 12 | use MailPoet\Entities\NewsletterLinkEntity; |
| 13 | use MailPoet\Entities\ScheduledTaskEntity; |
| 14 | use MailPoet\Entities\SendingQueueEntity; |
| 15 | use MailPoet\Entities\StatsNotificationEntity; |
| 16 | use MailPoet\Mailer\MailerFactory; |
| 17 | use MailPoet\Mailer\MetaInfo; |
| 18 | use MailPoet\Newsletter\Statistics\NewsletterStatisticsRepository; |
| 19 | use MailPoet\Settings\SettingsController; |
| 20 | use MailPoet\Subscribers\SubscribersRepository; |
| 21 | use MailPoet\Util\License\Features\Subscribers as SubscribersFeature; |
| 22 | use MailPoet\WP\Functions as WPFunctions; |
| 23 | use MailPoet\WPCOM\DotcomHelperFunctions; |
| 24 | use MailPoetVendor\Carbon\Carbon; |
| 25 | use MailPoetVendor\Doctrine\ORM\EntityManager; |
| 26 | |
| 27 | class Worker { |
| 28 | |
| 29 | const TASK_TYPE = 'stats_notification'; |
| 30 | const SETTINGS_KEY = 'stats_notifications'; |
| 31 | const BATCH_SIZE = 5; |
| 32 | |
| 33 | /** @var Renderer */ |
| 34 | private $renderer; |
| 35 | |
| 36 | /** @var MailerFactory */ |
| 37 | private $mailerFactory; |
| 38 | |
| 39 | /** @var SettingsController */ |
| 40 | private $settings; |
| 41 | |
| 42 | /** @var CronHelper */ |
| 43 | private $cronHelper; |
| 44 | |
| 45 | /** @var MetaInfo */ |
| 46 | private $mailerMetaInfo; |
| 47 | |
| 48 | /** @var StatsNotificationsRepository */ |
| 49 | private $repository; |
| 50 | |
| 51 | /** @var EntityManager */ |
| 52 | private $entityManager; |
| 53 | |
| 54 | /** @var NewsletterLinkRepository */ |
| 55 | private $newsletterLinkRepository; |
| 56 | |
| 57 | /** @var NewsletterStatisticsRepository */ |
| 58 | private $newsletterStatisticsRepository; |
| 59 | |
| 60 | /** @var SubscribersFeature */ |
| 61 | private $subscribersFeature; |
| 62 | |
| 63 | /** @var SubscribersRepository */ |
| 64 | private $subscribersRepository; |
| 65 | |
| 66 | /** @var ServicesChecker */ |
| 67 | private $servicesChecker; |
| 68 | |
| 69 | /** @var DotcomHelperFunctions */ |
| 70 | private $dotcomHelperFunctions; |
| 71 | |
| 72 | public function __construct( |
| 73 | MailerFactory $mailerFactory, |
| 74 | Renderer $renderer, |
| 75 | SettingsController $settings, |
| 76 | CronHelper $cronHelper, |
| 77 | MetaInfo $mailerMetaInfo, |
| 78 | StatsNotificationsRepository $repository, |
| 79 | NewsletterLinkRepository $newsletterLinkRepository, |
| 80 | NewsletterStatisticsRepository $newsletterStatisticsRepository, |
| 81 | EntityManager $entityManager, |
| 82 | SubscribersFeature $subscribersFeature, |
| 83 | SubscribersRepository $subscribersRepository, |
| 84 | ServicesChecker $servicesChecker, |
| 85 | DotcomHelperFunctions $dotcomHelperFunctions |
| 86 | ) { |
| 87 | $this->renderer = $renderer; |
| 88 | $this->mailerFactory = $mailerFactory; |
| 89 | $this->settings = $settings; |
| 90 | $this->cronHelper = $cronHelper; |
| 91 | $this->mailerMetaInfo = $mailerMetaInfo; |
| 92 | $this->repository = $repository; |
| 93 | $this->entityManager = $entityManager; |
| 94 | $this->newsletterLinkRepository = $newsletterLinkRepository; |
| 95 | $this->newsletterStatisticsRepository = $newsletterStatisticsRepository; |
| 96 | $this->subscribersFeature = $subscribersFeature; |
| 97 | $this->subscribersRepository = $subscribersRepository; |
| 98 | $this->servicesChecker = $servicesChecker; |
| 99 | $this->dotcomHelperFunctions = $dotcomHelperFunctions; |
| 100 | } |
| 101 | |
| 102 | /** @throws \Exception */ |
| 103 | public function process($timer = false) { |
| 104 | $timer = $timer ?: microtime(true); |
| 105 | $settings = $this->settings->get(self::SETTINGS_KEY); |
| 106 | // Cleanup potential orphaned task created due bug MAILPOET-3015 |
| 107 | $this->repository->deleteOrphanedScheduledTasks(); |
| 108 | foreach ($this->repository->findScheduled(self::BATCH_SIZE) as $statsNotificationEntity) { |
| 109 | try { |
| 110 | $extraParams = [ |
| 111 | 'meta' => $this->mailerMetaInfo->getStatsNotificationMetaInfo(), |
| 112 | ]; |
| 113 | $this->mailerFactory->getDefaultMailer()->send($this->constructNewsletter($statsNotificationEntity, $settings), $settings['address'], $extraParams); |
| 114 | } catch (\Exception $e) { |
| 115 | if (WP_DEBUG) { |
| 116 | throw $e; |
| 117 | } |
| 118 | } finally { |
| 119 | $task = $statsNotificationEntity->getTask(); |
| 120 | if ($task instanceof ScheduledTaskEntity) { |
| 121 | $this->markTaskAsFinished($task); |
| 122 | } |
| 123 | } |
| 124 | $this->cronHelper->enforceExecutionLimit($timer); |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | private function constructNewsletter(StatsNotificationEntity $statsNotificationEntity, array $settings) { |
| 129 | $newsletter = $statsNotificationEntity->getNewsletter(); |
| 130 | if (!$newsletter instanceof NewsletterEntity) { |
| 131 | throw new \RuntimeException('Missing newsletter entity for statistic notification.'); |
| 132 | } |
| 133 | $link = $this->newsletterLinkRepository->findTopLinkForNewsletter((int)$newsletter->getId()); |
| 134 | $sendingQueue = $newsletter->getLatestQueue(); |
| 135 | if (!$sendingQueue instanceof SendingQueueEntity) { |
| 136 | throw new \RuntimeException('Missing sending queue entity for statistic notification.'); |
| 137 | } |
| 138 | $context = $this->prepareContext($newsletter, $sendingQueue, $link, $settings); |
| 139 | $subject = $sendingQueue->getNewsletterRenderedSubject(); |
| 140 | if ($this->dotcomHelperFunctions->isGarden()) { |
| 141 | // translators: %s is the name of the email campaign. |
| 142 | $emailSubject = sprintf(__('Campaign performance summary: %s', 'mailpoet'), $subject); |
| 143 | } else { |
| 144 | // translators: %s is the subject of the email. |
| 145 | $emailSubject = sprintf(_x('Stats for email %s', 'title of an automatic email containing statistics (newsletter open rate, click rate, etc)', 'mailpoet'), $subject); |
| 146 | } |
| 147 | return [ |
| 148 | 'subject' => $emailSubject, |
| 149 | 'body' => [ |
| 150 | 'html' => $this->renderer->render('emails/statsNotification.html', $context), |
| 151 | 'text' => $this->renderer->render('emails/statsNotification.txt', $context), |
| 152 | ], |
| 153 | ]; |
| 154 | } |
| 155 | |
| 156 | private function prepareContext(NewsletterEntity $newsletter, SendingQueueEntity $sendingQueue, ?NewsletterLinkEntity $link = null, array $settings = []) { |
| 157 | $statistics = $this->newsletterStatisticsRepository->getStatistics($newsletter); |
| 158 | $totalSentCount = $statistics->getTotalSentCount() ?: 1; |
| 159 | $clicked = ($statistics->getClickCount() * 100) / $totalSentCount; |
| 160 | $opened = ($statistics->getOpenCount() * 100) / $totalSentCount; |
| 161 | $machineOpened = ($statistics->getMachineOpenCount() * 100) / $totalSentCount; |
| 162 | $unsubscribed = ($statistics->getUnsubscribeCount() * 100) / $totalSentCount; |
| 163 | $bounced = ($statistics->getBounceCount() * 100) / $totalSentCount; |
| 164 | $subject = $sendingQueue->getNewsletterRenderedSubject(); |
| 165 | $subscribersCount = $this->subscribersRepository->getTotalSubscribers(); |
| 166 | $hasValidApiKey = $this->subscribersFeature->hasValidApiKey(); |
| 167 | $context = [ |
| 168 | 'subject' => $subject, |
| 169 | 'preheader' => sprintf( |
| 170 | // translators: %1$s is the percentage of clicks, %2$s the percentage of opens and %3$s the number of unsubscribes. |
| 171 | _x( |
| 172 | '%1$s%% clicks, %2$s%% opens, %3$s%% unsubscribes in a nutshell.', |
| 173 | 'newsletter open rate, click rate and unsubscribe rate', |
| 174 | 'mailpoet' |
| 175 | ), |
| 176 | number_format($clicked, 2), |
| 177 | number_format($opened, 2), |
| 178 | number_format($unsubscribed, 2) |
| 179 | ), |
| 180 | 'topLinkClicks' => 0, |
| 181 | 'linkSettings' => WPFunctions::get()->applyFilters( |
| 182 | 'mailpoet_stats_notification_link_settings', |
| 183 | WPFunctions::get()->getSiteUrl(null, '/wp-admin/admin.php?page=mailpoet-settings#basics') |
| 184 | ), |
| 185 | 'linkStats' => WPFunctions::get()->applyFilters( |
| 186 | 'mailpoet_stats_notification_link_stats', |
| 187 | WPFunctions::get()->getSiteUrl(null, '/wp-admin/admin.php?page=mailpoet-newsletters&stats=' . $newsletter->getId()), |
| 188 | $newsletter->getId() |
| 189 | ), |
| 190 | 'clicked' => $clicked, |
| 191 | 'opened' => $opened, |
| 192 | 'machineOpened' => $machineOpened, |
| 193 | 'unsubscribed' => $unsubscribed, |
| 194 | 'bounced' => $bounced, |
| 195 | 'subscribersLimitReached' => $this->subscribersFeature->check(), |
| 196 | 'hasValidApiKey' => $hasValidApiKey, |
| 197 | 'subscribersLimit' => $this->subscribersFeature->getSubscribersLimit(), |
| 198 | 'upgradeNowLink' => $hasValidApiKey |
| 199 | ? 'https://account.mailpoet.com/orders/upgrade/' . $this->servicesChecker->generatePartialApiKey() |
| 200 | : 'https://account.mailpoet.com/?s=' . ($subscribersCount + 1), |
| 201 | ]; |
| 202 | if ($link) { |
| 203 | $context['topLinkClicks'] = $link->getTotalClicksCount(); |
| 204 | $mappings = self::getShortcodeLinksMapping(); |
| 205 | $context['topLink'] = isset($mappings[$link->getUrl()]) ? $mappings[$link->getUrl()] : $link->getUrl(); |
| 206 | } |
| 207 | $context['blogName'] = WPFunctions::get()->getBloginfo('name'); |
| 208 | $context['recipientFirstName'] = $this->getRecipientFirstName($settings['address'] ?? ''); |
| 209 | return $context; |
| 210 | } |
| 211 | |
| 212 | private function getRecipientFirstName(string $email): string { |
| 213 | if (empty($email)) { |
| 214 | return ''; |
| 215 | } |
| 216 | $user = WPFunctions::get()->getUserBy('email', $email); |
| 217 | if (!$user) { |
| 218 | return ''; |
| 219 | } |
| 220 | $firstName = $user->first_name; // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps |
| 221 | if (!empty($firstName)) { |
| 222 | return $firstName; |
| 223 | } |
| 224 | $displayName = $user->display_name; // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps |
| 225 | return !empty($displayName) ? $displayName : ''; |
| 226 | } |
| 227 | |
| 228 | private function markTaskAsFinished(ScheduledTaskEntity $task) { |
| 229 | $task->setStatus(ScheduledTaskEntity::STATUS_COMPLETED); |
| 230 | $task->setProcessedAt(Carbon::now()->millisecond(0)); |
| 231 | $task->setScheduledAt(null); |
| 232 | $this->entityManager->flush(); |
| 233 | } |
| 234 | |
| 235 | public static function getShortcodeLinksMapping() { |
| 236 | return [ |
| 237 | NewsletterLinkEntity::UNSUBSCRIBE_LINK_SHORT_CODE => __('Unsubscribe link', 'mailpoet'), |
| 238 | NewsletterLinkEntity::INSTANT_UNSUBSCRIBE_LINK_SHORT_CODE => __('Unsubscribe link (without confirmation)', 'mailpoet'), |
| 239 | '[link:subscription_manage_url]' => __('Manage subscription link', 'mailpoet'), |
| 240 | '[link:newsletter_view_in_browser_url]' => __('View in browser link', 'mailpoet'), |
| 241 | ]; |
| 242 | } |
| 243 | } |
| 244 |