StatisticsExporter.php
285 lines
| 1 | <?php declare(strict_types = 1); |
| 2 | |
| 3 | namespace MailPoet\Newsletter\Statistics\Export; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use MailPoet\Entities\NewsletterEntity; |
| 9 | use MailPoet\Newsletter\Sending\TimeZoneCampaignScheduler; |
| 10 | use MailPoet\Newsletter\Statistics\NewsletterStatistics; |
| 11 | use MailPoet\Newsletter\Statistics\NewsletterStatisticsRepository; |
| 12 | use MailPoet\Newsletter\Statistics\WooCommerceRevenue; |
| 13 | use MailPoet\Router\Endpoints\ExportDownload; |
| 14 | use MailPoet\WP\Functions as WPFunctions; |
| 15 | use MailPoetVendor\XLSXWriter; |
| 16 | |
| 17 | class StatisticsExporter { |
| 18 | public const FORMAT_CSV = 'csv'; |
| 19 | public const FORMAT_XLSX = 'xlsx'; |
| 20 | |
| 21 | public const FILE_PREFIX = 'MailPoet_stats_export_'; |
| 22 | /** |
| 23 | * Filter applied to populate per-recipient rows when exporting recipients. |
| 24 | * The free plugin ships an empty implementation; the premium plugin |
| 25 | * registers a callback that returns the per-recipient data. |
| 26 | * |
| 27 | * Filter signature: (array $rows, NewsletterEntity $newsletter): array |
| 28 | */ |
| 29 | public const FILTER_RECIPIENT_ROWS = 'mailpoet_statistics_export_recipient_rows'; |
| 30 | |
| 31 | /** @var NewsletterStatisticsRepository */ |
| 32 | private $statisticsRepository; |
| 33 | |
| 34 | /** @var TimeZoneCampaignScheduler */ |
| 35 | private $timeZoneCampaignScheduler; |
| 36 | |
| 37 | /** @var WPFunctions */ |
| 38 | private $wp; |
| 39 | |
| 40 | public function __construct( |
| 41 | NewsletterStatisticsRepository $statisticsRepository, |
| 42 | TimeZoneCampaignScheduler $timeZoneCampaignScheduler, |
| 43 | WPFunctions $wp |
| 44 | ) { |
| 45 | $this->statisticsRepository = $statisticsRepository; |
| 46 | $this->timeZoneCampaignScheduler = $timeZoneCampaignScheduler; |
| 47 | $this->wp = $wp; |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * Export aggregate stats for a single newsletter to CSV or XLSX. |
| 52 | * |
| 53 | * @return array{exportFileURL: string, totalExported: int} |
| 54 | */ |
| 55 | public function exportSingleAggregate(NewsletterEntity $newsletter, string $format): array { |
| 56 | $format = $this->normalizeFormat($format); |
| 57 | $headers = $this->getAggregateHeaders(); |
| 58 | $stats = $this->statisticsRepository->getStatistics($newsletter); |
| 59 | $row = $this->buildAggregateRow($newsletter, $stats); |
| 60 | |
| 61 | $this->ensureExportDirectory(); |
| 62 | $file = ExportDownload::createExportFile(self::FILE_PREFIX, $format); |
| 63 | $this->writeFile($file['path'], $headers, [$row], $format); |
| 64 | |
| 65 | return [ |
| 66 | 'exportFileURL' => $this->getExportFileUrl($file['token'], $format), |
| 67 | 'totalExported' => 1, |
| 68 | ]; |
| 69 | } |
| 70 | |
| 71 | /** |
| 72 | * Export aggregate stats for multiple newsletters to CSV or XLSX (one |
| 73 | * row per newsletter). Used by the bulk export action on the listing. |
| 74 | * |
| 75 | * @param NewsletterEntity[] $newsletters |
| 76 | * @return array{exportFileURL: string, totalExported: int} |
| 77 | */ |
| 78 | public function exportBulkAggregate(array $newsletters, string $format): array { |
| 79 | $format = $this->normalizeFormat($format); |
| 80 | $headers = $this->getAggregateHeaders(); |
| 81 | |
| 82 | $rows = []; |
| 83 | foreach ($newsletters as $newsletter) { |
| 84 | if (!$newsletter instanceof NewsletterEntity) { |
| 85 | continue; |
| 86 | } |
| 87 | $stats = $this->statisticsRepository->getStatistics($newsletter); |
| 88 | $rows[] = $this->buildAggregateRow($newsletter, $stats); |
| 89 | } |
| 90 | |
| 91 | $this->ensureExportDirectory(); |
| 92 | $file = ExportDownload::createExportFile(self::FILE_PREFIX, $format); |
| 93 | $this->writeFile($file['path'], $headers, $rows, $format); |
| 94 | |
| 95 | return [ |
| 96 | 'exportFileURL' => $this->getExportFileUrl($file['token'], $format), |
| 97 | 'totalExported' => count($rows), |
| 98 | ]; |
| 99 | } |
| 100 | |
| 101 | /** |
| 102 | * Export per-recipient stats for a newsletter to CSV or XLSX. Rows are |
| 103 | * populated via the FILTER_RECIPIENT_ROWS filter — the free plugin returns |
| 104 | * no rows, premium populates them. |
| 105 | * |
| 106 | * @return array{exportFileURL: string, totalExported: int} |
| 107 | */ |
| 108 | public function exportRecipients(NewsletterEntity $newsletter, string $format): array { |
| 109 | $format = $this->normalizeFormat($format); |
| 110 | $headers = $this->getRecipientHeaders($newsletter); |
| 111 | |
| 112 | /** @var array<array<int|string|float|null>> $rows */ |
| 113 | $rows = (array)$this->wp->applyFilters(self::FILTER_RECIPIENT_ROWS, [], $newsletter); |
| 114 | if (count($headers) > count($this->getRecipientHeaders())) { |
| 115 | $headerCount = count($headers); |
| 116 | foreach ($rows as $index => $row) { |
| 117 | $rows[$index] = array_pad($row, $headerCount, ''); |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | $this->ensureExportDirectory(); |
| 122 | $file = ExportDownload::createExportFile(self::FILE_PREFIX, $format); |
| 123 | $this->writeFile($file['path'], $headers, $rows, $format); |
| 124 | |
| 125 | return [ |
| 126 | 'exportFileURL' => $this->getExportFileUrl($file['token'], $format), |
| 127 | 'totalExported' => count($rows), |
| 128 | ]; |
| 129 | } |
| 130 | |
| 131 | /** |
| 132 | * Recipient export headers. For subscriber-timezone campaigns three extra |
| 133 | * delivery columns are appended; the premium plugin appends the matching |
| 134 | * row cells in `RecipientsExporter::getRows()` using the same resolver, so |
| 135 | * the two MUST stay in sync. |
| 136 | * |
| 137 | * @return string[] |
| 138 | */ |
| 139 | public function getRecipientHeaders(?NewsletterEntity $newsletter = null): array { |
| 140 | $headers = [ |
| 141 | __('Subscriber ID', 'mailpoet'), |
| 142 | __('Email', 'mailpoet'), |
| 143 | __('First name', 'mailpoet'), |
| 144 | __('Last name', 'mailpoet'), |
| 145 | __('Status', 'mailpoet'), |
| 146 | __('Opened', 'mailpoet'), |
| 147 | __('First open at', 'mailpoet'), |
| 148 | __('Open count', 'mailpoet'), |
| 149 | __('Machine opened', 'mailpoet'), |
| 150 | __('Clicked', 'mailpoet'), |
| 151 | __('Click count', 'mailpoet'), |
| 152 | __('Bounced', 'mailpoet'), |
| 153 | __('Unsubscribed', 'mailpoet'), |
| 154 | ]; |
| 155 | if ($newsletter && $this->isTimeZoneCampaign($newsletter)) { |
| 156 | $headers[] = __('Delivery timezone', 'mailpoet'); |
| 157 | $headers[] = __('Timezone fallback used', 'mailpoet'); |
| 158 | $headers[] = __('Local send time', 'mailpoet'); |
| 159 | } |
| 160 | return $headers; |
| 161 | } |
| 162 | |
| 163 | private function isTimeZoneCampaign(NewsletterEntity $newsletter): bool { |
| 164 | return $this->timeZoneCampaignScheduler->resolveTimeZoneCampaignQueue($newsletter) !== null; |
| 165 | } |
| 166 | |
| 167 | /** |
| 168 | * @return string[] |
| 169 | */ |
| 170 | public function getAggregateHeaders(): array { |
| 171 | return [ |
| 172 | __('Newsletter ID', 'mailpoet'), |
| 173 | __('Subject', 'mailpoet'), |
| 174 | __('Campaign name', 'mailpoet'), |
| 175 | __('Sent at', 'mailpoet'), |
| 176 | __('Total sent', 'mailpoet'), |
| 177 | __('Unique opens', 'mailpoet'), |
| 178 | __('Machine opens', 'mailpoet'), |
| 179 | __('Unique clicks', 'mailpoet'), |
| 180 | __('Bounces', 'mailpoet'), |
| 181 | __('Unsubscribes', 'mailpoet'), |
| 182 | __('Revenue', 'mailpoet'), |
| 183 | __('Currency', 'mailpoet'), |
| 184 | __('Orders', 'mailpoet'), |
| 185 | ]; |
| 186 | } |
| 187 | |
| 188 | /** |
| 189 | * Build one aggregate row for a newsletter, in the same column order as |
| 190 | * `getAggregateHeaders()`. Public so it can be reused by bulk export in phase 3. |
| 191 | * |
| 192 | * @return array<int|string|float|null> |
| 193 | */ |
| 194 | public function buildAggregateRow(NewsletterEntity $newsletter, NewsletterStatistics $stats): array { |
| 195 | $sentAt = $newsletter->getSentAt(); |
| 196 | $revenue = $stats->getWooCommerceRevenue(); |
| 197 | |
| 198 | return [ |
| 199 | (int)$newsletter->getId(), |
| 200 | (string)$newsletter->getSubject(), |
| 201 | (string)($newsletter->getCampaignName() ?? ''), |
| 202 | $sentAt ? $sentAt->format('Y-m-d H:i:s') : '', |
| 203 | $stats->getTotalSentCount(), |
| 204 | $stats->getOpenCount(), |
| 205 | $stats->getMachineOpenCount(), |
| 206 | $stats->getClickCount(), |
| 207 | $stats->getBounceCount(), |
| 208 | $stats->getUnsubscribeCount(), |
| 209 | $revenue instanceof WooCommerceRevenue ? $revenue->getValue() : '', |
| 210 | $revenue instanceof WooCommerceRevenue ? $revenue->getCurrency() : '', |
| 211 | $revenue instanceof WooCommerceRevenue ? $revenue->getOrdersCount() : '', |
| 212 | ]; |
| 213 | } |
| 214 | |
| 215 | /** |
| 216 | * @param string[] $headers |
| 217 | * @param array<array<int|string|float|null>> $rows |
| 218 | */ |
| 219 | private function writeFile(string $filePath, array $headers, array $rows, string $format): void { |
| 220 | if ($format === self::FORMAT_XLSX) { |
| 221 | $this->writeXlsx($filePath, $headers, $rows); |
| 222 | return; |
| 223 | } |
| 224 | $this->writeCsv($filePath, $headers, $rows); |
| 225 | } |
| 226 | |
| 227 | /** |
| 228 | * @param string[] $headers |
| 229 | * @param array<array<int|string|float|null>> $rows |
| 230 | */ |
| 231 | private function writeCsv(string $filePath, array $headers, array $rows): void { |
| 232 | $handle = fopen($filePath, 'w'); |
| 233 | if ($handle === false) { |
| 234 | throw new \RuntimeException('Failed opening file for export.'); |
| 235 | } |
| 236 | |
| 237 | // UTF-8 BOM so Excel auto-detects encoding (matches Subscribers/ImportExport/Export/Export.php) |
| 238 | fwrite($handle, chr(0xEF) . chr(0xBB) . chr(0xBF)); |
| 239 | $this->writeCsvLine($handle, $headers); |
| 240 | foreach ($rows as $row) { |
| 241 | $this->writeCsvLine($handle, $row); |
| 242 | } |
| 243 | fclose($handle); |
| 244 | } |
| 245 | |
| 246 | /** |
| 247 | * @param resource $handle |
| 248 | * @param array<int|string|float|null> $row |
| 249 | */ |
| 250 | private function writeCsvLine($handle, array $row): void { |
| 251 | // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_fputcsv -- Export handles are created under Env::$tempPath, which is MailPoet's WordPress temp directory. |
| 252 | fputcsv($handle, array_map('strval', $row), ',', '"', ''); |
| 253 | } |
| 254 | |
| 255 | /** |
| 256 | * @param string[] $headers |
| 257 | * @param array<array<int|string|float|null>> $rows |
| 258 | */ |
| 259 | private function writeXlsx(string $filePath, array $headers, array $rows): void { |
| 260 | $writer = new XLSXWriter(); |
| 261 | $sheetName = __('Statistics', 'mailpoet'); |
| 262 | $writer->writeSheetHeader($sheetName, array_fill_keys($headers, 'string')); |
| 263 | foreach ($rows as $row) { |
| 264 | $writer->writeSheetRow($sheetName, $row); |
| 265 | } |
| 266 | $writer->writeToFile($filePath); |
| 267 | } |
| 268 | |
| 269 | private function ensureExportDirectory(): void { |
| 270 | ExportDownload::ensureExportDirectory($this->wp); |
| 271 | } |
| 272 | |
| 273 | private function getExportFileUrl(string $token, string $format): string { |
| 274 | return ExportDownload::buildStatisticsExportUrl($token, $format, $this->wp->homeUrl()); |
| 275 | } |
| 276 | |
| 277 | private function normalizeFormat(string $format): string { |
| 278 | $format = strtolower($format); |
| 279 | if ($format !== self::FORMAT_CSV && $format !== self::FORMAT_XLSX) { |
| 280 | throw new \InvalidArgumentException(sprintf('Unsupported export format "%s".', $format)); |
| 281 | } |
| 282 | return $format; |
| 283 | } |
| 284 | } |
| 285 |