Cli.php
2 weeks ago
Import.php
2 weeks ago
MailChimp.php
2 months ago
MailChimpDataMapper.php
2 months ago
index.php
3 years ago
MailChimp.php
209 lines
| 1 | <?php // phpcs:ignore SlevomatCodingStandard.TypeHints.DeclareStrictTypes.DeclareStrictTypesMissing |
| 2 | |
| 3 | namespace MailPoet\Subscribers\ImportExport\Import; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use MailPoet\Util\Helpers; |
| 9 | |
| 10 | class MailChimp { |
| 11 | private const API_BASE_URI = 'https://user:%s@%s.api.mailchimp.com/3.0/'; |
| 12 | private const API_KEY_REGEX = '/[a-zA-Z0-9]{32}-[a-zA-Z0-9]{2,4}$/'; |
| 13 | private const API_BATCH_SIZE = 100; |
| 14 | |
| 15 | /** @var false|string */ |
| 16 | public $apiKey; |
| 17 | /** @var int */ |
| 18 | public $maxPostSize; |
| 19 | /** @var false|string */ |
| 20 | public $dataCenter; |
| 21 | /** @var MailChimpDataMapper */ |
| 22 | private $mapper; |
| 23 | |
| 24 | public function __construct( |
| 25 | string $apiKey |
| 26 | ) { |
| 27 | $this->apiKey = $this->getAPIKey($apiKey); |
| 28 | $this->maxPostSize = (int)Helpers::getMaxPostSize('bytes'); |
| 29 | $this->dataCenter = $this->getDataCenter($this->apiKey); |
| 30 | $this->mapper = new MailChimpDataMapper(); |
| 31 | } |
| 32 | |
| 33 | public function getLists(): array { |
| 34 | if (!$this->apiKey || !$this->dataCenter) { |
| 35 | $this->throwException('API'); |
| 36 | } |
| 37 | |
| 38 | $lists = []; |
| 39 | $count = 0; |
| 40 | while (true) { |
| 41 | $data = $this->getApiData('lists', $count); |
| 42 | if ($data === null) { |
| 43 | $this->throwException('lists'); |
| 44 | break; |
| 45 | } |
| 46 | |
| 47 | $count += count($data['lists']); |
| 48 | foreach ($data['lists'] as $list) { |
| 49 | $lists[] = [ |
| 50 | 'id' => $list['id'], |
| 51 | 'name' => $list['name'], |
| 52 | ]; |
| 53 | } |
| 54 | |
| 55 | if ($data['total_items'] <= $count) { |
| 56 | break; |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | return $lists; |
| 61 | } |
| 62 | |
| 63 | public function getSubscribers(array $lists = []): array { |
| 64 | if (!$this->apiKey || !$this->dataCenter) { |
| 65 | $this->throwException('API'); |
| 66 | } |
| 67 | |
| 68 | if (!$lists) { |
| 69 | $this->throwException('lists'); |
| 70 | } |
| 71 | |
| 72 | $subscribers = []; |
| 73 | $duplicate = []; |
| 74 | $disallowed = []; |
| 75 | foreach ($lists as $list) { |
| 76 | $count = 0; |
| 77 | while (true) { |
| 78 | $data = $this->getApiData("lists/{$list}/members", $count); |
| 79 | if ($data === null) { |
| 80 | $this->throwException('lists'); |
| 81 | break; |
| 82 | } |
| 83 | $count += count($data['members']); |
| 84 | foreach ($data['members'] as $member) { |
| 85 | $emailAddress = $member['email_address']; |
| 86 | if (!$this->isSubscriberAllowed($member)) { |
| 87 | $disallowed[$emailAddress] = $this->mapper->mapMember($member); |
| 88 | } elseif (isset($subscribers[$emailAddress])) { |
| 89 | $duplicate[$emailAddress] = $this->mapper->mapMember($member); |
| 90 | } else { |
| 91 | $subscribers[$emailAddress] = $this->mapper->mapMember($member); |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | if ($data['total_items'] <= $count) { |
| 96 | break; |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | if (!count($subscribers)) { |
| 102 | $this->throwException('subscribers'); |
| 103 | } |
| 104 | |
| 105 | return [ |
| 106 | 'subscribers' => array_values($subscribers), |
| 107 | 'invalid' => [], |
| 108 | 'duplicate' => $duplicate, |
| 109 | 'disallowed' => $disallowed, |
| 110 | 'role' => [], |
| 111 | 'header' => $this->mapper->getMembersHeader(), |
| 112 | 'subscribersCount' => count($subscribers), |
| 113 | ]; |
| 114 | } |
| 115 | |
| 116 | /** |
| 117 | * @param string|false $apiKey |
| 118 | * @return false|string |
| 119 | */ |
| 120 | public function getDataCenter($apiKey) { |
| 121 | if (!$apiKey) return false; |
| 122 | $apiKeyParts = explode('-', $apiKey); |
| 123 | return end($apiKeyParts); |
| 124 | } |
| 125 | |
| 126 | /** |
| 127 | * @param string $apiKey |
| 128 | * @return false|string |
| 129 | */ |
| 130 | public function getAPIKey(string $apiKey) { |
| 131 | return (preg_match(self::API_KEY_REGEX, $apiKey)) ? $apiKey : false; |
| 132 | } |
| 133 | |
| 134 | /** |
| 135 | * @param string $error |
| 136 | * @throws \Exception |
| 137 | */ |
| 138 | public function throwException(string $error): void { |
| 139 | $errorMessage = __('Unknown MailChimp error.', 'mailpoet'); |
| 140 | switch ($error) { |
| 141 | case 'API': |
| 142 | $errorMessage = __('Invalid API Key.', 'mailpoet'); |
| 143 | break; |
| 144 | case 'size': |
| 145 | $errorMessage = __('The information received from MailChimp is too large for processing. Please limit the number of lists!', 'mailpoet'); |
| 146 | break; |
| 147 | case 'subscribers': |
| 148 | $errorMessage = __('Did not find any active subscribers.', 'mailpoet'); |
| 149 | break; |
| 150 | case 'lists': |
| 151 | $errorMessage = __('Did not find any valid lists.', 'mailpoet'); |
| 152 | break; |
| 153 | } |
| 154 | throw new \Exception($errorMessage); |
| 155 | } |
| 156 | |
| 157 | public function isSubscriberAllowed(array $subscriber): bool { |
| 158 | if (in_array($subscriber['status'], ['unsubscribed', 'cleaned', 'pending'], true)) { |
| 159 | return false; |
| 160 | } |
| 161 | if ($subscriber['member_rating'] < 2) { |
| 162 | return false; |
| 163 | } |
| 164 | // Rate 1 is on MailChimp API equal to 100% and we don't want to import avg_open_rate lower than 5% |
| 165 | if ($subscriber['stats']['avg_open_rate'] < 0.05) { |
| 166 | return false; |
| 167 | } |
| 168 | // We don't want to import avg_click_rate lower than 0.5% |
| 169 | if ($subscriber['stats']['avg_click_rate'] < 0.005) { |
| 170 | return false; |
| 171 | } |
| 172 | |
| 173 | return true; |
| 174 | } |
| 175 | |
| 176 | private function getApiData(string $endpoint, int $offset): ?array { |
| 177 | $url = sprintf(self::API_BASE_URI, $this->apiKey, $this->dataCenter); |
| 178 | $url .= $endpoint . '?' . http_build_query([ |
| 179 | 'count' => self::API_BATCH_SIZE, |
| 180 | 'offset' => $offset, |
| 181 | ]); |
| 182 | |
| 183 | $connection = @fopen($url, 'r'); |
| 184 | if (!$connection) { |
| 185 | return null; |
| 186 | } |
| 187 | |
| 188 | $bytesFetched = 0; |
| 189 | $response = ''; |
| 190 | while (!feof($connection)) { |
| 191 | $buffer = fgets($connection, 4096); |
| 192 | if (!is_string($buffer)) { |
| 193 | return null; |
| 194 | } |
| 195 | if (trim($buffer) !== '') { |
| 196 | $response .= $buffer; |
| 197 | } |
| 198 | $bytesFetched += strlen((string)$buffer); |
| 199 | if ($bytesFetched > $this->maxPostSize) { |
| 200 | $this->throwException('size'); |
| 201 | } |
| 202 | } |
| 203 | fclose($connection); |
| 204 | |
| 205 | $decoded = json_decode($response, true); |
| 206 | return is_array($decoded) ? $decoded : null; |
| 207 | } |
| 208 | } |
| 209 |