This repository has been archived by the owner on Mar 7, 2021. It is now read-only.
forked from lakoo/mailchimp-webhooks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmailchimp-webhooks.php
428 lines (298 loc) · 11.4 KB
/
mailchimp-webhooks.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
<?php
require 'config.php';
/**
* Plugin Name: MailChimp WebHooks (mcwh)
* Plugin URI: https://github.com/pommiegranit/mailchimp-webhooks
* Description: Allows WordPress users to be updated with MailChimp subscribe/unsubscribe actions
* Version: 1.0.0
* Author: Chris Knowles
* Author URI: http://premium.wpmudev.org/blog/author/chrisdknowles
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
* Text Domain: mcwh
*/
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
die;
}
function mcwh_init(){
$mcwh_settings = get_option( 'mcwh_settings' );
/* if global option mcwh_settings doesn't exist then create it */
if ( $mcwh_settings == false ) {
add_option( 'mcwh_settings', array('hard_subscribe' => 0, 'hard_unsubscribe' => 0, 'webhook_key' => 'putyourkeyhere', 'keep_log' => 1 ) );
$mcwh_settings = get_option( 'mcwh_settings' );
}
/* hooks for plugin options */
add_action( 'admin_menu', 'mcwh_admin_menu' );
add_action( 'admin_init', 'mcwh_settings_init' );
/* hook for creating webhook endpoints */
add_action( 'init', 'mcwh_endpoint' );
add_action( 'parse_request', 'mcwh_parse_request' );
/* add hooks for showing _newsletter_subscriber value in profile */
add_action( 'show_user_profile', 'mcwh_show_user_profile' );
add_action( 'edit_user_profile', 'mcwh_show_user_profile' );
}
function mcwh_admin_menu() {
add_options_page( 'MailChimp Webhooks', 'MailChimp Webhooks', 'manage_options', 'mailchimp_webhooks', 'mcwh_options_page' );
}
function mcwh_settings_init() {
register_setting( 'mcwh', 'mcwh_settings' , 'mcwh_settings_check' );
add_settings_section(
'mcwh_section',
__( 'Control the behavior associated with MailChimp webhooks', 'mailchimp_webhooks' ),
'mcwh_section_callback',
'mcwh'
);
add_settings_field(
'hard_subscribe',
__( 'Create new user on subscribe?', 'mailchimp_webhooks' ),
'mcwh_hard_subscribe_render',
'mcwh',
'mcwh_section'
);
add_settings_field(
'hard_unsubscribe',
__( 'Delete user on unsubscribe?', 'mailchimp_webhooks' ),
'mcwh_hard_unsubscribe_render',
'mcwh',
'mcwh_section'
);
add_settings_field(
'webhook_key',
__( 'Specify a unique webhook key', 'mailchimp_webhooks' ),
'mcwh_webhook_key_render',
'mcwh',
'mcwh_section'
);
add_settings_field(
'keep_log',
__( 'Write activity to log?', 'mailchimp_webhooks' ),
'mcwh_webhook_log_render',
'mcwh',
'mcwh_section'
);
}
function mcwh_endpoint(){
// access webhook at url such as http://[your site]/mailchimp/webhook
add_rewrite_rule( 'webhook' , 'index.php?webhook=1', 'top' );
add_rewrite_tag( '%webhook%' , '([^&]+)' );
}
function mcwh_parse_request( &$wp )
{
if ( array_key_exists( 'webhook', $wp->query_vars ) ) {
mcwh_action_webhook();
exit();
}
}
function mcwh_action_webhook() {
$mcwh_settings = get_option( 'mcwh_settings' );
mcwh_log('==================[ Incoming Request ]==================');
// mcwh_log('Full _REQUEST dump:\n'.print_r($_REQUEST,true));
if ( empty($_POST) ) {
mcwh_log('No request details found.');
die('No request details found.');
}
if ( !isset($_GET['key']) ){
mcwh_log('FAILED! No security key specified, ignoring request');
} elseif ($_GET['key'] != $mcwh_settings['webhook_key']) {
mcwh_log('FAILED: Security key specified, but not correct');
// mcwh_log("\t".'Wanted: "'.$webhook_key.'", but received "'.$_GET['key'].'"');
} else {
//process the request
mcwh_log('Processing a "'.$_POST['type'].'" request for email address ' . $_POST['data']['email'] . '...');
switch($_POST['type']){
case 'subscribe' : mcwh_subscribe($_POST['data'], $_POST['fired_at']); break;
//case 'unsubscribe': mcwh_unsubscribe($_POST['data']); break;
case 'cleaned' : mcwh_cleaned($_POST['data']); break;
case 'upemail' : mcwh_upemail($_POST['data']); break;
case 'profile' : mcwh_subscribe($_POST['data'], $_POST['fired_at']); break;
default:
mcwh_log('Request type "'.$_POST['type'].'" unknown, ignoring.');
}
}
mcwh_log('Finished processing request.');
}
function mcwh_show_user_profile( $user ) {
$subscribed = get_user_meta( $user->ID, '_newsletter_subscriber', true );
echo '<h3>MailChimp Newsletter</h3>
<table class="form-table">
<tr>
<th><label for="_newsletter_subscriber">Current Subscriber</label></th>
<td>';
echo '<input type="checkbox" name="_newsletter_subscriber" id="_newsletter_subscriber" ';
echo $subscribed ? "checked" : "";
echo ' disabled/><br />
<span class="description">Is this user subscribed to the MailChimp newsletter?</span>
</td>
</tr>
</table>';
}
/*
* initialize the plugin
*/
mcwh_init();
/***********************************************
Helper Functions
***********************************************/
function mcwh_options_page() {
?>
<form action='options.php' method='post'>
<h2>MailChimp Webhooks</h2>
<?php
settings_fields( 'mcwh' );
do_settings_sections( 'mcwh' );
submit_button();
?>
</form>
<?php
}
function mcwh_hard_subscribe_render() {
$mcwh_settings = get_option( 'mcwh_settings' );
?>
<input type="checkbox" name="mcwh_settings[hard_subscribe]" <?php echo $mcwh_settings['hard_subscribe']? 'checked':''; ?> value="1">
<?php
}
function mcwh_hard_unsubscribe_render() {
$mcwh_settings = get_option( 'mcwh_settings' );
?>
<input type="checkbox" name="mcwh_settings[hard_unsubscribe]" <?php echo $mcwh_settings['hard_unsubscribe']? 'checked':''; ?> value="1">
<?php
}
function mcwh_webhook_key_render() {
$mcwh_settings = get_option( 'mcwh_settings' );
?>
<input type='text' name='mcwh_settings[webhook_key]' value='<?php echo $mcwh_settings['webhook_key']; ?>' >
<?php
}
function mcwh_webhook_log_render() {
$mcwh_settings = get_option( 'mcwh_settings' );
?>
<input type='checkbox' name='mcwh_settings[keep_log]' <?php echo $mcwh_settings['keep_log']? 'checked':''; ?> value="1">
<p>Your Webhook URL is: <?php echo get_option('siteurl') . '/index.php?webhook=1&key=' . $mcwh_settings['webhook_key']; ?></p>
<?php
}
function mcwh_section_callback() {
echo __( '<p></p>', 'mailchimp_webhooks' );
echo '<p><a href="' . plugins_url('webhook.log', __FILE__) . '" target="_blank">View the webhook log</a></p>';
}
function mcwh_settings_check($settings){
$new_settings['webhook_key'] = $settings['webhook_key'];
if ( $settings['hard_subscribe'] ) {
$new_settings['hard_subscribe'] = 1;
} else {
$new_settings['hard_subscribe'] = 0;
}
if ( $settings['hard_unsubscribe'] ) {
$new_settings['hard_unsubscribe'] = 1;
} else {
$new_settings['hard_unsubscribe'] = 0;
}
if ( $settings['keep_log'] ) {
$new_settings['keep_log'] = 1;
} else {
$new_settings['keep_log'] = 0;
}
return $new_settings;
}
/* Handles a subscribe notification from MailChimp
* If create new user on subscribe is true then a new user will be created if it doesn't already exist
* User meta _newsletter_subscribe is always set to 1
*/
function mcwh_subscribe($data, $time){
$mcwh_settings = get_option( 'mcwh_settings' );
$user_email = $data['email'];
/* get existing user record */
$thisuser = get_user_by( 'email', $user_email );
/* if new user... */
if ( $thisuser === false )
/* if hard_subscribe then create new user record */
if ( $mcwh_settings['hard_subscribe'] ) {
// $userdata = array(
// 'user_pass' => wp_generate_password( $length=12, $include_standard_special_chars=false ),
// 'user_login' => $data['id']$data['id'],
// 'user_email' => $user_email,
// 'first_name' => $data['merges']['FNAME'],
// 'last_name' => $data['merges']['LNAME'],
// 'role' => 'subscriber'
// );
$user_name = $data['list_id'].$data['id'];
$password = wp_generate_password( $length=12, $include_standard_special_chars=false );
$email = $user_email;
$user_id = wpmu_create_user( $user_name, $password, $email);
if ( !is_wp_error( $user_id ) ) {
mcwh_log( 'SUBSCRIBE: Created new user [ ' . $user_email . ' ]' );
} else {
mcwh_log( 'SUBSCRIBE: FAILED! Problem encountered trying to create new user [ ' . $user_email . ' ]' );
return;
}
} else {
/* if no user found and not creating accounts then exit */
mcwh_log( 'SUBSCRIBE: FAILED! No user found with this email address and hard_(un)subscribe is false' );
return;
} else {
mcwh_log( 'SUBSCRIBE: Existing user found with this email address ' . $user_email );
$user_id = $thisuser->ID;
}
/* update the user meta regardless - if hard_unsubscribe just won't be shown on the user profile */
$common_tags = unserialize(COMMON_TAGS);
$prefix = unserialize(MCWH_LIST_IDS)[$data['list_id']];
foreach ($data['merges'] as $key => $value ){
if ($key == "GROUPINGS" || $key == "INTERESTS") continue;
$insert_key = $prefix.$key;
if ($common_tags[$key]) {
$insert_key = $common_tags[$key];
}
mchw_insert_user_meta($user_id, $insert_key, $value);
}
// add user create dates if not exist
add_user_meta($user_id, "CREATE_DATE", $time, true);
add_user_meta($user_id, $prefix."CREATE_DATE", $time, true);
mcwh_log( 'SUBSCRIBE: ' . ( $subscribed ? 'SUCCESS! User subscribed' : 'FAILED! User already subscribed' ) );
}
/* Handles an unsubscribe notification from MailChimp
* If hard_unsubscribe is true then user will be deleted, otherwise user meta _newsletter_subscribe is set to 0
*/
function mcwh_unsubscribe($data){
$mcwh_settings = get_option( 'mcwh_settings' );
$user_email = $data['email'];
/* get existing user */
$thisuser = get_user_by( 'email', $user_email );
/* if user exists then unsubscribe */
if( $thisuser ) {
/* if hard unsubscribe then delete the user */
if ( $mcwh_settings['hard_unsubscribe'] ) {
/* have to include this file to get access to wp_delete_user function */
require_once(ABSPATH.'wp-admin/includes/user.php' );
wp_delete_user( $thisuser->ID );
mcwh_log( 'UNSUBSCRIBE: SUCCESS! ' . $user_email . ' deleted (hard unsubscribe) ');
} else {
/* soft unsubscribe - just change _newsletter_subscriber meta to 0 */
$unsubscribed = update_user_meta( $thisuser->ID, '_newsletter_subscriber', 0, 1 );
mcwh_log( 'UNSUBSCRIBE: ' . ( $unsubscribed ? 'SUCCESS! User unsubscribed' : 'FAILED: User already unsubscribed' ) );
}
} else {
mcwh_log ( 'UNSUBSCRIBE: FAILED! User with email address ' . $user_email . ' does not exist. Cannot unsubscribe.' );
}
}
function mchw_cleaned($data){
mcwh_log($data['email'] . ' was cleaned from your list!');
}
function mchw_upemail($data){
mcwh_log($data['old_email'] . ' changed their email address to '. $data['new_email']. '!');
}
function mchw_profile($data){
mcwh_log($data['email'] . ' updated their profile!');
}
function mcwh_log($msg){
$mcwh_settings = get_option( 'mcwh_settings' );
if ( $mcwh_settings['keep_log'] ) {
$logfile = plugin_dir_path(__FILE__) . 'webhook.log';
file_put_contents($logfile,date("Y-m-d H:i:s")." | ".$msg."\n",FILE_APPEND);
}
}
function mchw_insert_user_meta( $user_id, $meta_key, $meta_value ){
$notexist = add_user_meta($user_id, $meta_key, $meta_value, true);
if (!$notexist){
update_user_meta($user_id, $meta_key, $meta_value);
}
}