-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathclass-newspack-newsletters-mailchimp.php
664 lines (605 loc) · 18.9 KB
/
class-newspack-newsletters-mailchimp.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
<?php
/**
* Service Provider: Mailchimp Implementation
*
* @package Newspack
*/
defined( 'ABSPATH' ) || exit;
use \DrewM\MailChimp\MailChimp;
/**
* Main Newspack Newsletters Class.
*/
final class Newspack_Newsletters_Mailchimp extends \Newspack_Newsletters_Service_Provider {
/**
* Class constructor.
*/
public function __construct() {
$this->service = 'mailchimp';
$this->controller = new Newspack_Newsletters_Mailchimp_Controller( $this );
add_action( 'save_post_' . Newspack_Newsletters::NEWSPACK_NEWSLETTERS_CPT, [ $this, 'save' ], 10, 3 );
add_action( 'transition_post_status', [ $this, 'send' ], 10, 3 );
add_action( 'wp_trash_post', [ $this, 'trash' ], 10, 1 );
add_filter( 'newspack_newsletters_process_link', [ $this, 'process_link' ], 10, 2 );
parent::__construct( $this );
}
/**
* Get API credentials for service provider.
*
* @return Object Stored API credentials for the service provider.
*/
public function api_credentials() {
return [
'api_key' => get_option( 'newspack_newsletters_mailchimp_api_key', '' ),
];
}
/**
* Check if provider has all necessary credentials set.
*
* @return Boolean Result.
*/
public function has_api_credentials() {
return ! empty( $this->api_key() );
}
/**
* Get API key for service provider.
*
* @return String Stored API key for the service provider.
*/
public function api_key() {
$credentials = self::api_credentials();
return $credentials['api_key'];
}
/**
* Set the API credentials for the service provider.
*
* @param object $credentials API credentials.
*/
public function set_api_credentials( $credentials ) {
$api_key = $credentials['api_key'];
if ( empty( $api_key ) ) {
return new WP_Error(
'newspack_newsletters_invalid_keys',
__( 'Please input a Mailchimp API key.', 'newspack-newsletters' )
);
}
try {
$mc = new Mailchimp( $api_key );
$ping = $mc->get( 'ping' );
} catch ( Exception $e ) {
$ping = null;
}
return $ping ?
update_option( 'newspack_newsletters_mailchimp_api_key', $api_key ) :
new WP_Error(
'newspack_newsletters_invalid_keys',
__( 'Please input a valid Mailchimp API key.', 'newspack-newsletters' )
);
}
/**
* Set list for a campaign.
*
* @param string $post_id Campaign Id.
* @param string $list_id ID of the list.
* @return object|WP_Error API API Response or error.
*/
public function list( $post_id, $list_id ) {
$mc_campaign_id = get_post_meta( $post_id, 'mc_campaign_id', true );
if ( ! $mc_campaign_id ) {
return new WP_Error(
'newspack_newsletters_no_campaign_id',
__( 'Mailchimp campaign ID not found.', 'newspack-newsletters' )
);
}
try {
$mc = new Mailchimp( $this->api_key() );
$payload = [
'recipients' => [
'list_id' => $list_id,
],
];
$result = $this->validate(
$mc->patch( "campaigns/$mc_campaign_id", $payload ),
__( 'Error setting Mailchimp list.', 'newspack_newsletters' )
);
$data = $this->retrieve( $post_id );
$data['result'] = $result;
return \rest_ensure_response( $data );
} catch ( Exception $e ) {
return new WP_Error(
'newspack_newsletters_mailchimp_error',
$e->getMessage()
);
}
}
/**
* Retrieve a campaign.
*
* @param integer $post_id Numeric ID of the Newsletter post.
* @return object|WP_Error API Response or error.
*/
public function retrieve( $post_id ) {
if ( ! $this->has_api_credentials() ) {
return [];
}
$transient = sprintf( 'newspack_newsletters_error_%s_%s', $post_id, get_current_user_id() );
$persisted_error = get_transient( $transient );
if ( $persisted_error ) {
delete_transient( $transient );
return new WP_Error(
'newspack_newsletters_mailchimp_error',
$persisted_error
);
}
try {
$mc_campaign_id = get_post_meta( $post_id, 'mc_campaign_id', true );
if ( ! $mc_campaign_id ) {
return new WP_Error(
'newspack_newsletters_mailchimp_error',
__( 'No Mailchimp campaign ID found for this Newsletter', 'newspack-newsletter' )
);
}
$mc = new Mailchimp( $this->api_key() );
$campaign = $this->validate(
$mc->get( "campaigns/$mc_campaign_id" ),
__( 'Error retrieving Mailchimp campaign.', 'newspack_newsletters' )
);
$list_id = $campaign && isset( $campaign['recipients']['list_id'] ) ? $campaign['recipients']['list_id'] : null;
$interest_categories = $list_id ? $this->validate(
$mc->get( "lists/$list_id/interest-categories" ),
__( 'Error retrieving Mailchimp groups.', 'newspack_newsletters' )
) : null;
if ( $interest_categories && count( $interest_categories['categories'] ) ) {
foreach ( $interest_categories['categories'] as &$category ) {
$category_id = $category['id'];
$category['interests'] = $this->validate(
$mc->get( "lists/$list_id/interest-categories/$category_id/interests" ),
__( 'Error retrieving Mailchimp groups.', 'newspack_newsletters' )
);
}
}
$newspack_newsletters_use_mailchimp_tags = get_option( 'newspack_newsletters_use_mailchimp_tags', false );
$tags = [];
if ( $list_id && $newspack_newsletters_use_mailchimp_tags ) {
$tags_response = $this->validate(
$mc->get( "lists/$list_id/segments?count=1000", [], 20 ),
__( 'Error retrieving Mailchimp tags.', 'newspack_newsletters' )
);
$tags = $tags_response['segments'];
}
return [
'lists' => $this->validate(
$mc->get(
'lists',
[
'count' => 1000,
]
),
__( 'Error retrieving Mailchimp lists.', 'newspack_newsletters' )
),
'campaign' => $campaign,
'campaign_id' => $mc_campaign_id,
'interest_categories' => $interest_categories,
'tags' => $tags,
];
} catch ( Exception $e ) {
return new WP_Error(
'newspack_newsletters_mailchimp_error',
$e->getMessage()
);
}
}
/**
* Set sender data.
*
* @param string $post_id Numeric ID of the campaign.
* @param string $from_name Sender name.
* @param string $reply_to Reply to email address.
* @return object|WP_Error API Response or error.
*/
public function sender( $post_id, $from_name, $reply_to ) {
$mc_campaign_id = get_post_meta( $post_id, 'mc_campaign_id', true );
if ( ! $mc_campaign_id ) {
return new WP_Error(
'newspack_newsletters_no_campaign_id',
__( 'Mailchimp campaign ID not found.', 'newspack-newsletters' )
);
}
try {
$mc = new Mailchimp( $this->api_key() );
$result = $this->validate(
$mc->get( 'verified-domains' ),
__( 'Error retrieving verified domains from Mailchimp.', 'newspack-newsletters' )
);
$verified_domains = array_filter(
array_map(
function( $domain ) {
return $domain['verified'] ? strtolower( trim( $domain['domain'] ) ) : null;
},
$result['domains']
),
function( $domain ) {
return ! empty( $domain );
}
);
$explode = explode( '@', $reply_to );
$domain = strtolower( trim( array_pop( $explode ) ) );
if ( ! in_array( $domain, $verified_domains ) ) {
return new WP_Error(
'newspack_newsletters_unverified_sender_domain',
sprintf(
// Translators: explanation that current domain is not verified, list of verified options.
__( '%1$s is not a verified domain. Verified domains for the linked Mailchimp account are: %2$s.', 'newspack-newsletters' ),
$domain,
implode( ', ', $verified_domains )
)
);
}
$settings = [];
if ( $from_name ) {
$settings['from_name'] = $from_name;
}
if ( $reply_to ) {
$settings['reply_to'] = $reply_to;
}
$payload = [
'settings' => $settings,
];
$result = $this->validate(
$mc->patch( "campaigns/$mc_campaign_id", $payload ),
__( 'Error setting sender name and email.', 'newspack_newsletters' )
);
$data = $this->retrieve( $post_id );
$data['result'] = $result;
return \rest_ensure_response( $data );
} catch ( Exception $e ) {
return new WP_Error(
'newspack_newsletters_mailchimp_error',
$e->getMessage()
);
}
}
/**
* Send test email or emails.
*
* @param integer $post_id Numeric ID of the Newsletter post.
* @param array $emails Array of email addresses to send to.
* @return object|WP_Error API Response or error.
*/
public function test( $post_id, $emails ) {
$mc_campaign_id = get_post_meta( $post_id, 'mc_campaign_id', true );
if ( ! $mc_campaign_id ) {
return new WP_Error(
'newspack_newsletters_no_campaign_id',
__( 'Mailchimp campaign ID not found.', 'newspack-newsletters' )
);
}
try {
$mc = new Mailchimp( $this->api_key() );
$payload = [
'test_emails' => $emails,
'send_type' => 'html',
];
$result = $this->validate(
$mc->post(
"campaigns/$mc_campaign_id/actions/test",
$payload,
60
),
__( 'Error sending test email.', 'newspack_newsletters' )
);
$data = $this->retrieve( $post_id );
$data['result'] = $result;
$data['message'] = sprintf(
// translators: Message after successful test email.
__( 'Mailchimp test sent successfully to %s.', 'newspack-newsletters' ),
implode( ', ', $emails )
);
return \rest_ensure_response( $data );
} catch ( Exception $e ) {
return new WP_Error(
'newspack_newsletters_mailchimp_error',
$e->getMessage()
);
}
}
/**
* Synchronize post with corresponding ESP campaign.
*
* @param WP_POST $post Post to synchronize.
* @return object|null API Response or error.
*/
public function sync( $post ) {
$api_key = $this->api_key();
if ( ! $api_key ) {
return new WP_Error(
'newspack_newsletters_incorrect_post_type',
__( 'No Mailchimp API key available.', 'newspack-newsletters' )
);
}
try {
$mc = new Mailchimp( $api_key );
$payload = [
'type' => 'regular',
'content_type' => 'template',
'settings' => [
'subject_line' => $post->post_title,
'title' => $post->post_title,
],
];
$mc_campaign_id = get_post_meta( $post->ID, 'mc_campaign_id', true );
if ( $mc_campaign_id ) {
$campaign_result = $this->validate(
$mc->patch( "campaigns/$mc_campaign_id", $payload ),
__( 'Error updating campaign title.', 'newspack_newsletters' )
);
} else {
$campaign_result = $this->validate(
$mc->post( 'campaigns', $payload ),
__( 'Error setting campaign title.', 'newspack_newsletters' )
);
$mc_campaign_id = $campaign_result['id'];
update_post_meta( $post->ID, 'mc_campaign_id', $mc_campaign_id );
}
// Prevent updating content of a sent campaign.
if ( in_array( $campaign_result['status'], [ 'sent', 'sending' ] ) ) {
return;
}
$renderer = new Newspack_Newsletters_Renderer();
$content_payload = [
'html' => $renderer->render_html_email( $post ),
];
$content_result = $this->validate(
$mc->put( "campaigns/$mc_campaign_id/content", $content_payload ),
__( 'Error updating campaign content.', 'newspack_newsletters' )
);
return [
'campaign_result' => $campaign_result,
'content_result' => $content_result,
];
} catch ( Exception $e ) {
$transient = sprintf( 'newspack_newsletters_error_%s_%s', $post->ID, get_current_user_id() );
set_transient( $transient, $e->getMessage(), 45 );
return;
}
}
/**
* Update ESP campaign after post save.
*
* @param string $post_id Numeric ID of the campaign.
* @param WP_Post $post The complete post object.
* @param boolean $update Whether this is an existing post being updated or not.
*/
public function save( $post_id, $post, $update ) {
$status = get_post_status( $post_id );
if ( 'trash' === $status ) {
return;
}
$this->sync( $post );
}
/**
* Send a campaign.
*
* @param string $new_status New status of the post.
* @param string $old_status Old status of the post.
* @param WP_POST $post Post to send.
*/
public function send( $new_status, $old_status, $post ) {
$post_id = $post->ID;
// Only run if the current service provider is Mailchimp.
if ( 'mailchimp' !== get_option( 'newspack_newsletters_service_provider', false ) ) {
return;
}
if ( ! Newspack_Newsletters::validate_newsletter_id( $post_id ) ) {
return new WP_Error(
'newspack_newsletters_incorrect_post_type',
__( 'Post is not a Newsletter.', 'newspack-newsletters' )
);
}
if ( 'publish' === $new_status && 'publish' !== $old_status ) {
try {
$sync_result = $this->sync( $post );
if ( is_wp_error( $sync_result ) ) {
return $sync_result;
}
$mc_campaign_id = get_post_meta( $post_id, 'mc_campaign_id', true );
if ( ! $mc_campaign_id ) {
return new WP_Error(
'newspack_newsletters_no_campaign_id',
__( 'Mailchimp campaign ID not found.', 'newspack-newsletters' )
);
}
$mc = new Mailchimp( $this->api_key() );
$payload = [
'send_type' => 'html',
];
$result = $this->validate(
$mc->post( "campaigns/$mc_campaign_id/actions/send", $payload ),
__( 'Error sending campaign.', 'newspack_newsletters' )
);
} catch ( Exception $e ) {
$transient = sprintf( 'newspack_newsletters_error_%s_%s', $post->ID, get_current_user_id() );
set_transient( $transient, $e->getMessage(), 45 );
return;
}
}
}
/**
* After Newsletter post is deleted, clean up by deleting corresponding ESP campaign.
*
* @param string $post_id Numeric ID of the campaign.
*/
public function trash( $post_id ) {
if ( Newspack_Newsletters::NEWSPACK_NEWSLETTERS_CPT !== get_post_type( $post_id ) ) {
return;
}
$mc_campaign_id = get_post_meta( $post_id, 'mc_campaign_id', true );
if ( ! $mc_campaign_id ) {
return;
}
$api_key = $this->api_key();
if ( ! $api_key ) {
return;
}
try {
$mc = new Mailchimp( $api_key );
$campaign = $mc->get( "campaigns/$mc_campaign_id" );
if ( $campaign ) {
$status = $campaign['status'];
if ( ! in_array( $status, [ 'sent', 'sending' ] ) ) {
$result = $mc->delete( "campaigns/$mc_campaign_id" );
delete_post_meta( $post_id, 'mc_campaign_id', $mc_campaign_id );
}
}
} catch ( Exception $e ) {
return; // Fail silently.
}
}
/**
* Set Mailchimp Audience segments for a Campaign.
*
* @param string $post_id Numeric ID of the post.
* @param string $compound_interest_id ID of the interest, including field.
* @param number[] $tag_ids List of tag IDs.
* @return object|WP_Error API API Response or error.
*/
public function audience_segments( $post_id, $compound_interest_id, $tag_ids ) {
if ( $compound_interest_id ) {
$exploded = explode( ':', $compound_interest_id );
$field = count( $exploded ) ? $exploded[0] : null;
$interest_id = count( $exploded ) > 1 ? $exploded[1] : null;
$is_unsetting_interest = 'no_interests' === $compound_interest_id;
if ( ! $is_unsetting_interest && ( ! $field || ! $interest_id ) ) {
return new WP_Error(
'newspack_newsletters_invalid_mailchimp_interest',
__( 'Invalid Mailchimp Interest.', 'newspack-newsletters' )
);
}
}
$mc_campaign_id = get_post_meta( $post_id, 'mc_campaign_id', true );
if ( ! $mc_campaign_id ) {
return new WP_Error(
'newspack_newsletters_no_campaign_id',
__( 'Mailchimp campaign ID not found.', 'newspack-newsletters' )
);
}
try {
$mc = new Mailchimp( $this->api_key() );
$campaign = $this->validate(
$mc->get( "campaigns/$mc_campaign_id" ),
__( 'Error retrieving Mailchimp campaign.', 'newspack_newsletters' )
);
$list_id = isset( $campaign, $campaign['recipients'], $campaign['recipients']['list_id'] ) ? $campaign['recipients']['list_id'] : null;
if ( ! $list_id ) {
return new WP_Error(
'newspack_newsletters_no_campaign_id',
__( 'Mailchimp list ID not found.', 'newspack-newsletters' )
);
}
$has_interest = $compound_interest_id && ! $is_unsetting_interest;
$segment_opts = (object) [];
if ( $has_interest || $tag_ids ) {
$segment_opts = [
'match' => 'all',
'conditions' => [],
];
if ( $has_interest ) {
$segment_opts['conditions'][] = [
'condition_type' => 'Interests',
'field' => $field,
'op' => 'interestcontains',
'value' => [
$interest_id,
],
];
}
if ( $tag_ids ) {
foreach ( $tag_ids as $tag_id ) {
$segment_opts['conditions'][] = [
'condition_type' => 'StaticSegment',
'field' => 'static_segment',
'op' => 'static_is',
'value' => $tag_id,
];
}
}
}
$payload = [
'recipients' => [
'list_id' => $list_id,
'segment_opts' => $segment_opts,
],
];
$result = $this->validate(
$mc->patch( "campaigns/$mc_campaign_id", $payload ),
__( 'Error updating Mailchimp segments.', 'newspack_newsletters' )
);
$data = $this->retrieve( $post_id );
$data['result'] = $result;
return \rest_ensure_response( $data );
} catch ( Exception $e ) {
return new WP_Error(
'newspack_newsletters_mailchimp_error',
$e->getMessage()
);
}
}
/**
* Throw an Exception if Mailchimp response indicates an error.
*
* @param Object $result Result of the Mailchimp operation.
* @param String $preferred_error Preset error to use instead of Mailchimp errors.
* @throws Exception Error message.
* @return The results of the API call.
*/
public function validate( $result, $preferred_error = null ) {
if ( ! $result ) {
if ( $preferred_error ) {
throw new Exception( $preferred_error );
} else {
throw new Exception( __( 'A Mailchimp error has occurred.', 'newspack-newsletters' ) );
}
}
if ( ! empty( $result['status'] ) && in_array( $result['status'], [ 400, 404 ] ) ) {
if ( $preferred_error && ! Newspack_Newsletters::debug_mode() ) {
if ( ! empty( $result['detail'] ) ) {
$preferred_error .= ' ' . $result['detail'];
}
throw new Exception( $preferred_error );
}
$messages = [];
if ( ! empty( $result['errors'] ) ) {
foreach ( $result['errors'] as $error ) {
if ( ! empty( $error['message'] ) ) {
$messages[] = $error['message'];
}
}
}
if ( ! count( $messages ) && ! empty( $result['detail'] ) ) {
$messages[] = $result['detail'];
}
if ( ! count( $messages ) ) {
$message[] = __( 'A Mailchimp error has occurred.', 'newspack-newsletters' );
}
throw new Exception( implode( ' ', $messages ) );
}
return $result;
}
/**
* Special handling for link hrefs containing Mailchimp merge fields.
*
* @param String $processed The processed link, with utm_medium parameter added.
* @param String $original The original, unprocessed link.
* @return The link to use.
*/
public function process_link( $processed, $original ) {
// Match Mailchimp Merge Fields.
if ( preg_match( '/\*\|([A-Z_0-9:]+)\|\*/', $original ) ) {
// Check if http:// was prepended.
if ( 0 === strpos( $original, 'http://*|' ) ) {
$original = substr( $original, 7 );
}
return $original;
}
return $processed;
}
}