-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclass-mailchimp-form-submission.php
More file actions
597 lines (531 loc) · 19.7 KB
/
class-mailchimp-form-submission.php
File metadata and controls
597 lines (531 loc) · 19.7 KB
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
<?php
/**
* Class responsible for handling the form submission for the Mailchimp block.
*
* @package Mailchimp
*/
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class Mailchimp_Form_Submission
*
* @since 1.8.0
*/
class Mailchimp_Form_Submission {
/**
* Initialize the class.
*/
public function init() {
// TODO: Update this to use ajax handler hook instead of init.
add_action( 'init', array( $this, 'request_handler' ) );
}
/**
* Request handler
*
* @return void
*/
public function request_handler() {
// Check if we have a request to handle.
if ( ! isset( $_POST['mcsf_action'] ) ) {
return;
}
// Check for correct action.
if ( 'mc_submit_signup_form' !== sanitize_text_field( wp_unslash( $_POST['mcsf_action'] ) ) ) {
return;
}
// Validate nonce.
if (
! isset( $_POST['_mc_submit_signup_form_nonce'] ) ||
! wp_verify_nonce( sanitize_key( $_POST['_mc_submit_signup_form_nonce'] ), 'mc_submit_signup_form' )
) {
wp_die( 'Cheatin’ huh?' );
}
// Handle form submission.
$response = $this->handle_form_submission();
$submit_type = isset( $_POST['mc_submit_type'] ) ? sanitize_text_field( wp_unslash( $_POST['mc_submit_type'] ) ) : '';
// If we have an error, then show it.
if ( is_wp_error( $response ) ) {
$error = $response->get_error_message();
mailchimp_sf_global_msg( '<strong class="mc_error_msg">' . $error . '</strong>' );
} else {
mailchimp_sf_global_msg( '<strong class="mc_success_msg">' . esc_html( $response ) . '</strong>' );
}
// Do a different action for html vs. js
switch ( $submit_type ) {
case 'html':
/* This gets set elsewhere! */
break;
case 'js':
if ( ! headers_sent() ) { // just in case...
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT', true, 200 );
}
// TODO: Refactor this to use JSON response instead of setting a global message.
echo wp_kses_post( mailchimp_sf_global_msg() );
exit;
}
}
/**
* Handles the form submission for the Mailchimp form.
*
* @return string|WP_Error Success message or error.
*/
public function handle_form_submission() {
$is_valid = $this->validate_form_submission();
if ( is_wp_error( $is_valid ) || ! $is_valid ) {
if ( is_wp_error( $is_valid ) ) {
return $is_valid;
}
// If the form submission is invalid, return an error.
return new WP_Error( 'mailchimp-invalid-form', esc_html__( 'Invalid form submission.', 'mailchimp' ) );
}
$list_id = get_option( 'mc_list_id' );
$update_existing = get_option( 'mc_update_existing' );
$double_opt_in = get_option( 'mc_double_optin' );
$skip_merge_validation = false;
$merge_fields = get_option( 'mc_merge_vars', array() );
$interest_groups = get_option( 'mc_interest_groups', array() );
// phpcs:disable WordPress.Security.NonceVerification.Missing -- Nonce check is already done in the request_handler() function.
// Check if request from latest block.
if ( isset( $_POST['mailchimp_sf_list_id'] ) ) {
$list_id = isset( $_POST['mailchimp_sf_list_id'] ) ? sanitize_text_field( wp_unslash( $_POST['mailchimp_sf_list_id'] ) ) : '';
$update_existing = isset( $_POST['mailchimp_sf_update_existing_subscribers'] ) ? sanitize_text_field( wp_unslash( $_POST['mailchimp_sf_update_existing_subscribers'] ) ) : '';
$double_opt_in = isset( $_POST['mailchimp_sf_double_opt_in'] ) ? sanitize_text_field( wp_unslash( $_POST['mailchimp_sf_double_opt_in'] ) ) : '';
$skip_merge_validation = isset( $_POST['mailchimp_sf_skip_merge_validation'] ) ? sanitize_text_field( wp_unslash( $_POST['mailchimp_sf_skip_merge_validation'] ) ) : '';
$hash = isset( $_POST['mailchimp_sf_hash'] ) ? sanitize_text_field( wp_unslash( $_POST['mailchimp_sf_hash'] ) ) : '';
$expected = wp_hash(
serialize( // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize
array(
'list_id' => $list_id,
'update_existing' => $update_existing,
'double_opt_in' => $double_opt_in,
'skip_merge_validation' => $skip_merge_validation,
)
)
);
// Bail if the hash is invalid.
if ( ! hash_equals( $expected, $hash ) ) {
return new WP_Error( 'mailchimp-invalid-hash', esc_html__( 'Invalid form submission.', 'mailchimp' ) );
}
$update_existing = 'yes' === $update_existing;
$double_opt_in = 'yes' === $double_opt_in;
$skip_merge_validation = 'yes' === $skip_merge_validation;
$merge_fields = get_option( 'mailchimp_sf_merge_fields_' . $list_id, array() );
$interest_groups = get_option( 'mailchimp_sf_interest_groups_' . $list_id, array() );
}
// Prepare request body
$email = isset( $_POST['mc_mv_EMAIL'] ) ? wp_strip_all_tags( wp_unslash( $_POST['mc_mv_EMAIL'] ) ) : '';
$merge_fields_body = $this->prepare_merge_fields_body( $merge_fields, $skip_merge_validation );
// Catch errors and fail early.
if ( is_wp_error( $merge_fields_body ) ) {
return $merge_fields_body;
}
$interest_groups = ! is_array( $interest_groups ) ? array() : $interest_groups;
$groups = $this->prepare_groups_body( $interest_groups );
// Clear out empty merge fields.
$merge_fields_body = $this->remove_empty_merge_fields( $merge_fields_body );
if ( isset( $_POST['email_type'] ) && in_array( $_POST['email_type'], array( 'text', 'html', 'mobile' ), true ) ) {
$email_type = sanitize_text_field( wp_unslash( $_POST['email_type'] ) );
} else {
$email_type = 'html';
}
// phpcs:enable WordPress.Security.NonceVerification.Missing
$response = $this->subscribe_to_list(
$list_id,
$email,
array(
'email_type' => $email_type,
'merge_fields' => $merge_fields_body,
'interests' => $groups,
'update_existing' => $update_existing,
'double_opt_in' => $double_opt_in,
'skip_merge_validation' => $skip_merge_validation,
)
);
// If we have errors, then show them
if ( is_wp_error( $response ) ) {
return $response;
}
$message = '';
if ( 'subscribed' === $response['status'] ) {
$message = __( 'Success, you\'ve been signed up.', 'mailchimp' );
} else {
$message = __( 'Success, you\'ve been signed up! Please look for our confirmation email.', 'mailchimp' );
}
/**
* Fires after a successful form submission.
*
* @param string $list_id The list ID the user subscribed to.
*/
do_action( 'mailchimp_sf_form_submission_success', $list_id );
// Return success message.
return $message;
}
/**
* Validate phone
*
* @param string $opt_val Option value.
* @param array $data Data.
* @return string|WP_Error Option value or error.
*/
public function validate_phone( $opt_val, $data ) {
if ( empty( $opt_val ) ) {
return '';
}
// Backwards compatibility for old phone format.
if ( is_array( $opt_val ) ) {
$opt_val = implode( '-', $opt_val );
}
$opt_val = trim( $opt_val );
// Validate phone number.
if ( preg_match( '/^\+?[\d\s\-\(\)\.]*$/', $opt_val ) ) {
return $opt_val;
} else {
/* translators: %s: field name */
$message = sprintf( esc_html__( 'Please enter a valid %s.', 'mailchimp' ), esc_html( $data['name'] ) );
return new WP_Error( 'mc_phone_validation', $message );
}
}
/**
* Validate address
*
* @param array $opt_val Option value
* @param array $data Data
* @return mixed
*/
public function validate_address( $opt_val, $data ) {
if ( true === (bool) $data['required'] ) {
if ( empty( $opt_val['addr1'] ) || empty( $opt_val['city'] ) ) {
/* translators: %s: field name */
$message = sprintf( esc_html__( '%s: Please enter a complete address.', 'mailchimp' ), esc_html( $data['name'] ) );
$error = new WP_Error( 'invalid_address_merge', $message );
return $error;
}
} elseif ( empty( $opt_val['addr1'] ) || empty( $opt_val['city'] ) ) {
return false;
}
$merge = new stdClass();
$merge->addr1 = $opt_val['addr1'];
$merge->addr2 = $opt_val['addr2'];
$merge->city = $opt_val['city'];
$merge->state = $opt_val['state'];
$merge->zip = $opt_val['zip'];
$merge->country = $opt_val['country'];
return $merge;
}
/**
* Prepare the merge fields body for the API request.
*
* @param array $merge_fields Merge fields.
* @param bool $skip_merge_validation Skip merge validation.
* @return stdClass|WP_Error
*/
public function prepare_merge_fields_body( $merge_fields, $skip_merge_validation = false ) {
// Loop through our merge fields, and if they're empty, but required, then print an error, and mark as failed
$merge = new stdClass();
foreach ( $merge_fields as $merge_field ) {
$tag = $merge_field['tag'];
$opt = 'mc_mv_' . $tag;
// Skip if the field is not required and not submitted.
if ( ( true !== (bool) $merge_field['required'] && ! isset( $_POST[ $opt ] ) ) || $skip_merge_validation ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce check is already done in the request_handler() function.
continue;
}
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce check is already done in the request_handler() function.
$opt_val = isset( $_POST[ $opt ] ) ? map_deep( stripslashes_deep( $_POST[ $opt ] ), 'sanitize_text_field' ) : '';
switch ( $merge_field['type'] ) {
/**
* US/International Phone validation
*/
case 'phone':
$opt_val = $this->validate_phone( $opt_val, $merge_field );
if ( is_wp_error( $opt_val ) ) {
return $opt_val;
}
break;
/**
* Address validation
*
* - Merge field is address
* - Merge field is an array (address contains multiple <input> elements)
*/
case 'address':
if ( is_array( $opt_val ) ) {
$validate = $this->validate_address( $opt_val, $merge_field );
if ( is_wp_error( $validate ) ) {
return $validate;
}
if ( $validate ) {
$merge->$tag = $validate;
}
}
break;
/**
* Handle generic array values
*
* Not sure what this does or is for
*
* - Merge field is an array, not specifically phone or address
*/
default:
if ( is_array( $opt_val ) ) {
$keys = array_keys( $opt_val );
$val = new stdClass();
foreach ( $keys as $key ) {
$val->$key = $opt_val[ $key ];
}
$opt_val = $val;
}
break;
}
/**
* Required fields
*
* If the field is required and empty, +return an error
*/
if ( true === (bool) $merge_field['required'] && empty( $opt_val ) ) {
/* translators: %s: field name */
$message = sprintf( esc_html__( 'You must fill in %s.', 'mailchimp' ), esc_html( $merge_field['name'] ) );
$error = new WP_Error( 'missing_required_field', $message );
return $error;
} elseif ( 'EMAIL' !== $tag ) {
$merge->$tag = $opt_val;
}
}
return $merge;
}
/**
* Prepare the interest groups body for the API request.
*
* @param array $interest_groups Interest groups.
* @return stdClass
*/
public function prepare_groups_body( $interest_groups ) {
// Bail if we don't have any interest groups
if ( empty( $interest_groups ) ) {
return new stdClass();
}
$groups = $this->set_all_groups_to_false( $interest_groups );
foreach ( $interest_groups as $interest_group ) {
$ig_id = $interest_group['id'];
// phpcs:disable WordPress.Security.NonceVerification.Missing -- Nonce check is already done in the request_handler() function.
if ( isset( $_POST['group'][ $ig_id ] ) && 'hidden' !== $interest_group['type'] ) {
switch ( $interest_group['type'] ) {
case 'dropdown':
case 'radio':
// there can only be one value submitted for radio/dropdowns, so use that at the group id.
if ( isset( $_POST['group'][ $ig_id ] ) && ! empty( $_POST['group'][ $ig_id ] ) ) {
$value = sanitize_text_field( wp_unslash( $_POST['group'][ $ig_id ] ) );
$groups->$value = true;
}
break;
case 'checkboxes':
if ( isset( $_POST['group'][ $ig_id ] ) ) {
$ig_ids = array_map(
'sanitize_text_field',
array_keys(
stripslashes_deep( $_POST['group'][ $ig_id ] ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- ignoring because this is sanitized through array_map above
)
);
foreach ( $ig_ids as $id ) {
$groups->$id = true;
}
}
break;
default:
// Nothing
break;
}
}
// phpcs:enable WordPress.Security.NonceVerification.Missing
}
return $groups;
}
/**
* Set all interest groups to false.
*
* @param array $interest_groups Interest groups.
* @return stdClass
*/
public function set_all_groups_to_false( $interest_groups ) {
$groups = new stdClass();
foreach ( $interest_groups as $interest_group ) {
if ( 'hidden' !== $interest_group['type'] ) {
foreach ( $interest_group['groups'] as $group ) {
$id = $group['id'];
$groups->$id = false;
}
}
}
return $groups;
}
/**
* Get signup form URL for the Mailchimp list.
*
* @param string $list_id The list ID.
* @return string
*/
public function get_signup_form_url( $list_id ) {
$dc = get_option( 'mc_datacenter' );
$user = get_option( 'mc_user' );
$url = 'https://' . $dc . '.list-manage.com/subscribe?u=' . $user['account_id'] . '&id=' . $list_id;
return $url;
}
/**
* Check the status of a subscriber.
*
* @param string $list_id The list ID.
* @param string $email The email address of the subscriber.
* @return string|bool The status of the subscriber or false on error.
*/
public function get_subscriber_status( $list_id, $email ) {
$api = mailchimp_sf_get_api();
if ( ! $api ) {
return false;
}
$endpoint = 'lists/' . $list_id . '/members/' . md5( strtolower( $email ) ) . '?fields=status';
$subscriber = $api->get( $endpoint, null );
if ( is_wp_error( $subscriber ) ) {
return false;
}
return $subscriber['status'];
}
/**
* Subscribe to a list.
*
* @param string $list_id The list ID.
* @param string $email The email address of the subscriber.
* @param array $args Additional arguments for the subscription.
*
* @return WP_Error|array The response from the Mailchimp API or an error.
*/
protected function subscribe_to_list( $list_id, $email, $args ) {
$api = mailchimp_sf_get_api();
// If we don't have an API, then show an error message.
if ( ! $api ) {
$url = $this->get_signup_form_url( $list_id );
$error = wp_kses(
sprintf(
/* translators: 1: email address 2: url */
__(
'We encountered a problem adding %1$s to the list. Please <a href="%2$s">sign up here.</a>',
'mailchimp'
),
esc_html( $email ),
esc_url( $url )
),
[
'a' => [
'href' => [],
],
]
);
return new WP_Error( 'mailchimp-auth-error', $error );
}
$url = 'lists/' . $list_id . '/members/' . md5( strtolower( $email ) );
$status = $this->get_subscriber_status( $list_id, $email );
// If update existing is turned off and the subscriber is not new, error out.
$is_new_subscriber = false === $status;
if ( ! $args['update_existing'] && ! $is_new_subscriber ) {
$msg = esc_html__( 'This email address has already been subscribed to this list.', 'mailchimp' );
return new WP_Error( 'mailchimp-update-existing', $msg );
}
// Add skip merge validation for handle hidden required fields for the form template.
if ( isset( $args['skip_merge_validation'] ) && $args['skip_merge_validation'] ) {
$url .= '?skip_merge_validation=true';
}
// Prepare request body
$request_body = $this->prepare_subscribe_request_body( $email, $status, $args );
$response = $api->post( $url, $request_body, 'PUT', $list_id );
return $response;
}
/**
* Prepare the request body for the Mailchimp API.
*
* @param string $email The email address of the subscriber.
* @param string $status The status of the subscriber (e.g., subscribed, pending).
* @param array $args Additional arguments for the subscription, including:
* - merge_fields (array): Merge fields data.
* - interests (array): Interest groups data.
* - email_type (string): The type of email (e.g., html, text).
* - double_opt_in (bool): Whether to use double opt-in.
* - update_existing (bool): Whether to update existing subscribers.
*
* @return stdClass The prepared request body.
*/
protected function prepare_subscribe_request_body( $email, $status, $args ) {
// Prepare the request body for the Mailchimp API.
$request_body = new stdClass();
$request_body->email_address = $email;
$request_body->email_type = $args['email_type'];
$request_body->merge_fields = $args['merge_fields'];
if ( ! empty( $args['interests'] ) ) {
$request_body->interests = $args['interests'];
}
// Early return for already subscribed users
if ( 'subscribed' === $status ) {
return $request_body;
}
// Subscribe the email immediately unless double opt-in is enabled
// "unsubscribed" and "subscribed" existing emails have been excluded at this stage
// "pending" emails should follow double opt-in rules
$request_body->status = $args['double_opt_in'] ? 'pending' : 'subscribed';
return $request_body;
}
/**
* Remove empty merge fields from the request body.
*
* @param object $merge Merge fields request body.
* @return object The modified merge fields request body.
*/
public function remove_empty_merge_fields( $merge ) {
foreach ( $merge as $k => $v ) {
if ( is_object( $v ) && empty( $v ) ) {
unset( $merge->$k );
} elseif ( ( is_string( $v ) && trim( $v ) === '' ) || is_null( $v ) ) {
unset( $merge->$k );
}
}
return $merge;
}
/**
* Validate the form submission.
* Basic checks for the prevention of spam.
*
* @return bool|WP_Error True if valid, WP_Error if invalid.
*/
protected function validate_form_submission() {
// phpcs:disable WordPress.Security.NonceVerification.Missing -- Nonce check is already done in the request_handler() function.
$spam_message = esc_html__( "We couldn't process your submission as it was flagged as potential spam. Please try again.", 'mailchimp' );
// Make sure the honeypot field is set, but not filled (if it is, then it's a spam).
if ( ! isset( $_POST['mailchimp_sf_alt_email'] ) || ! empty( $_POST['mailchimp_sf_alt_email'] ) ) {
return new WP_Error( 'spam', $spam_message );
}
// Make sure that no-js field is not present (if it is, then it's a spam).
if ( isset( $_POST['mailchimp_sf_no_js'] ) ) {
return new WP_Error( 'spam', $spam_message );
}
// Make sure that user-agent is set and it has reasonable length.
$user_agent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';
if ( strlen( $user_agent ) < 2 ) {
return new WP_Error( 'spam', $spam_message );
}
// Early return if the email is not set
if ( empty( $_POST['mc_mv_EMAIL'] ) ) {
return new WP_Error( 'email_required', esc_html__( 'Please enter your email address.', 'mailchimp' ) );
}
// Check if the email is valid
if ( ! is_email( sanitize_email( wp_unslash( $_POST['mc_mv_EMAIL'] ) ) ) ) {
return new WP_Error( 'invalid_email', esc_html__( 'Please enter a valid email address.', 'mailchimp' ) );
}
/**
* Filter to allow for custom validation of the form submission.
*
* @since 1.8.0
* @param bool $is_valid True if valid, false if invalid, return WP_Error to provide error message.
* @param array $post_data The $_POST data.
*/
return apply_filters( 'mailchimp_sf_form_submission_validation', true, $_POST );
// phpcs:enable WordPress.Security.NonceVerification.Missing
}
}