This repository has been archived by the owner on Dec 22, 2018. It is now read-only.
/
mailchimp.module
1617 lines (1460 loc) · 46.9 KB
/
mailchimp.module
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
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* Mailchimp module.
*/
define('MAILCHIMP_QUEUE_CRON', 'mailchimp');
define('MAILCHIMP_BATCH_QUEUE_CRON', 'mailchimp_batch');
define('MAILCHIMP_STATUS_SENT', 'sent');
define('MAILCHIMP_STATUS_SAVE', 'save');
define('MAILCHIMP_STATUS_PAUSED', 'paused');
define('MAILCHIMP_STATUS_SCHEDULE', 'schedule');
define('MAILCHIMP_STATUS_SENDING', 'sending');
/**
* Implements hook_libraries_info().
*/
function mailchimp_libraries_info() {
$libraries['mailchimp'] = array(
'name' => 'MailChimp API',
'vendor url' => 'https://github.com/thinkshout/mailchimp-api-php',
'download url' => 'https://github.com/thinkshout/mailchimp-api-php/archive/v1.0.3.zip',
'version arguments' => array(
'file' => 'composer.json',
'pattern' => '/"version": "([0-9a-zA-Z.-]+)"/',
),
'files' => array(
'php' => array(
'src/Mailchimp.php',
'src/MailchimpAPIException',
'src/MailchimpCampaigns.php',
'src/MailchimpLists.php',
'src/MailchimpReports.php',
'src/MailchimpTemplates.php',
'vendor/autoload.php',
),
),
);
return $libraries;
}
/**
* Implements hook_menu().
*/
function mailchimp_menu() {
$items = array();
$items['admin/config/services/mailchimp'] = array(
'title' => 'MailChimp',
'description' => t('Manage MailChimp Settings.'),
'page callback' => 'drupal_get_form',
'page arguments' => array('mailchimp_admin_settings'),
'access arguments' => array('administer mailchimp'),
'file' => 'includes/mailchimp.admin.inc',
'type' => MENU_NORMAL_ITEM,
);
$items['admin/config/services/mailchimp/global'] = array(
'title' => t('Global Settings'),
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
);
$items['admin/config/services/mailchimp/list_cache_clear'] = array(
'title' => 'MailChimp webhooks endpoint',
'page callback' => 'drupal_get_form',
'page arguments' => array('mailchimp_clear_list_cache_form'),
'access callback' => 'mailchimp_apikey_ready_access',
'access arguments' => array('administer mailchimp'),
'file' => 'includes/mailchimp.admin.inc',
'type' => MENU_CALLBACK,
);
$items['mailchimp/webhook'] = array(
'title' => 'MailChimp webhooks endpoint',
'page callback' => 'mailchimp_process_webhook',
'access callback' => 'mailchimp_process_webhook_access',
'access arguments' => array(2),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Implements hook_permission().
*/
function mailchimp_permission() {
return array(
'administer mailchimp' => array(
'title' => t('administer mailchimp'),
'description' => t('Access the MailChimp configuration options.'),
),
);
}
/**
* Access callback for mailchimp submodule menu items.
*/
function mailchimp_apikey_ready_access($permission) {
if (mailchimp_get_api_object() && user_access($permission)) {
return TRUE;
}
return FALSE;
}
/**
* Get an instance of the MailChimp library.
*
* @param string $classname
* The MailChimp library class to instantiate.
* @param string $api_key
* The MailChimp api key to use if not the default.
*
* @return Mailchimp
* Instance of the MailChimp library class. Can be overridden by $classname.
*/
function mailchimp_get_api_object($classname = 'Mailchimp', $api_key = NULL) {
// Set correct library class namespace depending on test mode.
if (variable_get('mailchimp_test_mode', FALSE)) {
$classname = '\Mailchimp\Tests\\' . $classname;
}
else {
$classname = '\Mailchimp\\' . $classname;
}
$mailchimp = &drupal_static(__FUNCTION__);
if (!$api_key && isset($mailchimp) && $mailchimp instanceof $classname) {
return $mailchimp;
}
if (module_exists('libraries')) {
$library = libraries_load('mailchimp');
}
else {
$library = FALSE;
}
if (!$library['installed'] && !class_exists('Mailchimp\Mailchimp')) {
$msg = t('Failed to load MailChimp PHP library. Please refer to the installation requirements.');
watchdog('mailchimp', $msg, array(), WATCHDOG_ERROR);
drupal_set_message($msg, 'error', FALSE);
return NULL;
}
if (!class_exists('\GuzzleHttp\Client')) {
$msg = t('The MailChimp PHP library is missing the required GuzzleHttp library. Please check the installation notes in README.txt.');
watchdog('mailchimp', $msg, array(), WATCHDOG_ERROR);
drupal_set_message($msg, 'error', FALSE);
return NULL;
}
$context = array(
'api_class' => $classname,
);
if (!$api_key) {
$api_key = $default_api_key = variable_get('mailchimp_api_key', '');
// Allow modules to alter the default.
drupal_alter('mailchimp_api_key', $api_key, $context);
// Check to see if the key was altered.
if ($api_key !== $default_api_key) {
// Invalidate all caches because the key was altered.
mailchimp_cache_clear_all();
}
}
if (!strlen($api_key)) {
watchdog('mailchimp', t('MailChimp Error: API Key cannot be blank.'), array(), WATCHDOG_ERROR);
return NULL;
}
// Set the timeout to something that won't take down the Drupal site:
$timeout = 60;
$mailchimp = new $classname($api_key, 'apikey', $timeout);
return $mailchimp;
}
/**
* Wrapper around mailchimp_get_lists() to return a single list.
*
* @param string $list_id
* The unique ID of the list provided by MailChimp.
*
* @return array
* A list array formatted as indicated in the MailChimp API documentation.
*/
function mailchimp_get_list($list_id) {
$lists = mailchimp_get_lists(array($list_id));
return reset($lists);
}
/**
* Return all MailChimp lists for a given key. Lists are stored in the cache.
*
* @param array $list_ids
* An array of list IDs to filter the results by.
* @param bool $reset
* Force a cache reset.
*
* @return array
* An array of list arrays.
*/
function mailchimp_get_lists($list_ids = array(), $reset = FALSE) {
$cache = $reset ? NULL : cache_get('lists', 'cache_mailchimp');
$lists = array();
// Return cached lists:
if ($cache) {
$lists = $cache->data;
}
// Query lists from the MailChimp API and store in cache:
else {
try {
/* @var \Mailchimp\MailchimpLists $mc_lists */
$mc_lists = mailchimp_get_api_object('MailchimpLists');
if (!$mc_lists) {
throw new MailchimpException('Cannot get lists without MailChimp API. Check API key has been entered.');
}
$result = $mc_lists->getLists(array('count' => 500));
if ($result->total_items > 0) {
foreach ($result->lists as $list) {
$int_category_data = $mc_lists->getInterestCategories($list->id, array('count' => 500));
if ($int_category_data->total_items > 0) {
$list->intgroups = array();
foreach ($int_category_data->categories as $interest_category) {
$interest_data = $mc_lists->getInterests($list->id, $interest_category->id, array('count' => 500));
if ($interest_data->total_items > 0) {
$interest_category->interests = $interest_data->interests;
}
$list->intgroups[] = $interest_category;
}
}
$lists[$list->id] = $list;
// Append mergefields:
$mergefields = $mc_lists->getMergeFields($list->id, array('count' => 500));
if ($mergefields->total_items > 0) {
$lists[$list->id]->mergevars = $mergefields->merge_fields;
}
}
}
uasort($lists, '_mailchimp_list_cmp');
cache_set('lists', $lists, 'cache_mailchimp', CACHE_TEMPORARY);
}
catch (Exception $e) {
watchdog('mailchimp', 'An error occurred requesting list information from MailChimp. "%message"', array(
'%message' => $e->getMessage(),
), WATCHDOG_ERROR);
}
}
// Filter by given ids:
if (!empty($list_ids)) {
$filtered_lists = array();
foreach ($list_ids as $id) {
if (array_key_exists($id, $lists)) {
$filtered_lists[$id] = $lists[$id];
}
}
return $filtered_lists;
}
else {
return $lists;
}
}
/**
* Helper function used by uasort() to sort lists alphabetically by name.
*
* @param array $a
* An array representing the first list.
* @param array $b
* An array representing the second list.
*
* @return int
* One of the values -1, 0, 1
*/
function _mailchimp_list_cmp($a, $b) {
if ($a->name == $b->name) {
return 0;
}
return ($a->name < $b->name) ? -1 : 1;
}
/**
* Wrapper around MailchimpLists->getMergeFields().
*
* @param array $list_ids
* Array of MailChimp list IDs.
* @param bool $reset
* Set to TRUE if mergevars should not be loaded from cache.
*
* @return array
* Struct describing mergevars for the specified lists.
*/
function mailchimp_get_mergevars($list_ids, $reset = FALSE) {
$mergevars = array();
if (!$reset) {
foreach ($list_ids as $key => $list_id) {
$cache = cache_get($list_id . '-mergevars', 'cache_mailchimp');
// Get cached data and unset from our remaining lists to query.
if ($cache) {
$mergevars[$list_id] = $cache->data;
unset($list_ids[$key]);
}
}
}
/* @var \Mailchimp\MailchimpLists $mc_lists */
$mc_lists = mailchimp_get_api_object('MailchimpLists');
try {
if (!$mc_lists) {
throw new MailchimpException('Cannot get merge vars without MailChimp API. Check API key has been entered.');
}
// Get the uncached merge vars from MailChimp.
foreach ($list_ids as $list_id) {
// Add default EMAIL merge var for all lists.
$mergevars[$list_id] = array(
(object) array(
'tag' => 'EMAIL',
'name' => 'Email Address',
'type' => 'email',
'required' => TRUE,
'default_value' => '',
'public' => TRUE,
'display_order' => 1,
'options' => (object) array(
'size' => 25,
),
),
);
$result = $mc_lists->getMergeFields($list_id, array('count' => 500));
if ($result->total_items > 0) {
$mergevars[$list_id] = array_merge($mergevars[$list_id], $result->merge_fields);
}
cache_set($list_id . '-mergevars', $mergevars[$list_id], 'cache_mailchimp', CACHE_TEMPORARY);
}
}
catch (Exception $e) {
watchdog('mailchimp', 'An error occurred requesting mergevars for list @list. "%message"', array(
'@list' => $list_id,
'%message' => $e->getMessage(),
), WATCHDOG_ERROR);
}
return $mergevars;
}
/**
* Get the MailChimp member info for a given email address and list.
*
* Results are cached in the cache_mailchimp bin which is cleared by the
* MailChimp web hooks system when needed.
*
* @param string $list_id
* The MailChimp list ID to get member info for.
* @param string $email
* The MailChimp user email address to load member info for.
* @param bool $reset
* Set to TRUE if member info should not be loaded from cache.
*
* @return object
* Member info object, empty if there is no valid info.
*/
function mailchimp_get_memberinfo($list_id, $email, $reset = FALSE) {
$cache = $reset ? NULL : cache_get($list_id . '-' . $email, 'cache_mailchimp');
// Return cached lists:
if ($cache) {
return $cache->data;
}
// Query lists from the MCAPI and store in cache:
$memberinfo = new stdClass();
/* @var \Mailchimp\MailchimpLists $mc_lists */
$mc_lists = mailchimp_get_api_object('MailchimpLists');
try {
if (!$mc_lists) {
throw new MailchimpException('Cannot get member info without MailChimp API. Check API key has been entered.');
}
try {
$memberinfo = $mc_lists->getMemberInfo($list_id, $email);
cache_set($list_id . '-' . $email, $memberinfo, 'cache_mailchimp', CACHE_TEMPORARY);
}
catch (Exception $e) {
// Throw exception only for errors other than member not found.
if ($e->getCode() != 404) {
throw new Exception($e->getMessage(), $e->getCode(), $e);
}
}
}
catch (Exception $e) {
watchdog('mailchimp', 'An error occurred requesting memberinfo for @email in list @list. "%message"', array(
'@email' => $email,
'@list' => $list_id,
'%message' => $e->getMessage(),
), WATCHDOG_ERROR);
}
return $memberinfo;
}
/**
* Check if the given email is subscribed to the given list.
*
* Simple wrapper around mailchimp_get_memberinfo().
*
* @param string $list_id
* Unique string identifier for the list on your MailChimp account.
* @param string $email
* Email address to check for on the identified MailChimp List
* @param bool $reset
* Set to TRUE to ignore the cache. (Used heavily in testing functions.)
*
* @return bool
* Indicates subscription status.
*/
function mailchimp_is_subscribed($list_id, $email, $reset = FALSE) {
$subscribed = FALSE;
$memberinfo = mailchimp_get_memberinfo($list_id, $email, $reset);
if (isset($memberinfo->status) && $memberinfo->status == 'subscribed') {
$subscribed = TRUE;
}
return $subscribed;
}
/**
* Subscribe a user to a MailChimp list in real time or by adding to the queue.
*
* @see Mailchimp_Lists::subscribe()
*
* @return bool
* True on success.
*/
function mailchimp_subscribe($list_id, $email, $merge_vars = NULL, $interests = array(), $double_optin = FALSE, $format = 'html') {
if (variable_get('mailchimp_cron', FALSE)) {
$args = array(
'list_id' => $list_id,
'email' => $email,
'merge_vars' => $merge_vars,
'interests' => $interests,
'double_optin' => $double_optin,
'format' => $format,
);
return mailchimp_addto_queue('mailchimp_subscribe_process', $args);
}
return mailchimp_subscribe_process($list_id, $email, $merge_vars, $interests, $double_optin, $format);
}
/**
* Wrapper around Mailchimp_Lists::subscribe().
*
* @see Mailchimp_Lists::subscribe()
*
* @return bool
* True on success.
*/
function mailchimp_subscribe_process($list_id, $email, $merge_vars = NULL, $interests = array(), $double_optin = FALSE, $format = 'html') {
$result = FALSE;
try {
/* @var \Mailchimp\MailchimpLists $mc_lists */
$mc_lists = mailchimp_get_api_object('MailchimpLists');
if (!$mc_lists) {
throw new MailchimpException('Cannot subscribe to list without MailChimp API. Check API key has been entered.');
}
$parameters = array(
// If double opt-in is required, set member status to 'pending'
'status' => ($double_optin) ? \Mailchimp\MailchimpLists::MEMBER_STATUS_PENDING : \Mailchimp\MailchimpLists::MEMBER_STATUS_SUBSCRIBED,
'email_type' => $format,
);
// Set interests.
if (!empty($interests)) {
$selected_interests = array();
foreach ($interests as $interest_group) {
foreach ($interest_group as $interest_id => $interest_status) {
$selected_interests[$interest_id] = ($interest_status !== 0);
}
}
if (!empty($selected_interests)) {
$parameters['interests'] = (object) $selected_interests;
}
}
// Set merge fields.
if (!empty($merge_vars)) {
$parameters['merge_fields'] = (object) $merge_vars;
}
// Add member to list.
$result = $mc_lists->addOrUpdateMember($list_id, $email, $parameters);
if (isset($result->id)) {
module_invoke_all('mailchimp_subscribe_user', $list_id, $email, $merge_vars);
// Clear user cache, just in case there's some cruft leftover:
mailchimp_cache_clear_member($list_id, $email);
watchdog('mailchimp', '@email was subscribed to list @list.',
array('@email' => $email, '@list' => $list_id), WATCHDOG_NOTICE
);
}
else {
if (!variable_get('mailchimp_test_mode')) {
watchdog('mailchimp', 'A problem occurred subscribing @email to list @list.', array(
'@email' => $email,
'@list' => $list_id,
), WATCHDOG_WARNING);
}
}
}
catch (Exception $e) {
watchdog('mailchimp', 'An error occurred subscribing @email to list @list. "%message"', array(
'@email' => $email,
'@list' => $list_id,
'%message' => $e->getMessage(),
), WATCHDOG_ERROR);
}
return $result;
}
/**
* Add a MailChimp subscription task to the queue.
*
* @string $function
* The name of the function the queue runner should call.
* @array $args
* The list of args to pass to the function.
*
* @return bool
* Success or failure.
*/
function mailchimp_addto_queue($function, $args) {
$queue = DrupalQueue::get(MAILCHIMP_QUEUE_CRON);
$queue->createQueue();
mailchimp_update_local_cache($function, $args);
return $queue->createItem(array(
'function' => $function,
'args' => $args,
));
}
/**
* Updates the local cache for a user as though a queued request had been processed.
*
* If we don't do this, then users can make changes, but not have them shown on the site until
* cron runs, which is intensely confusing. See https://www.drupal.org/node/2503597
*
* @string $function
* The name of the function that the queue runner will call when the update is processed.
* @array $args
* The list of args that will be passed to the queue runner.
*/
function mailchimp_update_local_cache($function, $args) {
$list_id = isset($args['list_id']) ? $args['list_id'] : NULL;
$email = isset($args['email']) ? $args['email'] : NULL;
if (empty($list_id) || empty($email)) {
return FALSE;
}
$cache = mailchimp_get_memberinfo($list_id, $email);
if (empty($cache)) {
// Create a new entry.
cache_set($list_id . '-' . $email,
(object) array('merge_fields' => new stdClass()),
'cache_mailchimp',
CACHE_TEMPORARY);
$cache = cache_get($list_id . '-' . $email, 'cache_mailchimp');
$cache = $cache->data;
}
// Handle unsubscribes.
if ($function == 'mailchimp_unsubscribe_process') {
$cache->status = 'unsubscribed';
// Reset interests.
$cache->interests = new stdClass();
}
// Handle subscribes.
if ($function == 'mailchimp_subscribe_process') {
$cache->status = 'subscribed';
}
// Handle member updates.
if ($function == 'mailchimp_update_member_process' ||
$function == 'mailchimp_subscribe_process') {
// Update cached merge vars.
foreach ($args['merge_vars'] as $key => $value) {
$cache->merge_fields->$key = $value;
}
// Update cached interests.
$cache->interests = new stdClass();
foreach ($args['interests'] as $interest_group => $interests) {
foreach ($interests as $interest_id => $value) {
if ($value !== 0) {
$cache->interests->$interest_id = TRUE;
}
}
}
}
// Store the data back in the local cache.
cache_set($list_id . '-' . $email, $cache, 'cache_mailchimp', CACHE_TEMPORARY);
}
/**
* Update a members list subscription in real time or by adding to the queue.
*
* @see Mailchimp_Lists::updateMember()
*
* @return bool
* Success or failure.
*/
function mailchimp_update_member($list_id, $email, $merge_vars, $interests, $format = 'html') {
if (variable_get('mailchimp_cron', FALSE)) {
$args = array(
'list_id' => $list_id,
'email' => $email,
'merge_vars' => $merge_vars,
'interests' => $interests,
'format' => $format,
);
return mailchimp_addto_queue('mailchimp_update_member_process', $args);
}
return mailchimp_update_member_process($list_id, $email, $merge_vars, $interests, $format);
}
/**
* Wrapper around Mailchimp_Lists::updateMember().
*
* @see Mailchimp_Lists::updateMember()
*
* @return bool
* Success or failure.
*/
function mailchimp_update_member_process($list_id, $email, $merge_vars, $interests, $format) {
$result = FALSE;
try {
/* @var \Mailchimp\MailchimpLists $mc_lists */
$mc_lists = mailchimp_get_api_object('MailchimpLists');
if (!$mc_lists) {
throw new MailchimpException('Cannot update member without MailChimp API. Check API key has been entered.');
}
$parameters = array(
'status' => 'subscribed',
'email_type' => $format,
);
// Set interests.
if (!empty($interests)) {
$selected_interests = array();
foreach ($interests as $interest_group) {
foreach ($interest_group as $interest_id => $interest_status) {
$selected_interests[$interest_id] = ($interest_status !== 0);
}
}
if (!empty($selected_interests)) {
$parameters['interests'] = (object) $selected_interests;
}
}
// Set merge fields.
if (!empty($merge_vars)) {
$parameters['merge_fields'] = (object) $merge_vars;
}
// Update member.
$result = $mc_lists->updateMember($list_id, $email, $parameters);
if (isset($result->id)) {
watchdog('mailchimp', '@email was updated in list @list_id.', array(
'@email' => $email,
'@list' => $list_id,
), WATCHDOG_NOTICE);
// Clear user cache:
mailchimp_cache_clear_member($list_id, $email);
}
else {
watchdog('mailchimp', 'A problem occurred updating @email on list @list.', array(
'@email' => $email,
'@list' => $list_id,
), WATCHDOG_WARNING);
}
}
catch (Exception $e) {
watchdog('mailchimp', 'An error occurred updating @email on list @list. "%message"', array(
'@email' => $email,
'@list' => $list_id,
'%message' => $e->getMessage(),
), WATCHDOG_ERROR);
}
return $result;
}
/**
* Retrieve all members of a given list with a given status.
*
* Note that this function can cause locking an is somewhat slow. It is not
* recommended unless you know what you are doing! See the MCAPI documentation.
*/
function mailchimp_get_members($list_id, $status = 'subscribed', $options = array()) {
$results = FALSE;
if (lock_acquire('mailchimp_get_members', 60)) {
try {
/* @var \Mailchimp\MailchimpLists $mc_lists */
$mc_lists = mailchimp_get_api_object('MailchimpLists');
if (!$mc_lists) {
throw new MailchimpException('Cannot get members without MailChimp API. Check API key has been entered.');
}
$options['status'] = $status;
$options['count'] = 500;
$results = $mc_lists->getMembers($list_id, $options);
}
catch (Exception $e) {
watchdog('mailchimp', 'An error occurred pulling member info for a list. "%message"', array(
'%message' => $e->getMessage(),
), WATCHDOG_ERROR);
}
lock_release('mailchimp_get_members');
}
return $results;
}
/**
* Wrapper around MailchimpLists->addOrUpdateMember().
*
* $batch is an array where each element is an array formatted thus:
* 'email' => 'example@example.com',
* 'email_type' => 'html' or 'text',
* 'merge_vars' => array('MERGEKEY' => 'value', 'MERGEKEY2' => 'value2'),
*/
function mailchimp_batch_update_members($list_id, $batch, $double_in = FALSE) {
try {
/* @var \Mailchimp\MailchimpLists $mc_lists */
$mc_lists = mailchimp_get_api_object('MailchimpLists');
if (!$mc_lists) {
throw new MailchimpException('Cannot batch subscribe to list without MailChimp API. Check API key has been entered.');
}
if (!empty($batch)) {
// Create a new batch update operation for each member.
foreach ($batch as $batch_data) {
// TODO: Remove 'advanced' earlier? Needed at all?
unset($batch_data['merge_vars']['advanced']);
$parameters = array(
'email_type' => $batch_data['email_type'],
'merge_fields' => (object) $batch_data['merge_vars'],
);
$mc_lists->addOrUpdateMember($list_id, $batch_data['email'], $parameters, TRUE);
}
// Process batch operations.
return $mc_lists->processBatchOperations();
}
}
catch (Exception $e) {
watchdog('mailchimp', 'An error occurred performing batch subscribe/update. "%message"', array(
'%message' => $e->getMessage(),
), WATCHDOG_ERROR);
}
}
/**
* Unsubscribe a member from a list.
*
* @param string $list_id
* A mailchimp list id.
* @param string $email
* Email address to be unsubscribed.
* @param bool $delete
* Indicates whether an email should be deleted or just unsubscribed.
* @param bool $goodbye
* Indicates whether to send the goodbye email to the email address.
* @param bool $notify
* Indicates whether to send the unsubscribe notification email to the address
* defined in the list email notification settings.
* @param object $mcapi
* MailChimp API object if one is already loaded.
* @param bool $allow_async
* Set to TRUE to allow asynchronous processing using DrupalQueue.
*
* @return bool
* Indicates whether unsubscribe was successful.
*/
function mailchimp_unsubscribe($list_id, $email, $delete = FALSE, $goodbye = FALSE, $notify = FALSE) {
$result = FALSE;
if (mailchimp_is_subscribed($list_id, $email)) {
if (variable_get('mailchimp_cron', FALSE)) {
$result = mailchimp_addto_queue(
'mailchimp_unsubscribe_process',
array(
'list_id' => $list_id,
'email' => $email,
'delete' => $delete,
'goodbye' => $goodbye,
'notify' => $notify,
)
);
}
else {
$result = mailchimp_unsubscribe_process($list_id, $email, $delete, $goodbye, $notify);
}
}
return $result;
}
/**
* Wrapper around Mailchimp_Lists::unsubscribe().
*
* @see Mailchimp_Lists::unsubscribe()
*
* @return bool
* Success or failure.
*/
function mailchimp_unsubscribe_process($list_id, $email, $delete, $goodbye, $notify) {
try {
/* @var \Mailchimp\MailchimpLists $mc_lists */
$mc_lists = mailchimp_get_api_object('MailchimpLists');
if (!$mc_lists) {
throw new MailchimpException('Cannot unsubscribe from list without MailChimp API. Check API key has been entered.');
}
$mc_lists->removeMember($list_id, $email);
module_invoke_all('mailchimp_unsubscribe_user', $list_id, $email);
// Clear user cache:
mailchimp_cache_clear_member($list_id, $email);
return TRUE;
}
catch (Exception $e) {
watchdog('mailchimp', 'An error occurred unsubscribing @email from list @list. "%message"', array(
'@email' => $email,
'@list' => $list_id,
'%message' => $e->getMessage(),
), WATCHDOG_ERROR);
return FALSE;
}
}
/**
* Wrapper around MailchimpLists->getSegments().
*
* @param string $list_id
* A MailChimp list id.
* @param bool $reset
* Set to TRUE if list segments should not be loaded from cache.
*
* @return array
* Array of segments details.
*/
function mailchimp_get_segments($list_id, $reset = NULL) {
$cache = $reset ? NULL : cache_get($list_id . '-segments', 'cache_mailchimp');
// Return cached lists:
if ($cache) {
return $cache->data;
}
// Query segments from the MCAPI and store in cache:
$segments = array();
try {
/* @var \Mailchimp\MailchimpLists $mc_lists */
$mc_lists = mailchimp_get_api_object('MailchimpLists');
if (!$mc_lists) {
throw new MailchimpException('Cannot get list segments without MailChimp API. Check API key has been entered.');
}
$result = $mc_lists->getSegments($list_id, array('count' => 500));
$segments = ($result->total_items > 0) ? $result->segments : array();
cache_set($list_id . '-segments', $segments, 'cache_mailchimp', CACHE_TEMPORARY);
}
catch (Exception $e) {
watchdog('mailchimp', 'An error occurred requesting list segment information from MailChimp. "%message"', array(
'%message' => $e->getMessage(),
), WATCHDOG_ERROR);
}
return $segments;
}
/**
* Wrapper around MailchimpLists->addSegment().
*
* @param string $list_id
* A MailChimp list id.
* @param string $name
* A label for the segment.
* @param string $type
* 'static' or 'saved'
* @param array $segment_options
* Array of options for 'saved' segments. See MailChimp API docs.
*
* @return int
* ID of the new segment.
*/
function mailchimp_segment_create($list_id, $name, $type, $segment_options = NULL) {
$segment_id = FALSE;
try {
/* @var \Mailchimp\MailchimpLists $mc_lists */
$mc_lists = mailchimp_get_api_object('MailchimpLists');
if (!$mc_lists) {
throw new MailchimpException('Cannot add list segment without MailChimp API. Check API key has been entered.');
}
$parameters = array(
'type' => $type,
);
if ($type == 'saved') {
$parameters['options'] = $segment_options;
}
$result = $mc_lists->addSegment($list_id, $name, $parameters);
if (!empty($result->id)) {
$segment_id = $result->id;
}
// Clear the segment cache:
mailchimp_get_segments($list_id, TRUE);
}
catch (Exception $e) {
watchdog('mailchimp', 'An error occurred creating segment @segment for list @list. "%message"', array(
'@segment' => $name,
'@list' => $list_id,
'%message' => $e->getMessage(),
), WATCHDOG_ERROR);
}
return $segment_id;
}
/**
* Add a specific subscriber to a static segment of a list.
*
* @param string $list_id
* ID of a MailChimp list
* @param string $segment_id
* ID of a segment of the MailChimp list
* @param string $email
* Email address to add to the segment (does NOT subscribe to the list)
* @param bool $batch
* Whether to queue this for the batch processor. Defaults to TRUE.
* @param string $queue_id
* The ID of the queue to use in batch processing.
*
* @return bool
* Success boolean
*/
function mailchimp_segment_add_subscriber($list_id, $segment_id, $email, $batch = TRUE, $queue_id = MAILCHIMP_BATCH_QUEUE_CRON) {
$item = array(
'email' => $email,
);
if (!$batch) {
$batch = array($item);
$success = mailchimp_segment_batch_add_subscribers($list_id, $segment_id, $batch);
}
else {
$queue = DrupalQueue::get($queue_id);
$queue->createQueue();
$success = $queue->createItem(array(
'function' => 'mailchimp_segment_batch_add_subscribers',
'list_id' => $list_id,
'arg' => $segment_id,
'item' => $item,
));
if (!$success) {
watchdog('mailchimp', 'A problem occurred adding a MailChimp segment subscribe to the queue. Email: @email List: @list Segment: @segment.', array(
'@email' => $email,
'@list' => $list_id,
'@segment' => $segment_id,
), WATCHDOG_WARNING);
}
}
return $success;
}
/**
* Add a batch of email addresses to a static segment of a list.
*
* @param string $list_id
* ID of a MailChimp list
* @param string $segment_id
* ID of a segment of the MailChimp list
* @param array $batch
* Batch of email addresses to add to the segment (does NOT subscribe new)