forked from strangerstudios/pmpro-recurring-emails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpmpro-recurring-emails.php
368 lines (307 loc) · 13.7 KB
/
pmpro-recurring-emails.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
<?php
/*
Plugin Name: Paid Memberships Pro - Recurring Emails Add On
Plugin URI: http://www.paidmembershipspro.com/wp/pmpro-recurring-emails/
Description: Send email message(s) X days before a recurring payment is scheduled, to warn/remind members.
Version: 0.5.5
Author: Stranger Studios, Thomas Sjolshagen <[email protected]>
Author URI: http://www.strangerstudios.com
*/
/*
We want to send a reminder to email to members N days before their membership renews.
This plugin is meant to be used with recurring membership levels in PMPro. Normally
an email is sent when the recurring payment goes through. We want to send an extra
email N days before this.
The email template, # of messages & days before sending can be configured
w/the pmpro_upcoming_recurring_payment_reminder filter.
*/
//run our cron at the same time as the expiration warning emails
add_action( "pmpro_cron_expiration_warnings", "pmpror_recurring_emails", 30 );
/**
* Manually trigger the process (test)
*/
function pmpror_init_test() {
if ( ! empty( $_REQUEST['pmpror_test'] ) && current_user_can( 'manage_options' ) ) {
// Do NOT send the email message(s)!
add_filter( 'pmprorm_send_reminder_to_user', '__return_false' );
// Process recurring email(s)
pmpror_recurring_emails();
// Reset send functionality
remove_filter( 'pmprorm_send_reminder_to_user', '__return_false' );
echo '<p>';
esc_html_e( 'Finished test. Check your PHP error log for details.', 'pmpro-recurring-emails' );
echo '</p>';
exit;
}
}
add_action( 'init', 'pmpror_init_test' );
/**
* Generate and send reminder(s) of upcoming payment event to members w/recurring membership subscription plans
*
* Use pmpro_upcoming_recurring_payment_reminder filter to set array of days (key) and
* template name (value) (<template_name>.html) to use when sending reminder.
*
* Use pmprorm_send_reminder_to_user filter to disable sending notice to all/any individual user(s)
*/
function pmpror_recurring_emails() {
global $wpdb;
//clean up errors in the memberships_users table that could cause problems
if( function_exists( 'pmpro_cleanup_memberships_users_table' ) ) {
pmpro_cleanup_memberships_users_table();
}
//get todays date for later calculations
$today = date_i18n( "Y-m-d", current_time( "timestamp" ) );
/**
* Filter will set how many days before you want to send, and the template to use
*
* @filter pmpro_upcoming_recurring_payment_reminder
*
* @param array $reminders key = # of days before payment will be charged (7 => 'membership_recurring')
* value = name of template to use w/o extension (membership_recurring.html)
*/
$emails = apply_filters( 'pmpro_upcoming_recurring_payment_reminder', array(
7 => 'membership_recurring'
) );
ksort( $emails, SORT_NUMERIC );
//array to store ids of folks we sent emails to so we don't email them twice
$sent_emails = array();
foreach ( $emails as $days => $template ) {
$recurring_soon = array();
//look for memberships that are going to renew within a configurable amount of time (1 week by default), but we haven't emailed them yet about it.
$sqlQuery = $wpdb->prepare( "
SELECT DISTINCT mo.user_id
FROM $wpdb->pmpro_membership_orders mo
LEFT JOIN $wpdb->pmpro_memberships_users mu -- to check for recurring
ON mu.user_id = mo.user_id
AND mu.membership_id = mo.membership_id
LEFT JOIN $wpdb->usermeta um -- to check if we've already emailed
ON um.user_id = mo.user_id
AND um.meta_key = '%s'
WHERE mo.timestamp = ( SELECT Max(mo2.timestamp) -- make sure it's the latest order
FROM $wpdb->pmpro_membership_orders mo2
WHERE mo2.user_id = mo.user_id
AND status = 'success' )
AND mo.status = 'success' -- only successful orders
AND mo.timestamp BETWEEN -- recurring soon
CASE mu.cycle_period
WHEN 'Day' THEN ('%s' - INTERVAL mu.cycle_number DAY)
WHEN 'Week' THEN ('%s' - INTERVAL mu.cycle_number WEEK)
WHEN 'Month' THEN ('%s' - INTERVAL mu.cycle_number MONTH)
WHEN 'Year' THEN ('%s' - INTERVAL mu.cycle_number YEAR)
END
AND
CASE mu.cycle_period
WHEN 'Day' THEN ('%s' - INTERVAL mu.cycle_number DAY + INTERVAL %d DAY)
WHEN 'Week' THEN ('%s' - INTERVAL mu.cycle_number WEEK + INTERVAL %d DAY)
WHEN 'Month' THEN ('%s' - INTERVAL mu.cycle_number MONTH + INTERVAL %d DAY)
WHEN 'Year' THEN ('%s' - INTERVAL mu.cycle_number YEAR + INTERVAL %d DAY)
END
AND (um.meta_value <= '%s' OR um.meta_value IS NULL) -- check if we've already emailed
AND (mu.enddate IS NULL OR mu.enddate = '0000-00-00 00:00:00') -- no enddate
AND mu.cycle_number > 0 -- recurring
AND mu.cycle_period IS NOT NULL -- recurring
AND mu.status = 'active' -- active subs only
",
"pmpro_recurring_notice_{$days}", // for meta_key to lookup
"{$today} 00:00:00", // for Day w/date
"{$today} 00:00:00", // for Week w/date
"{$today} 00:00:00", // for Month w/date
"{$today} 00:00:00", // for Year w/date
"{$today} 23:59:59", // for Day w/date & interval
$days, // for Day w/date & interval
"{$today} 23:59:59", // for Week w/date & interval
$days, // for Week w/date & interval
"{$today} 23:59:59", // for Month w/date & interval
$days, // for Month w/date & interval
"{$today} 23:59:59", // for Year w/date & interval
$days, // for Year w/date & interval
"{$today} 00:00:00" // for meta_value to lookup
);
if ( WP_DEBUG ) {
error_log( "SQL used to fetch user list:" );
error_log( $sqlQuery );
}
$recurring_soon = $wpdb->get_results( $sqlQuery );
if ( is_wp_error( $recurring_soon ) ) {
if ( WP_DEBUG ) {
error_log( "Error while searching for users with upcoming recurring payments: " . $recurring_soon->print_error() );
}
return;
}
if ( WP_DEBUG ) {
error_log( "Found {$wpdb->num_rows} records..." );
}
foreach ( $recurring_soon as $e ) {
if ( ! in_array( $e->user_id, $sent_emails ) ) {
if ( WP_DEBUG ) {
error_log( "Preparing email to send for {$e->user_id}" );
}
//send an email
$pmproemail = new PMProEmail();
$euser = get_userdata( $e->user_id );
// Make sure we have a user.
if ( empty( $euser ) ) {
continue;
}
//make sure we have the current membership level data
$membership_level = pmpro_getMembershipLevelForUser( $euser->ID );
//some standard fields
$pmproemail->email = $euser->user_email;
$pmproemail->subject = sprintf( __( "Your membership at %s will renew soon", "pmpro" ), get_option( "blogname" ) );
$pmproemail->template = $template;
$pmproemail->data = array(
"subject" => $pmproemail->subject,
"name" => $euser->display_name,
"user_login" => $euser->user_login,
"sitename" => get_option( "blogname" ),
"membership_id" => $membership_level->id,
"membership_level_name" => $membership_level->name,
"membership_cost" => pmpro_getLevelCost( $membership_level ),
"billing_amount" => pmpro_formatPrice( $euser->membership_level->billing_amount ),
"siteemail" => pmpro_getOption( "from_email" ),
"login_link" => wp_login_url(),
"enddate" => date( get_option( 'date_format' ), $membership_level->enddate ),
"display_name" => $euser->display_name,
"user_email" => $euser->user_email,
"cancel_link" => wp_login_url( pmpro_url( "cancel" ) )
);
//get last order
$lastorder = new MemberOrder();
$lastorder->getLastMemberOrder( $euser->ID );
//figure out billing info
if ( ! empty( $lastorder->id ) ) {
//set renewal date
$pmproemail->data['renewaldate'] = date( get_option( "date_format" ), pmpro_next_payment( $euser->ID ) );
//update billing info
$billinginfo = "";
//get card type and last4
if ( ! empty( $lastorder->cardtype ) && ! empty( $lastorder->accountnumber ) ) {
$billinginfo .= $lastorder->cardtype . ": " . $lastorder->accountnumber . "<br />";
if ( ! empty( $lastorder->expirationmonth ) && ! empty( $lastorder->expirationyear ) ) {
$billinginfo .= "Expires: " . $lastorder->expirationmonth . "/" . $lastorder->expirationyear . "<br />";
//check if expiring soon
$now = current_time( "timestamp" );
$expires = strtotime( $lastorder->expirationyear . "-" . $lastorder->expirationmonth . "-01" );
$daysleft = ( $expires - $now ) * DAY_IN_SECONDS;
if ( $daysleft < 60 ) {
$billinginfo .= "Please make sure your billing information is up to date.";
}
}
} elseif ( ! empty( $lastorder->payment_type ) ) {
$billinginfo .= "Payment Type: " . $lastorder->payment_type;
}
if ( ! empty( $billinginfo ) ) {
$pmproemail->data['billinginfo'] = "<p>" . $billinginfo . "</p>";
} else {
$pmproemail->data['billinginfo'] = "";
}
//set body
$pmproemail->body = pmpro_loadTemplate( $template, 'local', 'emails', 'html' );
/**
* @filter pmprorm_send_reminder_to_user
*
* @param boolean $send_mail - Whether to send mail or not (true by default)
* @param WP_User $user - User object being processed
* @param MembershipOrder $lastorder - order object for previous order saved
*/
$send_emails = apply_filters( 'pmprorm_send_reminder_to_user', true, $euser, $lastorder );
if ( true === $send_emails ) {
//send the email
$pmproemail->sendEmail();
//notify script
if ( WP_DEBUG ) {
error_log( sprintf( __( "Membership renewing email sent to %s.<br />", "pmpro" ), $euser->user_email ) );
}
//remember so we don't send twice
$sent_emails[] = $euser->ID;
} else {
if ( WP_DEBUG ) {
error_log( "PMProRE - What we may have sent: " . print_r( $pmproemail, true ) );
$sent_emails[] = $euser->ID;
}
}
} else {
//shouldn't get here, but if no order found, just continue
if ( WP_DEBUG ) {
error_log( sprintf( __( "Couldn't find the last order for %s.", "pmpro" ), $euser->user_email ) );
}
}
}
//update user meta so we don't email them again
foreach ( $emails as $d => $t ) {
// update the meta value/key if we're looking at a reminder/template to be sent at or before the one being sent
if ( true === $send_emails && intval( $d ) >= intval( $days ) ) {
update_user_meta(
$e->user_id,
"pmpro_recurring_notice_{$d}",
date( "Y-m-d 00:00:00", strtotime( "+" . ( intval( $d ) + 1 ) . " days", current_time( 'timestamp' ) ) )
);
} else {
if ( WP_DEBUG ) {
error_log( sprintf( "Would have updated metadata for %d: %s = %s ", $e->user_id, "pmpro_recurring_notice_{$d}", date( "Y-m-d 00:00:00", strtotime( "+" . ( intval( $d ) + 1 ) . " days", current_time( 'timestamp' ) ) ) ) );
}
}
} // foreach sent emails
if ( WP_DEBUG ) {
error_log( "Sent emails: " . print_r( $sent_emails, true ) );
}
} // foreach (users to process)
} // foreach (to-send email list)
}
/**
* Add message template to the Email templates add-on (if installed).
*
* @param $templates - The previously defined template array
*
* @return mixed - (possibly) updated template array
*
*/
function pmprore_add_to_templates( $templates ) {
// PMPro Email Templates may be active without PMPro active.
if ( ! function_exists( 'pmpro_loadTemplate' ) ) {
return $templates;
}
$re_emails = apply_filters( 'pmpro_upcoming_recurring_payment_reminder', array(
7 => 'membership_recurring'
) );
$site = get_option( 'blogname' );
foreach ( $re_emails as $days => $templ ) {
$body = pmpro_loadTemplate( $templ, 'local', 'emails', 'html' );
$templates["{$templ}"] = array(
'subject' => __( "Happening soon: The recurring payment for your membership at {$site}", "pmprore" ),
'description' => __( "Membership level recurring payment message for {$site}", "pmprore" ),
'body' => $body,
);
}
return $templates;
}
add_filter( 'pmproet_templates', 'pmprore_add_to_templates', 10, 1 );
/**
* Filter hook for the included upcoming payment warning message
*
* @param array $templates
* @param string $page_name
* @param string $type
* @param string $where
* @param string $ext
*
* @return array -- Path to the plugin specific template file
*/
function pmprore_add_email_template( $templates, $page_name, $type = 'emails', $where = 'local', $ext = 'html' ) {
$templates[] = plugin_dir_path( __FILE__ ) . "emails/membership_recurring.html";
return $templates;
}
add_filter( 'pmpro_emails_custom_template_path', 'pmprore_add_email_template', 10, 5 );
/*
Function to add links to the plugin row meta
*/
function pmpro_recurring_emails_plugin_row_meta( $links, $file ) {
if ( strpos( $file, 'pmpro-recurring-emails.php' ) !== false ) {
$new_links = array(
'<a href="' . esc_url( 'http://paidmembershipspro.com/support/' ) . '" title="' . esc_attr( __( 'Visit Customer Support Forum', 'pmpro' ) ) . '">' . __( 'Support', 'pmpro' ) . '</a>',
);
$links = array_merge( $links, $new_links );
}
return $links;
}
add_filter( 'plugin_row_meta', 'pmpro_recurring_emails_plugin_row_meta', 10, 2 );