-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathMailchimpSubscribeService.php
884 lines (742 loc) · 30.5 KB
/
MailchimpSubscribeService.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
<?php
/**
* Mailchimp Subscribe plugin for Craft CMS 3.x
*
* @link https://www.vaersaagod.no
* @copyright Copyright (c) 2017 André Elvan
*/
namespace aelvan\mailchimpsubscribe\services;
use Craft;
use craft\base\Component;
use craft\errors\DeprecationException;
use aelvan\mailchimpsubscribe\MailchimpSubscribe as Plugin;
use aelvan\mailchimpsubscribe\models\SubscribeResponse;
use aelvan\mailchimpsubscribe\models\Settings;
use Illuminate\Support\Collection;
use Mailchimp\Mailchimp;
/**
* @author André Elvan
* @package MailchimpSubscribe
* @since 2.0.0
*/
class MailchimpSubscribeService extends Component
{
/**
* Subscribe a member to a Mailchimp lists
*
* @param string $email
* @param string $audienceId
* @param array|null $opts
*
* @return SubscribeResponse
* @throws DeprecationException
*/
public function subscribe($email, $audienceId, $opts = null): SubscribeResponse
{
// get settings
$settings = Plugin::$plugin->getSettings();
if ($email === '' || !$this->validateEmail($email)) { // error, invalid email
return new SubscribeResponse([
'success' => false,
'errorCode' => '1000',
'message' => Craft::t('mailchimp-subscribe', 'Invalid email'),
'values' => array_merge(['email' => $email], $opts ?? [])
]);
}
// get list id string
$audienceId = $this->prepAudienceId($audienceId);
if ($settings->getApiKey() === '' || $audienceId === '') { // error, no API key or list id
return new SubscribeResponse([
'success' => false,
'errorCode' => '2000',
'message' => Craft::t('mailchimp-subscribe', 'API Key or Audience ID not supplied. Check your settings.'),
'values' => array_merge(['email' => $email], $opts ?? [])
]);
}
// create a new api instance, and subscribe
$mc = $this->getClient();
$member = $this->getMemberByEmail($email, $audienceId);
// convert interest groups if present
$interests = [];
if (isset($opts['interests']) && $opts['interests'] !== null) {
$interests = $this->prepInterests($audienceId, $opts['interests']);
}
// marketing permissions
$marketingPermissions = [];
if (isset($opts['marketing_permissions']) && $opts['marketing_permissions'] !== null) {
$marketingPermissions = $this->prepMarketingPermissions($member, $opts['marketing_permissions']);
}
// Build the post variables
$postVars = [
'status_if_new' => $settings->getDoubleOptIn() ? 'pending' : 'subscribed',
'status' => $settings->getDoubleOptIn() ? 'pending' : 'subscribed',
'email_type' => $opts['email_type'] ?? 'html',
'email_address' => $email,
];
if (isset($opts['language']) && $opts['language'] !== null) {
$postVars['language'] = $opts['language'];
}
if (isset($opts['vip']) && $opts['vip'] !== null) {
$postVars['vip'] = $opts['vip'];
}
if (isset($opts['merge_fields']) && is_array($opts['merge_fields']) && count($opts['merge_fields']) > 0) {
$postVars['merge_fields'] = $opts['merge_fields'];
}
if (!empty($interests)) {
$postVars['interests'] = $interests;
$opts['interests'] = $interests;
}
if (!empty($marketingPermissions)) {
$marketingPostObject = [];
foreach ($marketingPermissions as $marketingPermissionId => $marketingPermissionValue) {
$marketingPostObject[] = ['marketing_permission_id' => $marketingPermissionId, 'enabled' => $marketingPermissionValue];
}
$postVars['marketing_permissions'] = $marketingPostObject;
$opts['marketing_permissions'] = $marketingPermissions;
}
// Subscribe
try {
$result = $mc->request('lists/' . $audienceId . '/members/' . md5(strtolower($email)), $postVars, 'PUT');
if (isset($result['_links'])) {
unset($result['_links']);
}
} catch (\Exception $e) {
$message = $e->getMessage();
$errorObj = json_decode($message, false);
if (JSON_ERROR_NONE !== json_last_error()) {
Craft::error('An error occured when trying to subscribe email `' . $email . '`: ' . $message, __METHOD__);
return new SubscribeResponse([
'success' => false,
'errorCode' => $errorObj->status ?? '9999',
'message' => Craft::t('mailchimp-subscribe', $message),
'values' => array_merge(['email' => $email], $opts ?? [])
]);
}
Craft::error('An error occured when trying to subscribe email `' . $email . '`: ' . $errorObj->title . ' (' . $errorObj->status . ')', __METHOD__);
return new SubscribeResponse([
'response' => $errorObj,
'success' => false,
'errorCode' => $errorObj->status,
'message' => Craft::t('mailchimp-subscribe', $errorObj->title),
'values' => array_merge(['email' => $email], $opts ?? [])
]);
}
// Add tags to member if they were submitted.
if (isset($opts['tags']) && $opts['tags'] !== null) {
try {
$tags = $this->prepMemberTags($opts['tags'], $result['tags']);
$tagsResult = $mc->request('lists/' . $audienceId . '/members/' . md5(strtolower($email)) . '/tags', ['tags' => $tags], 'POST');
} catch (\Exception $e) {
Craft::error('An error occured when trying to add tags to email `' . $email . '`: ' . print_r($e->getMessage(), true), __METHOD__);
}
}
return new SubscribeResponse([
'response' => $result,
'success' => true,
'errorCode' => 200,
'message' => Craft::t('mailchimp-subscribe', 'Subscribed successfully'),
'values' => array_merge(['email' => $email], $opts ?? [])
]);
}
/**
* Unsubscribe a member from a Mailchimp lists
*
* @param string $email
* @param string $audienceId
*
* @return SubscribeResponse
* @throws DeprecationException
*/
public function unsubscribe($email, $audienceId): SubscribeResponse
{
// get settings
$settings = Plugin::$plugin->getSettings();
if ($email === '' || !$this->validateEmail($email)) { // error, invalid email
return new SubscribeResponse([
'action' => 'unsubscribe',
'success' => false,
'errorCode' => '1000',
'message' => Craft::t('mailchimp-subscribe', 'Invalid email'),
'values' => ['email' => $email]
]);
}
// get list id string
$audienceId = $this->prepAudienceId($audienceId);
if ($settings->getApiKey() === '' || $audienceId === '') { // error, no API key or list id
return new SubscribeResponse([
'action' => 'unsubscribe',
'success' => false,
'errorCode' => '2000',
'message' => Craft::t('mailchimp-subscribe', 'API Key or Audience ID not supplied. Check your settings.'),
'values' => ['email' => $email]
]);
}
// create a new api instance, and subscribe
$mc = $this->getClient();;
try {
$result = $mc->request('lists/' . $audienceId . '/members/' . md5(strtolower($email)), ['status' => 'unsubscribed'], 'PATCH');
if (isset($result['_links'])) {
unset($result['_links']);
}
} catch (\Exception $e) { // an error occured
$message = $e->getMessage();
$errorObj = json_decode($message, false);
if (JSON_ERROR_NONE !== json_last_error()) {
Craft::error('An error occured when trying to unsubscribe email `' . $email . '`: ' . $message, __METHOD__);
return new SubscribeResponse([
'action' => 'unsubscribe',
'success' => false,
'errorCode' => $errorObj->status ?? '9999',
'message' => Craft::t('mailchimp-subscribe', $message),
'values' => ['email' => $email]
]);
}
Craft::error('An error occured when trying to unsubscribe email `' . $email . '`: ' . $errorObj->title . ' (' . $errorObj->status . ')', __METHOD__);
return new SubscribeResponse([
'action' => 'unsubscribe',
'response' => $errorObj,
'success' => false,
'errorCode' => $errorObj->status,
'message' => Craft::t('mailchimp-subscribe', $errorObj->title),
'values' => ['email' => $email]
]);
}
return new SubscribeResponse([
'action' => 'unsubscribe',
'response' => $result,
'success' => true,
'errorCode' => 200,
'message' => Craft::t('mailchimp-subscribe', 'Unsubscribed successfully'),
'values' => ['email' => $email]
]);
}
/**
* Delete a member from a Mailchimp lists
*
* @param string $email
* @param string $audienceId
* @param bool $permanent
* @return SubscribeResponse
* @throws DeprecationException
*/
public function delete($email, $audienceId, $permanent = false): SubscribeResponse
{
// get settings
$settings = Plugin::$plugin->getSettings();
if ($email === '' || !$this->validateEmail($email)) { // error, invalid email
return new SubscribeResponse([
'action' => 'delete',
'success' => false,
'errorCode' => '1000',
'message' => Craft::t('mailchimp-subscribe', 'Invalid email'),
'values' => ['email' => $email]
]);
}
// get list id string
$audienceId = $this->prepAudienceId($audienceId);
if ($settings->getApiKey() === '' || $audienceId === '') { // error, no API key or list id
return new SubscribeResponse([
'action' => 'delete',
'success' => false,
'errorCode' => '2000',
'message' => Craft::t('mailchimp-subscribe', 'API Key or Audience ID not supplied. Check your settings.'),
'values' => ['email' => $email]
]);
}
// create a new api instance, and subscribe
$mc = $this->getClient();;
try {
if ($permanent) {
$result = $mc->request('lists/' . $audienceId . '/members/' . md5(strtolower($email)) . '/actions/delete-permanent', [], 'POST');
} else {
$result = $mc->request('lists/' . $audienceId . '/members/' . md5(strtolower($email)), [], 'DELETE');
}
if (isset($result['_links'])) {
unset($result['_links']);
}
} catch (\Exception $e) { // an error occured
$message = $e->getMessage();
$errorObj = json_decode($message, false);
if (JSON_ERROR_NONE !== json_last_error()) {
Craft::error('An error occured when trying to delete email `' . $email . '`: ' . $message, __METHOD__);
return new SubscribeResponse([
'action' => 'delete',
'success' => false,
'errorCode' => $errorObj->status ?? '9999',
'message' => Craft::t('mailchimp-subscribe', $message),
'values' => ['email' => $email]
]);
}
Craft::error('An error occured when trying to delete email `' . $email . '`: ' . $errorObj->title . ' (' . $errorObj->status . ')', __METHOD__);
return new SubscribeResponse([
'action' => 'delete',
'response' => $errorObj,
'success' => false,
'errorCode' => $errorObj->status,
'message' => Craft::t('mailchimp-subscribe', $errorObj->title),
'values' => ['email' => $email]
]);
}
return new SubscribeResponse([
'action' => 'delete',
'response' => $result,
'success' => true,
'errorCode' => 200,
'message' => Craft::t('mailchimp-subscribe', 'Deleted successfully'),
'values' => ['email' => $email]
]);
}
/**
* Return member object by email
*
* @param string $email
* @param string $audienceId
*
* @return Collection|null
* @throws DeprecationException
*/
public function getMemberByEmail($email, $audienceId)
{
// get settings
$settings = Plugin::$plugin->getSettings();
$audienceId = $this->prepAudienceId($audienceId);
if ($email === '' || !$this->validateEmail($email)) { // error, invalid email
Craft::error('Invalid email', __METHOD__);
return null;
}
// check if we got an api key and a audience id
if ($settings->getApiKey() === '' || $audienceId === '') {
Craft::error('API Key or Audience ID not supplied. Check your settings.', __METHOD__);
return null;
}
// create a new api instance
$mc = $this->getClient();;
try {
/** @var Collection $member */
$member = $mc->request('lists/' . $audienceId . '/members/' . md5(strtolower($email)));
if (isset($member['_links'])) {
unset($member['_links']);
}
} catch (\Exception $e) { // subscriber didn't exist
$member = null;
}
return $member;
}
/**
* Return audience object by id
*
* @param string $audienceId
*
* @return Collection|null
* @throws DeprecationException
*/
public function getAudienceById($audienceId)
{
// get settings
$settings = Plugin::$plugin->getSettings();
$audienceId = $this->prepAudienceId($audienceId);
// check if we got an api key and id
if ($settings->getApiKey() === '' || $audienceId === '') {
Craft::error('API Key or Audience ID not supplied. Check your settings.', __METHOD__);
return null;
}
// create a new api instance
$mc = $this->getClient();;
try {
/** @var Collection $list */
$list = $mc->request('lists/' . $audienceId);
if (isset($list['_links'])) {
unset($list['_links']);
}
} catch (\Exception $e) { // audience didn't exist
$list = null;
}
return $list;
}
/**
* Gets marketing permissions from member by email
*
* @param $email
* @param $audienceId
* @return array|null
* @throws DeprecationException
*/
public function getMarketingPermissionsByEmail($email, $audienceId)
{
// get settings
$settings = Plugin::$plugin->getSettings();
$audienceId = $this->prepAudienceId($audienceId);
if ($email === '' || !$this->validateEmail($email)) { // error, invalid email
Craft::error('Invalid email', __METHOD__);
return null;
}
// check if we got an api key and id
if ($settings->getApiKey() === '' || $audienceId === '') {
Craft::error('API Key or Audience ID not supplied. Check your settings.', __METHOD__);
return null;
}
$member = $this->getMemberByEmail($email, $audienceId);
if ($member === null) {
return null;
}
return $member['marketing_permissions'] ?? null;
}
/**
* Returns interest groups in audience by id
*
* @param string $audienceId
*
* @return array|null
* @throws DeprecationException
*/
public function getInterestGroups($audienceId = '')
{
$settings = Plugin::$plugin->getSettings();
$audienceId = $this->prepAudienceId($audienceId);
// check if we got an api key and a list id
if ($settings->getApiKey() === '' || $audienceId === '') { // error, no API key or list id
Craft::error('API Key or Audience ID not supplied. Check your settings.', __METHOD__);
return null;
}
// create a new api instance
$mc = $this->getClient();;
try {
/** @var Collection $result */
$result = $mc->request('lists/' . $audienceId . '/interest-categories');
$return = [];
foreach ($result['categories'] as $category) {
$categoryData = [];
$categoryData['title'] = $category->title;
$categoryData['type'] = $category->type;
$categoryData['interests'] = [];
/** @var Collection $interestsResult */
$interestsResult = $mc->request('lists/' . $audienceId . '/interest-categories/' . $category->id . '/interests');
foreach ($interestsResult['interests'] as $interest) {
$interestData = [];
$interestData['id'] = $interest->id;
$interestData['name'] = $interest->name;
$categoryData['interests'][] = $interestData;
}
$return[] = $categoryData;
}
return $return;
} catch (\Exception $e) { // subscriber didn't exist
$message = $e->getMessage();
$msg = json_decode($message, false);
if (JSON_ERROR_NONE !== json_last_error()) {
Craft::error('An error occured when trying to get list interests: ' . $message, __METHOD__);
return null;
}
Craft::error('An error occured when trying to get list interests: ' . $msg->detail, __METHOD__);
return null;
}
}
/**
* Returns member tags from member by email
*
* @param string $email
* @param string $audienceId
* @return array|null
* @throws DeprecationException
*/
public function getMemberTagsByEmail($email, $audienceId = '')
{
$settings = Plugin::$plugin->getSettings();
$audienceId = $this->prepAudienceId($audienceId);
if ($email === '' || !$this->validateEmail($email)) { // error, invalid email
Craft::error('Invalid email', __METHOD__);
return null;
}
// check if we got an api key and a list id
if ($settings->getApiKey() === '' || $audienceId === '') { // error, no API key or list id
Craft::error('API Key or Audience ID not supplied. Check your settings.', __METHOD__);
return null;
}
// create a new api instance
$mc = $this->getClient();
try {
/** @var Collection $result */
$result = $mc->request('lists/' . $audienceId . '/members/' . md5(strtolower($email)) . '/tags');
} catch (\Exception $e) { // subscriber didn't exist
$message = $e->getMessage();
$msg = json_decode($message, false);
if (JSON_ERROR_NONE !== json_last_error()) {
Craft::error('An error occured when trying to get list interests: ' . $message, __METHOD__);
return null;
}
Craft::error('An error occured when trying to get list interests: ' . $msg->detail, __METHOD__);
return null;
}
return $result['tags'];
}
/**
* --- Deprecated methods --------------------------------------------------------------------------------------
*/
/**
* @param string $listId
* @return array|mixed
* @throws DeprecationException
* @deprecated Deprecated since version 3.0
*/
public function getListInterestGroups($listId = '')
{
Craft::$app->deprecator->log(__METHOD__, 'The `getListInterestGroups` template variable and service method is deprecated. Use `getInterestGroups` instead.');
return $this->getInterestGroups($listId);
}
/**
* Check if email is subscribed to one or more lists.
*
* @param string $email
* @param string $audienceId
*
* @return array|mixed
* @throws DeprecationException
* @deprecated Deprecated since version 3.0
*/
public function checkIfSubscribed($email, $audienceId)
{
Craft::$app->deprecator->log(__METHOD__, 'The `checkIfSubscribed` service method and controller action has been deprecated. Use `getMemberByEmail` and check `status` instead.');
// get settings
$settings = Plugin::$plugin->getSettings();
if ($email === '' || !$this->validateEmail($email)) { // error, invalid email
return $this->getMessage(1000, $email, [], Craft::t('mailchimp-subscribe', 'Invalid email'));
}
$audienceId = $this->prepAudienceId($audienceId);
// check if we got an api key and a list id
if ($settings->getApiKey() === '' || $audienceId === '') { // error, no API key or list id
return $this->getMessage(2000, $email, [], Craft::t('mailchimp-subscribe', 'API Key or Audience ID not supplied. Check your settings.'));
}
$member = $this->getMemberByEmail($email, $audienceId);
if ($member) {
if ($member['status'] === 'subscribed') {
return $this->getMessage(200, $email, [], Craft::t('mailchimp-subscribe', 'The email address exists on this list'), true);
}
return $this->getMessage(200, $email, [], Craft::t('mailchimp-subscribe', 'The email address was unsubscribed from this list'), false);
}
return $this->getMessage(1000, $email, [], Craft::t('mailchimp-subscribe', 'The email address does not exist on this list'), false);
}
/**
* Check if email exists in one or more lists.
*
* @param string $email
* @param string $listId
*
* @return array|mixed
* @throws DeprecationException
* @deprecated Deprecated since version 3.0
*/
public function checkIfInList($email, $listId)
{
Craft::$app->deprecator->log(__METHOD__, 'The `checkIfInList` service method and controller action has been deprecated. Use `getMemberByEmail` and check `status` instead.');
// get settings
$settings = Plugin::$plugin->getSettings();
if ($email === '' || !$this->validateEmail($email)) { // error, invalid email
return $this->getMessage(1000, $email, [], Craft::t('mailchimp-subscribe', 'Invalid email'));
}
$listId = $this->prepAudienceId($listId);
// check if we got an api key and a list id
if ($settings->getApiKey() === '' || $listId === '') { // error, no API key or list id
return $this->getMessage(2000, $email, [], Craft::t('mailchimp-subscribe', 'API Key or Audience ID not supplied. Check your settings.'));
}
if ($this->getMemberByEmail($email, $listId)) {
return $this->getMessage(200, $email, [], Craft::t('mailchimp-subscribe', 'The email address exists on this list'), true);
}
return $this->getMessage(1000, $email, [], Craft::t('mailchimp-subscribe', 'The email address does not exist on this list'), false);
}
/**
* Creates return message object
*
* @param string|int $errorcode
* @param string $email
* @param array $vars
* @param string $message
* @param bool $success
*
* @return array
* @author Martin Blackburn
* @deprecated Deprecated since version 3.0
*/
private function getMessage($errorcode, $email, $vars, $message = '', $success = false): array
{
return [
'success' => $success,
'errorCode' => $errorcode,
'message' => $message,
'values' => [
'email' => $email,
'vars' => $vars
]
];
}
/**
* --- Private methods --------------------------------------------------------------------------------------
*/
/**
* Creates Mailchimp client
*
* @return Mailchimp
*/
private function getClient(): Mailchimp
{
$settings = Plugin::$plugin->getSettings();
return new Mailchimp(Craft::parseEnv($settings->getApiKey()));
}
/**
* Gets the correct list ID to use. Throws deprecation errors if something is wrong.
*
* @param $audienceId
* @return string
* @throws DeprecationException
*/
private function prepAudienceId($audienceId): string
{
/** @var Settings $settings */
$settings = Plugin::$plugin->getSettings();
if ($settings->listId !== '') {
Craft::$app->deprecator->log(__METHOD__ . '_listId_setting', 'The Mailchimp Subscribe config setting `listId` has been deprecated and will be removed in the next major version. Use `audienceId` instead.');
if ($settings->getAudienceId() === '') {
$settings->audienceId = $settings->listId;
}
}
$audienceId = !empty($audienceId) ? $audienceId : $settings->getAudienceId();
// split id string on | in case more than one list id is supplied
$audienceIdArr = explode('|', $audienceId);
if (count($audienceIdArr) > 1) {
Craft::$app->deprecator->log(__METHOD__, 'Mailchimp Subscribe no longer supports using multiple lists by adding multiple list ids as a pipe-seperated string.');
$audienceId = $audienceIdArr[0];
}
return Craft::parseEnv($audienceId);
}
/**
* Preps interests. For groups that have been set in front-end form, existing interests are reset.
*
* @param string $audienceId
* @param array|string $interests
*
* @return array
* @throws DeprecationException
*/
private function prepInterests($audienceId, $interests): array
{
$interestGroupsResult = $this->getInterestGroups($audienceId);
$r = [];
// Reset all interests
foreach ($interestGroupsResult as $group) {
if (isset($interests[$group['title']])) {
foreach ($group['interests'] as $groupInterest) {
$r[$groupInterest['id']] = false;
}
}
}
// add configures interests
if (is_array($interests)) {
foreach ($interests as $interestGroup) {
if (is_array($interestGroup)) {
foreach ($interestGroup as $interest) {
$r[$interest] = true;
}
}
}
}
return $r;
}
/**
* Preps marketing permissions array by adding all missing permissions to array and assuming that they are disabled.
*
* @param Collection|null $member
* @param array $marketingPermissions
* @return array
*/
private function prepMarketingPermissions($member, $marketingPermissions): array
{
$memberMarketingPermissions = $member ? $member['marketing_permissions'] : [];
$r = [];
foreach ($memberMarketingPermissions as $memberMarketingPermission) {
$r[$memberMarketingPermission->marketing_permission_id] = false;
}
if (is_array($marketingPermissions)) {
foreach ($marketingPermissions as $marketingPermission) {
$r[$marketingPermission] = true;
}
}
return $r;
}
/**
* Preps submitted array of tags for sending to member tags endpoint.
*
* @param array $tags
* @param array $memberTags
* @return array
*/
private function prepMemberTags($tags, $memberTags): array
{
$r = [];
$tagsMap = [];
foreach ($memberTags as $tag) {
$tagsMap[$tag->name] = 'inactive';
}
if (is_array($tags)) {
foreach ($tags as $tag) {
$tagsMap[$tag] = 'active';
}
}
foreach ($tagsMap as $tag=>$status) {
$r[] = ['name' => $tag, 'status' => $status];
}
return $r;
}
/**
* Validate an email address.
* Provide email address (raw input)
* Returns true if the email address has the email
* address format and the domain exists.
*
* @param string $email Email to validate
*
* @return boolean
* @author André Elvan
*/
public function validateEmail($email): bool
{
$isValid = true;
$atIndex = strrpos($email, '@');
if (is_bool($atIndex) && !$atIndex) {
$isValid = false;
} else {
$domain = substr($email, $atIndex + 1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64) {
// local part length exceeded
$isValid = false;
} else if ($domainLen < 1 || $domainLen > 255) {
// domain part length exceeded
$isValid = false;
} else if (strpos($local, '.') === 0 || $local[$localLen - 1] === '.') {
// local part starts or ends with '.'
$isValid = false;
} else if (preg_match('/\\.\\./', $local)) {
// local part has two consecutive dots
$isValid = false;
} else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
// character not valid in domain part
$isValid = false;
} else if (preg_match('/\\.\\./', $domain)) {
// domain part has two consecutive dots
$isValid = false;
} else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\", "", $local))) {
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\", "", $local))) {
$isValid = false;
}
}
if ($isValid && !(checkdnsrr($domain, "MX") || checkdnsrr($domain, "A"))) {
// domain not found in DNS
$isValid = false;
}
}
return $isValid;
}
}