-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy patheme-mailer.php
2998 lines (2855 loc) · 159 KB
/
eme-mailer.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
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
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
function eme_set_wpmail_html_content_type() {
return 'text/html';
}
// for backwards compat, the fromname and email are after the replyto and can be empty
function eme_send_mail( $subject, $body, $receiveremail, $receivername = '', $replytoemail = '', $replytoname = '', $fromemail = '', $fromname = '', $atts_arr = [], $custom_headers = [] ) {
$subject = preg_replace( '/(^\s+|\s+$)/m', '', $subject );
$res = true;
$message = '';
$debugtxt = '';
// nothing to send? Then act as if all is ok
if ( empty( $body ) || empty( $subject ) || empty( $receiveremail ) ) {
return [ $res, $message ];
}
if ( empty( $fromemail ) ) {
$fromemail = $replytoemail;
$fromname = $replytoname;
}
// if forced or fromemail is still empty
if ( get_option( 'eme_mail_force_from' ) || empty( $fromemail ) ) {
[$fromname, $fromemail] = eme_get_default_mailer_info();
}
// now the from should never be empty, so just check reply to again
if ( empty( $replytoemail ) ) {
$replytoemail = $fromemail;
}
if ( empty( $replytoname ) ) {
$replytoname = $fromname;
}
// get all mail options, put them in an array and apply filter
// if you change this array, don't forget to update the doc
$mailoptions = [
'fromMail' => $fromemail,
'fromName' => $fromname,
'toMail' => $receiveremail,
'toName' => $receivername,
'replytoMail' => $replytoemail,
'replytoName' => $replytoname,
'bcc_addresses' => get_option( 'eme_mail_bcc_address', '' ),
'mail_send_method' => get_option( 'eme_mail_send_method' ), // smtp, mail, sendmail, qmail, wp_mail
'send_html' => get_option( 'eme_mail_send_html' ), // true or false
'smtp_host' => get_option( 'eme_smtp_host', 'localhost' ),
'smtp_encryption' => get_option( 'eme_smtp_encryption' ), // none, tls or ssl
'smtp_verify_cert' => get_option( 'eme_smtp_verify_cert' ), // true or false
'smtp_port' => intval(get_option( 'eme_smtp_port', 25 )),
'smtp_auth' => get_option( 'eme_smtp_auth' ), // 0 or 1, false or true
'smtp_username' => get_option( 'eme_smtp_username', '' ),
'smtp_password' => get_option( 'eme_smtp_password', '' ),
'smtp_debug' => get_option( 'eme_smtp_debug' ), // true or false
];
$mailoptions = apply_filters( 'eme_filter_mail_options', $mailoptions );
if ( empty( $mailoptions['smtp_host'] ) ) {
$mailoptions['smtp_host'] = 'localhost';
}
if ( empty( $mailoptions['smtp_port'] ) ) {
$mailoptions['smtp_port'] = 25;
}
$bcc_addresses = preg_split( '/,|;/', $mailoptions['bcc_addresses'] );
// allow either an array of file paths or of attachment ids
$attachment_paths_arr = [];
if ( ! is_array( $atts_arr ) ) {
$atts_arr = [];
}
foreach ( $atts_arr as $attachment ) {
if ( ! empty( $attachment ) ) {
if ( is_numeric( $attachment ) ) {
$file_path = get_attached_file( $attachment );
if ( ! empty( $file_path ) && file_exists( $file_path ) ) {
$attach_name = eme_sanitize_attach_filename(basename($file_path));
if (!empty($attach_name))
$attachment_paths_arr[$attach_name] = $file_path;
}
} elseif ( is_array( $attachment ) ) {
// an array: the first element is the desired attach name, the second the real path of the file to attach
if ( file_exists( $attachment[1] ) ) {
if (eme_is_empty_string($attachment[0])) {
// if no desired name, we base ourselves on the real path but remove some ugly parts
$filename = pathinfo($attachment[1], PATHINFO_FILENAME);
$extension = pathinfo($attachment[1], PATHINFO_EXTENSION);
if (empty($extension))
$extension = "none";
// now remove parts of the file
$filename = preg_replace( '/(member-\d+|booking-\d+)-.*/', '$1', $filename );
$filename = preg_replace( '/.*-(qrcode.*)/', '$1', $filename );
$attach_name = eme_sanitize_attach_filename($filename.'.'.$extension);
$attachment_paths_arr[$attach_name] = $attachment[1];
} else {
$filename = eme_sanitize_attach_filename($attachment[0]);
$attachment_paths_arr[$filename] = $attachment[1];
}
}
} else {
// if it is not a numeric id, it is a file path (like for pdf tickets)
if ( file_exists( $attachment ) ) {
$filename = pathinfo($attachment, PATHINFO_FILENAME);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
if (empty($extension))
$extension = "none";
// now remove parts of the file
$filename = preg_replace( '/(member-\d+|booking-\d+)-.*/', '$1', $filename );
$filename = preg_replace( '/.*-(qrcode.*)/', '$1', $filename );
$attach_name = eme_sanitize_attach_filename($filename.'.'.$extension);
$attachment_paths_arr[$attach_name] = $attachment;
}
}
}
}
if ( ! in_array( $mailoptions['mail_send_method'], [ 'smtp', 'mail', 'sendmail', 'qmail', 'wp_mail' ] ) ) {
$mailoptions['mail_send_method'] = 'wp_mail';
}
if ( $mailoptions['mail_send_method'] == 'wp_mail' ) {
// Set the correct mail headers (the first 2 are to try to avoid auto-repliers)
$headers[] = 'Auto-Submitted: auto-generated';
$headers[] = 'X-Auto-Response-Suppress: all';
$headers[] = 'From: '.$mailoptions['fromName'].' <'.$mailoptions['fromMail'].'>';
if ( !empty($mailoptions['replytoMail']) && eme_is_email($mailoptions['replytoMail'])) {
$headers[] = 'Reply-To: '.$mailoptions['replytoName'].' <'.$mailoptions['replytoMail'].'>';
}
if ( ! empty( $mailoptions['bcc_addresses'] ) ) {
foreach ( $bcc_addresses as $bcc_address ) {
if (eme_is_email($bcc_address)) {
$headers[] = 'Bcc: ' . trim( $bcc_address );
}
}
}
if ( ! empty( $custom_headers ) && is_array( $custom_headers ) ) {
foreach ( $custom_headers as $custom_header ) {
$headers[] = $custom_header;
}
}
// set the correct content type
if ( $mailoptions['send_html'] ) {
$body = eme_nl2br_save_html( $body );
// set the content-type header, wp-mail knows about this one
// it is cleaner than add_filter/remove_filter of wp_mail_content_type ...
$headers[] = 'Content-type: text/html';
//add_filter( 'wp_mail_content_type', 'eme_set_wpmail_html_content_type' );
}
// now send it
if ( ! empty( $mailoptions['toMail'] ) ) {
$res = wp_mail( $mailoptions['toMail'], $subject, $body, $headers, $attachment_paths_arr );
if ( ! $res ) {
$message = __( 'There were some problems while sending mail.', 'events-made-easy' );
}
} else {
$res = false;
$message = __( 'Empty email', 'events-made-easy' );
}
// Reset content-type to avoid conflicts -- http://core.trac.wordpress.org/ticket/23578
//if ( $mailoptions['send_html'] ) {
// remove_filter( 'wp_mail_content_type', 'eme_set_wpmail_html_content_type' );
//}
} else {
// we prefer the new location first
if ( file_exists( ABSPATH . WPINC . '/PHPMailer/PHPMailer.php' ) ) {
require_once ABSPATH . WPINC . '/PHPMailer/PHPMailer.php';
require_once ABSPATH . WPINC . '/PHPMailer/SMTP.php';
require_once ABSPATH . WPINC . '/PHPMailer/Exception.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
} else {
// for older wp instances (pre 5.5)
require_once ABSPATH . WPINC . '/class-phpmailer.php';
$mail = new PHPMailer();
}
$mail->ClearAllRecipients();
$mail->ClearAddresses();
$mail->ClearAttachments();
$mail->clearCustomHeaders();
$mail->clearReplyTos();
$mail->CharSet = 'utf-8';
// avoid the x-mailer header
$mail->XMailer = ' ';
// Set the correct mail headers (the first 2 are to try to avoid auto-repliers)
$mail->addCustomHeader('Auto-Submitted: auto-generated');
$mail->addCustomHeader('X-Auto-Response-Suppress: all');
// add custom headers
if ( ! empty( $custom_headers ) && is_array( $custom_headers ) ) {
foreach ( $custom_headers as $custom_header ) {
$mail->addCustomHeader( $custom_header );
}
}
//$mail->SetLanguage( 'en', __DIR__ . '/' );
if ( $mailoptions['mail_send_method'] == 'qmail' ) {
$mail->IsQmail();
} else {
$mail->Mailer = $mailoptions['mail_send_method'];
}
if ( $mailoptions['mail_send_method'] == 'smtp' ) {
// let us keep a normal smtp timeout ...
$mail->Timeout = 10;
$mail->Host = $mailoptions['smtp_host'];
// we set optional encryption and port settings
// but if the Host contains ssl://, tls:// or port info, it will take precedence over these anyway
// so it is not bad at all :-)
if ( $mailoptions['smtp_encryption'] == 'tls' || $mailoptions['smtp_encryption'] == 'ssl' ) {
$mail->SMTPSecure = $mailoptions['smtp_encryption'];
} else {
// if we don't want encryption, let's disable autotls too, since that might be a problem
$mail->SMTPAutoTLS = false;
}
if ( ! $mailoptions['smtp_verify_cert'] ) {
// let's disable certificate verification, but only for reserved ranges
// weirdly the private range filter doesn't contain 127.0.0.0/8, so we use reserved
// range which is still internal
$tmp_ip = $mail->Host;
// remove the possible ssl:// or tls://
$tmp_ip = preg_replace( '/.*?:\/\//', '', $tmp_ip );
// if the host setting is not an ip, resolve it and get the ip
if ( ! filter_var( $tmp_ip, FILTER_VALIDATE_IP ) ) {
$lookup = dns_get_record( $tmp_ip );
if ( $lookup ) {
foreach ( $lookup as $res ) {
if ( isset( $res['ip'] ) ) {
$tmp_ip = $res['ip'];
} elseif ( isset( $res['ipv6'] ) ) {
$tmp_ip = $res['ipv6'];
}
// we're only interested in 1 result
break;
}
}
}
$in_reserved_range = 0;
if ( filter_var( $tmp_ip, FILTER_VALIDATE_IP )
&& ! filter_var( $tmp_ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE ) ) {
// ip in the reserved range? then we still set it only if the ip is valid
$in_reserved_range = 1;
}
// so now we disable cert verification as requested and allow self signed
// but only for ip's in the reserved range
if ( $in_reserved_range ) {
$mail->SMTPOptions = [
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true,
],
];
}
}
$mail->Port = intval( $mailoptions['smtp_port'] );
if ( $mailoptions['smtp_auth'] ) {
$mail->SMTPAuth = true;
$mail->Username = $mailoptions['smtp_username'];
$mail->Password = $mailoptions['smtp_password'];
}
if ( $mailoptions['smtp_debug'] ) {
$mail->SMTPDebug = 2;
$mail->Debugoutput = function( $str, $level ) use (&$debugtxt) {
$debugtxt .= "$level: $str\n";
};
}
}
$mail->setFrom( $mailoptions['fromMail'], $mailoptions['fromName'] );
$altbody = eme_replacelinks( $body );
if ( $mailoptions['send_html'] ) {
$mail->isHTML( true );
// Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
$mail->AltBody = $mail->normalizeBreaks( $mail->html2text( $altbody ) );
$mail->Body = $mail->normalizeBreaks( eme_nl2br_save_html( $body ) );
} else {
$mail->Body = $mail->normalizeBreaks( $altbody );
}
$mail->Subject = $subject;
if ( ! empty( $mailoptions['replytoMail'] ) && eme_is_email($mailoptions['replytoMail'] ) ) {
$mail->addReplyTo( $mailoptions['replytoMail'], $mailoptions['replytoName'] );
}
if ( ! empty( $mailoptions['bcc_addresses'] ) ) {
foreach ( $bcc_addresses as $bcc_address ) {
if (eme_is_email($bcc_address)) {
$mail->addBCC( trim( $bcc_address ) );
}
}
}
if ( ! empty( $attachment_paths_arr ) ) {
foreach ( $attachment_paths_arr as $filename => $att ) {
$filename = is_string( $filename ) ? $filename : '';
$mail->addAttachment( $att, $filename );
}
}
if ( ! empty( $mailoptions['toMail'] ) ) {
$mail->addAddress( $mailoptions['toMail'], $mailoptions['toName'] );
if ( ! $mail->send() ) {
$res = false;
$message = $mail->ErrorInfo;
} else {
$res = true;
}
} else {
$res = false;
$message = __( 'Empty email', 'events-made-easy' );
}
}
// remove the phpmailer url added for some errors
$message = str_replace( 'https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting', '', $message );
return [ $res, $message, $debugtxt ];
}
function eme_db_insert_ongoing_mailing( $mailing_name, $subject, $body, $fromemail, $fromname, $replytoemail, $replytoname, $mail_text_html, $conditions = [] ) {
$now = current_time( 'mysql', false );
return eme_db_insert_mailing( $mailing_name, $now, $subject, $body, $fromemail, $fromname, $replytoemail, $replytoname, $mail_text_html, $conditions, "ongoing" );
}
function eme_db_insert_mailing( $mailing_name, $planned_on, $subject, $body, $fromemail, $fromname, $replytoemail, $replytoname, $mail_text_html, $conditions, $status = "initial" ) {
global $wpdb;
$mailing_table = EME_DB_PREFIX . EME_MAILINGS_TBNAME;
if ( empty( $fromemail ) ) {
$fromemail = $replytoemail;
$fromname = $replytoname;
}
// if forced or fromemail is still empty
if ( get_option( 'eme_mail_force_from' ) || empty( $fromemail ) ) {
[$fromname, $fromemail] = eme_get_default_mailer_info();
}
// now the from should never be empty, so just check reply to again
if ( empty( $replytoemail ) ) {
$replytoemail = $fromemail;
}
if ( empty( $replytoname ) ) {
$replytoname = $fromname;
}
$now = current_time( 'mysql', false );
$mailing = [
'name' => mb_substr( $mailing_name, 0, 255 ),
'planned_on' => $planned_on,
'status' => $status,
'subject' => mb_substr( $subject, 0, 255 ),
'body' => $body,
'fromemail' => $fromemail,
'fromname' => mb_substr( $fromname, 0, 255 ),
'replytoemail' => $replytoemail,
'replytoname' => mb_substr( $replytoname, 0, 255 ),
'mail_text_html' => $mail_text_html,
'creation_date' => $now,
'conditions' => eme_serialize( $conditions ),
];
// add userid if possible
$current_userid = get_current_user_id();
if (!empty($current_userid)) {
$mailing['created_by'] = $current_userid;
}
if ( $wpdb->insert( $mailing_table, $mailing ) === false ) {
return false;
} else {
return $wpdb->insert_id;
}
}
function eme_queue_fastmail( $subject, $body, $fromemail, $fromname, $receiveremail, $receivername, $replytoemail, $replytoname, $mailing_id = 0, $person_id = 0, $member_id = 0, $atts_arr = [] ) {
return eme_queue_mail( $subject, $body, $fromemail, $fromname, $receiveremail, $receivername, $replytoemail, $replytoname, $mailing_id, $person_id, $member_id, $atts_arr, 1 );
}
function eme_queue_mail( $subject, $body, $fromemail, $fromname, $receiveremail, $receivername, $replytoemail = '', $replytoname = '', $mailing_id = 0, $person_id = 0, $member_id = 0, $atts_arr = [], $send_immediately = 0 ) {
global $wpdb;
$mqueue_table = EME_DB_PREFIX . EME_MQUEUE_TBNAME;
if ( eme_is_empty_string( $subject ) || eme_is_empty_string( $body ) ) {
// no mail to be sent: fake it
return true;
}
// no valid email? return false
if ( ! eme_is_email( $receiveremail ) ) {
return false;
}
$random_id = eme_random_id();
if ( ! get_option( 'eme_queue_mails' ) ) {
$send_immediately = 1;
}
// not needed if part of a mailing: then this is already done
if (!$mailing_id) {
if ( empty( $fromemail ) ) {
$fromemail = $replytoemail;
$fromname = $replytoname;
}
// if forced or fromemail is still empty
if ( get_option( 'eme_mail_force_from' ) || empty( $fromemail ) ) {
[$fromname, $fromemail] = eme_get_default_mailer_info();
}
// now the from should never be empty, so just check reply to again
if ( empty( $replytoemail ) ) {
$replytoemail = $fromemail;
}
if ( empty( $replytoname ) ) {
$replytoname = $fromname;
}
}
$now = current_time( 'mysql', false );
$mail = [
'subject' => mb_substr( $subject, 0, 255 ),
'body' => $body,
'fromemail' => $fromemail,
'fromname' => mb_substr( $fromname, 0, 255 ),
'receiveremail' => $receiveremail,
'receivername' => mb_substr( $receivername, 0, 255 ),
'replytoemail' => $replytoemail,
'replytoname' => mb_substr( $replytoname, 0, 255 ),
'mailing_id' => $mailing_id,
'person_id' => $person_id,
'member_id' => $member_id,
'attachments' => eme_serialize( $atts_arr ),
'creation_date' => $now,
'random_id' => $random_id,
];
// add userid if possible
if (!empty($current_userid)) {
$mail['created_by'] = $current_userid;
}
if ( $send_immediately ) {
// we add the mail to the queue as sent and send it immediately
$mail['status'] = 1;
$mail['sent_datetime'] = $now;
if ($wpdb->insert( $mqueue_table, $mail ) === false) {
return false;
} else {
$custom_headers = [ 'X-EME-mailid:' . $random_id ];
$mail_res_arr = eme_send_mail( $subject, $body, $receiveremail, $receivername, $replytoemail, $replytoname, $fromemail, $fromname, $atts_arr, $custom_headers );
if ( $mail_res_arr[0] ) {
return true;
} else {
return false;
}
}
} elseif ( $wpdb->insert( $mqueue_table, $mail ) === false ) {
return false;
} else {
return true;
}
}
function eme_mark_mail_ignored( $id ) {
global $wpdb;
$mqueue_table = EME_DB_PREFIX . EME_MQUEUE_TBNAME;
$where = [];
$fields = [];
$where['id'] = intval( $id );
$fields['status'] = 4;
$fields['sent_datetime'] = current_time( 'mysql', false );
if ( $wpdb->update( $mqueue_table, $fields, $where ) === false ) {
return false;
} else {
return true;
}
}
function eme_mark_mail_sent( $id ) {
global $wpdb;
$mqueue_table = EME_DB_PREFIX . EME_MQUEUE_TBNAME;
$where = [];
$fields = [];
$where['id'] = intval( $id );
$fields['status'] = 1;
$fields['sent_datetime'] = current_time( 'mysql', false );
if ( $wpdb->update( $mqueue_table, $fields, $where ) === false ) {
return false;
} else {
return true;
}
}
function eme_mark_mail_fail( $id, $error_msg = '' ) {
global $wpdb;
$mqueue_table = EME_DB_PREFIX . EME_MQUEUE_TBNAME;
$where = [];
$fields = [];
$where['id'] = intval( $id );
$fields['status'] = 2;
$fields['error_msg'] = esc_sql( $error_msg );
$fields['sent_datetime'] = current_time( 'mysql', false );
if ( $wpdb->update( $mqueue_table, $fields, $where ) === false ) {
return false;
} else {
return true;
}
}
function eme_cancel_all_queued() {
global $wpdb;
// cancel all ongoing and planned mailings
$ongoing_mailings = eme_get_mailings(status: 'ongoing');
foreach ( $ongoing_mailings as $mailing) {
eme_cancel_mailing( $mailing['id'] );
}
$planned_mailings = eme_get_mailings(status: 'planned');
foreach ( $planned_mailings as $mailing) {
eme_cancel_mailing( $mailing['id'] );
}
// cancel individual mails
$mqueue_table = EME_DB_PREFIX . EME_MQUEUE_TBNAME;
$sql = "UPDATE $mqueue_table WHERE status=3 WHERE status=0";
$wpdb->query( $sql );
}
function eme_get_queued_count() {
global $wpdb;
$mqueue_table = EME_DB_PREFIX . EME_MQUEUE_TBNAME;
// the queued count is to know how much mails are left unsent in the queue
$sql = "SELECT COUNT(*) FROM $mqueue_table WHERE status=0";
$count = $wpdb->get_var( $sql );
// now also include planned mailings
$planned_mailings = eme_get_mailings(status: 'planned');
foreach ($planned_mailings as $mailing) {
// older mailings inserted the mails directly and not update the stats
// newer mailings only set the planned stats and update the receivers the moment the mailing starts
if (empty($mailing['stats'])) {
$stats = eme_get_mailing_stats( $mailing['id'] );
} else {
$stats = eme_unserialize( $mailing['stats'] );
}
$count += $stats['planned'];
}
return $count;
}
function eme_get_queued( $now ) {
global $wpdb;
$mqueue_table = EME_DB_PREFIX . EME_MQUEUE_TBNAME;
$mailings_table = EME_DB_PREFIX . EME_MAILINGS_TBNAME;
// we take only the queued mails with status=0 where either the planning date for the mailing has passed (so we know those can be send) or that are not part of a mailing
$sql = "SELECT $mqueue_table.* FROM $mqueue_table LEFT JOIN $mailings_table ON $mqueue_table.mailing_id=$mailings_table.id WHERE $mqueue_table.status=0 AND ($mqueue_table.mailing_id=0 OR ($mqueue_table.mailing_id>0 and $mailings_table.planned_on<'$now'))";
$eme_cron_queue_count = intval( get_option( 'eme_cron_queue_count' ) );
if ( $eme_cron_queue_count > 0 ) {
$sql .= " LIMIT $eme_cron_queue_count";
}
return $wpdb->get_results( $sql, ARRAY_A );
}
function eme_send_queued_rest( WP_REST_Request $request ) {
$force_interval = $request['interval'];
//if (defined('REST_REQUEST')) {
// return new WP_REST_Response( $force_interval, 200 );
//}
if (is_numeric($force_interval))
eme_send_queued($force_interval);
}
function eme_send_queued($force_interval=0) {
// we'll build in a safety precaution to make sure to never surpass the schedule duration
$start_time = time();
if (!$force_interval || !is_numeric($force_interval)) {
$scheduled = wp_get_schedule( 'eme_cron_send_queued' );
if (!$scheduled) { // issue with wp cron? Then take 1 hour, to make sure this still runs ok
$scheduled = 'hourly';
}
$wp_schedules = wp_get_schedules();
$interval = $wp_schedules[ $scheduled ]['interval'];
// let's keep 5 seconds to ourselves (see at the end of this function)
$interval -= 5;
} else {
$interval = $force_interval-5;
}
$eme_mail_send_html = get_option( 'eme_mail_send_html' );
$eme_mail_sleep = intval( get_option( 'eme_mail_sleep' ) );
if ( $eme_mail_sleep >= 1000000 ) {
$eme_mail_sleep_seconds = intval( $eme_mail_sleep / 1000000 );
$eme_mail_sleep_useconds = $eme_mail_sleep % 1000000;
} elseif ( $eme_mail_sleep > 0 ) {
$eme_mail_sleep_seconds = 0;
$eme_mail_sleep_useconds = $eme_mail_sleep;
} else {
$eme_mail_sleep_seconds = 0;
$eme_mail_sleep_useconds = 0;
}
// we use $now as an argument for eme_get_passed_planned_mailingids and eme_get_queued
// Reason: since eme_check_mailing_receivers can take some time, we want to make sure that
// both eme_get_passed_planned_mailingids and eme_get_queued are talking about the same 'past'
$eme_date_obj_now = new ExpressiveDate( 'now', EME_TIMEZONE );
$now = $eme_date_obj_now->getDateTime();
// for all planned mailings in the passed: re-evaluate the receivers
// since we mark the mailing as ongoing afterwards, this re-evalution only happens once
// and as such doesn't get in the way of eme_get_queued doing it's work
$passed_planned_mailings = eme_get_passed_planned_mailingids( $now );
foreach ( $passed_planned_mailings as $mailing_id ) {
// the next function call can take a while
eme_check_mailing_receivers( $mailing_id );
eme_mark_mailing_ongoing( $mailing_id );
}
// check if tracking is required and possible (meaning: only for html mails)
if ( $eme_mail_send_html && get_option( 'eme_mail_tracking' ) ) {
$add_tracking = true;
} else {
$add_tracking = false;
}
// now handle any queued mails
$mails = eme_get_queued( $now );
foreach ( $mails as $mail ) {
if ( empty( $mail['receiveremail'] ) ) {
eme_mark_mail_ignored( $mail['id'] );
continue; // the continue-statement continues the higher foreach-loop
}
$body = $mail['body'];
if (eme_is_serialized( $mail['attachments'] )) {
$atts = eme_unserialize( $mail['attachments'] );
} else {
$atts = [];
}
if ( $add_tracking && ! empty( $mail['random_id'] ) ) {
$track_url = eme_tracker_url( $mail['random_id'] );
$track_html = "<img src='$track_url' alt=''>";
// if a closing body-tag is present, add it before that
// otherwise add it to the end
if ( strstr( $body, '</body>' ) ) {
$body = str_replace( '</body>', $track_html . '</body>', $body );
} else {
$body .= $track_html;
}
}
$custom_headers = [ 'X-EME-mailid:' . $mail['random_id'] ];
$mail_res_arr = eme_send_mail( $mail['subject'], $body, $mail['receiveremail'], $mail['receivername'], $mail['replytoemail'], $mail['replytoname'], $mail['fromemail'], $mail['fromname'], $atts, $custom_headers );
if ( $mail_res_arr[0] ) {
eme_mark_mail_sent( $mail['id'] );
} else {
eme_mark_mail_fail( $mail['id'], $mail_res_arr[1] );
}
// we'll build in a safety precaution to make sure to never surpass the schedule duration
// this is only usefull if the sleep is configured, since otherwise mails are send immediately, but just to be sure ...
$cur_time = time();
if ( $cur_time - $start_time > $interval ) {
break;
}
// now sleep if wanted and the send the next mail
if ( $eme_mail_sleep_seconds > 0 ) {
sleep( $eme_mail_sleep_seconds );
}
if ( $eme_mail_sleep_useconds > 0 ) {
usleep( $eme_mail_sleep_useconds );
}
}
// and for the mailings that were marked ongoing, mark them as finished if appropriate
// thanks to the fact we substraced 5 seconds from the $interval, we always have time to finish this
$ongoing_mailings = eme_get_mailings(status: 'ongoing');
foreach ( $ongoing_mailings as $mailing) {
if ( eme_count_mails_to_send( $mailing['id'] ) == 0 ) {
eme_mark_mailing_completed( $mailing['id'] );
}
}
}
function eme_get_passed_planned_mailingids( $now ) {
global $wpdb;
$mailings_table = EME_DB_PREFIX . EME_MAILINGS_TBNAME;
$sql = "SELECT id FROM $mailings_table WHERE status='planned' AND planned_on<'$now'";
return $wpdb->get_col( $sql );
}
function eme_mark_mailing_planned( $mailing_id, $planned_count ) {
global $wpdb;
$mailings_table = EME_DB_PREFIX . EME_MAILINGS_TBNAME;
$stats = [
'planned' => $planned_count,
'sent' => 0,
'failed' => 0,
'cancelled' => 0,
'ignored' => 0,
'total_read_count' => 0,
];
$sql = $wpdb->prepare( "UPDATE $mailings_table SET status='planned', stats=%s WHERE id=%d", eme_serialize( $stats ), $mailing_id );
$wpdb->query( $sql );
}
function eme_mark_mailing_ongoing( $mailing_id ) {
global $wpdb;
$mailings_table = EME_DB_PREFIX . EME_MAILINGS_TBNAME;
$sql = $wpdb->prepare( "UPDATE $mailings_table SET status='ongoing' WHERE id=%d", $mailing_id );
$wpdb->query( $sql );
}
function eme_mark_mailing_completed( $mailing_id ) {
global $wpdb;
$stats = eme_get_mailing_stats( $mailing_id );
$mailings_table = EME_DB_PREFIX . EME_MAILINGS_TBNAME;
$sql = $wpdb->prepare( "UPDATE $mailings_table SET status='completed', stats=%s WHERE id=%d", eme_serialize( $stats ), $mailing_id );
$wpdb->query( $sql );
if ( $stats['failed'] > 0 ) {
$mailing = eme_get_mailing( $mailing_id );
$failed_subject = __( 'Mailing completed with errors', 'events-made-easy' );
$failed_body = sprintf( __( 'Mailing "%s" completed with %d errors, please check the mailing report', 'events-made-easy' ), $mailing['name'], $stats['failed'] );
eme_send_mail( $failed_subject, $failed_body, $mailing['replytoemail'], $mailing['replytoname'], $mailing['replytoemail'], $mailing['replytoname'] );
}
}
function eme_archive_mailing( $mailing_id ) {
global $wpdb;
$mailing = eme_get_mailing( $mailing_id );
if ( $mailing['status'] == 'planned' || $mailing['status'] == 'ongoing' ) {
return;
}
$mailings_table = EME_DB_PREFIX . EME_MAILINGS_TBNAME;
if ( $mailing['status'] == 'completed' ) {
// for completed mailings, the stats no longer change
$sql = $wpdb->prepare( "UPDATE $mailings_table SET status='archived' WHERE id=%d", $mailing_id );
} else {
$stats = eme_serialize( eme_get_mailing_stats( $mailing_id ) );
$sql = $wpdb->prepare( "UPDATE $mailings_table SET status='archived', stats=%s WHERE id=%d", $stats, $mailing_id );
}
$wpdb->query( $sql );
$queue_table = EME_DB_PREFIX . EME_MQUEUE_TBNAME;
$sql = $wpdb->prepare( "DELETE FROM $queue_table WHERE mailing_id=%d", $mailing_id );
$wpdb->query( $sql );
}
function eme_mailing_retry_failed( $id ) {
global $wpdb;
$mqueue_table = EME_DB_PREFIX . EME_MQUEUE_TBNAME;
$where = [];
$fields = [];
$where['mailing_id'] = intval( $id );
$where['status'] = 2;
$fields['status'] = 0;
if ( $wpdb->update( $mqueue_table, $fields, $where ) === false ) {
return false;
} else {
return true;
}
}
// for GDPR CRON
function eme_archive_old_mailings() {
global $wpdb;
$archive_old_mailings_days = get_option( 'eme_gdpr_archive_old_mailings_days' );
if ( empty( $archive_old_mailings_days ) ) {
return;
} else {
$archive_old_mailings_days = abs( $archive_old_mailings_days );
}
$eme_date_obj = new ExpressiveDate( 'now', EME_TIMEZONE );
$old_date = $eme_date_obj->minusDays( $archive_old_mailings_days )->getDateTime();
$mailings_table = EME_DB_PREFIX . EME_MAILINGS_TBNAME;
$sql = "SELECT id FROM $mailings_table WHERE creation_date < '$old_date' AND (status='completed' OR status='cancelled')";
$mailing_ids = $wpdb->get_col( $sql );
foreach ( $mailing_ids as $mailing_id ) {
eme_archive_mailing( $mailing_id );
}
// now remove old mails not belonging to a specific mailing
$queue_table = EME_DB_PREFIX . EME_MQUEUE_TBNAME;
$sql = "DELETE FROM $queue_table WHERE mailing_id=0 AND creation_date < '$old_date'";
$wpdb->query( $sql );
}
function eme_cancel_mail( $mail_id ) {
global $wpdb;
$queue_table = EME_DB_PREFIX . EME_MQUEUE_TBNAME;
$sql = $wpdb->prepare( "UPDATE $queue_table SET status=3 WHERE status=0 AND id=%d", $mail_id );
$wpdb->query( $sql );
}
function eme_cancel_mailing( $mailing_id ) {
global $wpdb;
$queue_table = EME_DB_PREFIX . EME_MQUEUE_TBNAME;
$sql = $wpdb->prepare( "UPDATE $queue_table SET status=3 WHERE status=0 AND mailing_id=%d", $mailing_id );
$wpdb->query( $sql );
$stats = eme_serialize( eme_get_mailing_stats( $mailing_id ) );
$mailings_table = EME_DB_PREFIX . EME_MAILINGS_TBNAME;
$sql = $wpdb->prepare( "UPDATE $mailings_table SET status='cancelled', stats=%s WHERE id=%d", $stats, $mailing_id );
$wpdb->query( $sql );
}
function eme_delete_mailing_mails( $id ) {
global $wpdb;
$queue_table = EME_DB_PREFIX . EME_MQUEUE_TBNAME;
$sql = $wpdb->prepare( "DELETE FROM $queue_table WHERE mailing_id=%d", $id );
$wpdb->query( $sql );
}
function eme_delete_mailing( $id ) {
global $wpdb;
eme_delete_mailing_mails( $id );
$mailings_table = EME_DB_PREFIX . EME_MAILINGS_TBNAME;
$sql = $wpdb->prepare( "DELETE FROM $mailings_table WHERE id=%d", $id );
$wpdb->query( $sql );
}
function eme_get_mail( $id ) {
global $wpdb;
$table = EME_DB_PREFIX . EME_MQUEUE_TBNAME;
$sql = $wpdb->prepare( "SELECT * FROM $table WHERE id=%d", $id );
return $wpdb->get_row( $sql, ARRAY_A );
}
function eme_get_mailing( $id ) {
global $wpdb;
$mailings_table = EME_DB_PREFIX . EME_MAILINGS_TBNAME;
$sql = $wpdb->prepare( "SELECT * FROM $mailings_table WHERE id=%d", $id );
return $wpdb->get_row( $sql, ARRAY_A );
}
function eme_get_mailings( $status = '', $search_text = '' ) {
global $wpdb;
$mailings_table = EME_DB_PREFIX . EME_MAILINGS_TBNAME;
$mailing_states = eme_mailing_localizedstates();
if ( !empty( $status ) && array_key_exists( $status, $mailing_states ) ) {
$where = " WHERE status='$status' ";
} else {
$where = " WHERE status<>'archived' ";
}
if ( !empty($search_text)) {
$search_text = "%" . $wpdb->esc_like( $search_text ) . "%";
$sql = $wpdb->prepare("SELECT * FROM $mailings_table $where AND ( name LIKE %s OR subject LIKE %s ) ORDER BY planned_on,name", $search_text, $search_text);
} else {
$sql = "SELECT * FROM $mailings_table $where ORDER BY planned_on,name";
}
return $wpdb->get_results( $sql, ARRAY_A );
}
function eme_mail_states() {
$states = [
0 => 'planned',
1 => 'sent',
2 => 'failed',
3 => 'cancelled',
4 => 'ignored',
];
return $states;
}
function eme_mail_localizedstates() {
$states = [
0 => __( 'Planned', 'events-made-easy' ),
1 => __( 'Sent', 'events-made-easy' ),
2 => __( 'Failed', 'events-made-easy' ),
3 => __( 'Cancelled', 'events-made-easy' ),
4 => __( 'Ignored', 'events-made-easy' )
];
return $states;
}
function eme_mailing_localizedstates() {
$states = [
'archived' => __( 'Archived', 'events-made-easy' ),
'planned' => __( 'Planned', 'events-made-easy' ),
'ongoing' => __( 'Ongoing', 'events-made-easy' ),
'completed' => __( 'Completed', 'events-made-easy' ),
'cancelled' => __( 'Cancelled', 'events-made-easy' ),
'initial' => __( 'Initializing ...', 'events-made-easy' )
];
return $states;
}
function eme_count_mails_to_send( $mailing_id ) {
global $wpdb;
$table = EME_DB_PREFIX . EME_MQUEUE_TBNAME;
$sql = $wpdb->prepare( "SELECT COUNT(*) FROM $table WHERE status=0 AND mailing_id=%d", $mailing_id );
return $wpdb->get_var( $sql );
}
function eme_get_mailing_stats( $mailing_id = 0 ) {
global $wpdb;
$table = EME_DB_PREFIX . EME_MQUEUE_TBNAME;
$sql = "SELECT COUNT(*) AS count,status FROM $table WHERE mailing_id=$mailing_id GROUP BY mailing_id,status";
$lines = $wpdb->get_results( $sql, ARRAY_A );
$res = [
'planned' => 0,
'sent' => 0,
'failed' => 0,
'cancelled' => 0,
'ignored' => 0,
'total_read_count' => 0,
];
$states = eme_mail_states();
foreach ( $lines as $line ) {
$status = $states[ $line['status'] ];
$res[ $status ] = $line['count'];
}
return $res;
}
function eme_mail_track( $random_id ) {
global $wpdb;
$table = EME_DB_PREFIX . EME_MQUEUE_TBNAME;
$mailings_table = EME_DB_PREFIX . EME_MAILINGS_TBNAME;
if ( ! empty( $random_id ) && get_option( 'eme_mail_tracking' ) ) {
// we'll randomly sleep between 0 and 20 times 0.1 seconds (100000 microseconds)
// so if 2 requests for the same id arrive at the same time, it will hopefully not do the select at the same time
// Without the random sleep, 2 request for the same id would cause the read_count in the mailings_table to be updated too much (nothing to worry about, but it wouldn't reflect reality)
// /usleep(rand(0, 20)*100000); // we do it in microseconds with random, is better than simple sleep(rand(0,2)) which could return the same result for rand too often
$sql = $wpdb->prepare( "SELECT * FROM $table WHERE random_id=%s", $random_id );
$queued_mail = $wpdb->get_row( $sql, ARRAY_A );
if ( $queued_mail ) {
// update the queue table when the mail was read for the first time
$eme_date_obj_now = new ExpressiveDate( 'now', EME_TIMEZONE );
// ignore if the same track arrives within the firt 2 minutes
$ignore = 0;
if ( ! eme_is_empty_datetime( $queued_mail['last_read_on'] ) ) {
$eme_date_obj_lastread = new ExpressiveDate( $queued_mail['last_read_on'], EME_TIMEZONE );
if ( $eme_date_obj_lastread->getDifferenceInMinutes( $eme_date_obj_now ) < 2 ) {
$ignore = 1;
}
}
if ( ! $ignore ) {
$now = $eme_date_obj_now->getDateTime();
// we add the read_count=0 to the SQL statement so we know that 2 identical queries arriving almost at the same time will not cause the same update
$sql = $wpdb->prepare( "UPDATE $table SET first_read_on=%s, last_read_on=%s, read_count=1 WHERE id = %d AND read_count=0", $now, $now, $queued_mail['id'] );
$res = $wpdb->query( $sql );
// update the mailing table with the count of times the mail was read
// read_count in the mailings_table is the unique read count for this mailing
if ( $res !== false ) {
if ( $res > 0 ) {
// res is >0, meaning a row was changed, so it was read for the first time
if ( $queued_mail['mailing_id'] > 0 ) {
$sql = $wpdb->prepare( "UPDATE $mailings_table SET read_count=read_count+1, total_read_count=total_read_count+1 WHERE id = %d", $queued_mail['mailing_id'] );
$wpdb->query( $sql );
}
} else {
// no row changed, meaning the mail was already read once, so do it without read_count=0 check
$sql = $wpdb->prepare( "UPDATE $table SET last_read_on=%s, read_count=read_count+1 WHERE id = %d", $now, $queued_mail['id'] );
$res = $wpdb->query( $sql );
if ( ! empty( $res ) && $queued_mail['mailing_id'] > 0 ) { // not false and >0
$sql = $wpdb->prepare( "UPDATE $mailings_table SET total_read_count=total_read_count+1 WHERE id = %d", $queued_mail['mailing_id'] );
$wpdb->query( $sql );
}
}
}
}
}
// always return a transparant image of 1x1
$eme_plugin_dir = eme_plugin_dir();
header( 'Content-Type: image/gif' );
//$image = file_get_contents($eme_plugin_dir.'images/1x1.gif');
//echo $image;
readfile( $eme_plugin_dir . 'images/1x1.gif' );
}
}
function eme_check_mailing_receivers( $mailing_id ) {
if ( ! $mailing_id ) {
return;
}
$mailing = eme_get_mailing( $mailing_id );
if ( ! $mailing || empty( $mailing['conditions'] ) ) {
return;
}
$conditions = eme_unserialize( $mailing['conditions'] );
// we delete all planned mails for the mailing and enter the mails anew, this allows us to have all mails with the latest content and receivers
// for newer versions of EME this delete no longer does anything since the individual mails are only inserted here when calling eme_update_mailing_receivers
eme_delete_mailing_mails( $mailing_id );
eme_update_mailing_receivers( $mailing['subject'], $mailing['body'], $mailing['fromemail'], $mailing['fromname'], $mailing['replytoemail'], $mailing['replytoname'], $mailing['mail_text_html'], $conditions, $mailing_id );
}
function eme_count_planned_mailing_receivers( $conditions, $mailing_id = 0) {
return eme_update_mailing_receivers( conditions: $conditions, mailing_id: $mailing_id, count_only: 1);
}
function eme_update_mailing_receivers( $mail_subject = '', $mail_message = '', $from_email = '', $from_name = '', $replyto_email = '', $replyto_name = '', $mail_text_html = 'html', $conditions = [], $mailing_id = 0, $count_only = 0 ) {
$res = [
'mail_problems' => 0,
'total' => 0,
'not_sent' => ''
];