forked from e107inc/e107
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmail.php
1555 lines (1296 loc) · 47.8 KB
/
mail.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
/*
* e107 website system
*
* Copyright (C) 2008-2013 e107 Inc (e107.org)
* Released under the terms and conditions of the
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
*
* Mail handler
*/
/**
*
* @package e107
* @subpackage e107_handlers
*
* Mailout handler - concerned with processing and sending a single email
* Extends the PHPMailer class
*/
/*
TODO:
1. Mustn't include header in text section of emails
2. Option to wrap HTML in a standard header (up to <body>) and footer (from </body>)
Maybe each template is an array with several parts - optional header and footer, use defaults if not defined
header looks for the {STYLESHEET} variable
If we do that, can have a single override file, plus a core file
3. mail (PHP method) - note that it has parameters for additional headers and other parameters
4. Check that language support works - PHPMailer defaults to English if other files not available
- PHPMailer expects a 2-letter code - $this->SetLanguage(CORE_LC) - e.g. 'en', 'br'
5. Logging:
- Use rolling log for errors - error string(s) available - sort out entry
- Look at support of some other logging options
9. Make sure SMTPDebug can be set (true/false)
12. Check support for port number - ATM we just override for SSL. Looks as if phpmailer can take it from end of server link.
18. Note object iteration - may be useful for dump of object state
19. Consider overriding error handler
20. Look at using new prefs structure
21. Should we always send an ID?
22. Force singleton so all mail sending flow controlled a bit (but not where parameters overridden in constructor)
Tested so far (with PHP4 version)
------------
SMTP send (standard)
Return receipts
text or mixed
replyto
priority field
TLS to googlemail (use TLS)
Notes if problems
-----------------
1. Attachment adding call had dirname() added round path.
2. There are legacy and new methods for generating a multi-part body (HTML + plain text). Only the new method handles inline images.
- Currently uses the new method (which is part of phpmailer)
General notes
-------------
1. Can specify a comma-separated list of smtp servers - presumably all require the same login credentials
2. qmail can be used (if available) by selecting sendmail, and setting the sendmail path to that for qmail instead
3. phpmailer does trim() on passed parameters where needed - so we don't need to.
4. phpmailer has its own list of MIME types.
5. Attachments - note method available for passing string attachments
- AddStringAttachment($string,$filename,$encoding,$type)
6. Several email address-related methods can accept two comma-separated strings, one for addresses and one for related names
7. Its possible to send a text-only email by passing an array of parameters including 'send_html' = false
8. For bulk emailing, must call the 'allSent()' method when complete to ensure SMTP mailer is properly closed.
9. For sending through googlemail (and presumably gmail), use TLS
10. Note that the 'add_html_header' option adds only the DOCTYPE bits - not the <head>....</head> section
Possible Enhancements
---------------------
1. Support other fields:
ContentType
Encoding - ???. Defaults to 8-bit
Preferences used:
$pref['mailer'] - connection type - SMTP, sendmail etc
$pref['mail_options'] - NEW - general mailing options
textonly - if true, defaults to plain text emails
hostname=text - used in Message ID and received headers, and default Helo string. (Otherwise server-related default used)
$pref['mail_log_options'] - NEW. Logging options (also used in mailout_process). Comma-separated list of values
1 - logenable - numeric value 0..3 controlling logging to a text file
2 - add_email - if '1', the detail of the email is logged as well
$pref['smtp_server'] |
$pref['smtp_username'] | Server details. USed for POP3 server if POP before SMTP authorisation
$pref['smtp_password'] |
$pref['smtp_keepalive'] - deprecated in favour of option - flag
$pref['smtp_pop3auth'] - deprecated in favour of option - POP before SMTP authorisation flag
$pref['smtp_options'] - NEW - comma separated list:
keepalive - If active, bulk email send keeps the SMTP connection open, closing it every $pref['mail_pause'] emails
useVERP - formats return path to facilitate bounce processing
secure=[TLS|SSL] - enable secure authorisation by TLS or SSL
pop3auth - enable POP before SMTP authorisation
helo=text - Alternative Helo string
$pref['sendmail'] - path to sendmail
$pref['mail_pause'] - number of emails to send before pause
$pref['mail_pausetime'] - time to pause
$pref['mail_bounce_email'] - 'reply to' address
$pref['mail_bounce_pop3']
$pref['mail_bounce_user']
$pref['mail_bounce_pass']
Usage
=====
1. Create new object of the correct class
2. Set up everything - to/from/email etc
3. Call create_connection()
4. Call send_mail()
+----------------------------------------------------------------------------+
*/
if (!defined('e107_INIT')) { exit; }
//define('MAIL_DEBUG',true);
//define('LOG_CALLER', true);
//require_once(e_HANDLER.'phpmailer/class.phpmailer.php');
//require_once(e_HANDLER.'phpmailer/class.smtp.php');
//require_once(e_HANDLER.'phpmailer/PHPMailerAutoload.php');
use PHPMailer\PHPMailer\PHPMailer;
// use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\POP3;
use PHPMailer\PHPMailer\Exception;
require_once(e_HANDLER.'vendor/autoload.php');
// Directory for log (if enabled)
define('MAIL_LOG_PATH',e_LOG);
/**
*
*/
class e107Email extends PHPMailer
{
private $general_opts = array();
private $logEnable = 2; // 0 = log disabled, 1 = 'dry run' (debug and log, no send). 2 = 'log all' (send, and log result)
/** @var resource */
private $logHandle = false; // Save handle of log file if opened
private $localUseVerp = false; // Use our own variable - PHPMailer one doesn't work with all mailers
private $save_bouncepath = ''; // Used with VERP
private $add_email = 0; // 1 includes email detail in log (if logging enabled, of course)
private $allow_html = 1; // Flag for HTML conversion - '1' = default, false = disable, true = force.
private $add_HTML_header = false; // If true, inserts a standard HTML header at the front of the HTML part of the email (set false for BC)
private $SendCount = 0; // Keep track of how many emails sent since last SMTP open/connect (used for SMTP KeepAlive)
private $TotalSent = 0; // Info might be of interest
private $TotalErrors = 0; // Count errors in sending emails
private $pause_amount = 10; // Number of emails to send before pausing/resetting (or closing if SMTPkeepAlive set)
private $pause_time = 1; // Time to pause after sending a block of emails
public $legacyBody = false; // true enables legacy conversion of plain text body to HTML in HTML emails
private $debug = false; // echos various debug info when set to true.
private $pref = array(); // Store code prefs.
private $previewMode = false;
private $previewAttachments = array();
private $overrides = array(
// Legacy // New
'SMTPDebug' => 'SMTPDebug',
'subject' => 'subject',
'email_sender_email' => 'sender_email',
'email_sender_name' => 'sender_name',
'email_replyto' => 'replyto',
'send_html' => 'html',
'email_attach' => 'attachment',
'email_copy_to' => 'cc',
'email_bcopy_to' => 'bcc',
'bouncepath' => 'bouncepath',
'returnreceipt' => 'returnreceipt',
'email_priority' => 'priority',
'extra_header' => 'extra_header',
'wordwrap' => 'wordwrap',
'split' => 'split',
'smtp_server' => 'smtp_server',
'smtp_username' => 'smtp_username',
'smtp_password' => 'smtp_password',
'smtp_port' => 'smtp_port',
);
/**
* Constructor sets up all the global options, and sensible defaults - it should be the only place the prefs are accessed
*
* @var array|boolean $overrides - array of values which override mail-related prefs. Key is the same as the corresponding pref.
* - second batch of keys can preset values configurable through the arraySet() method
* @return null
*/
public function __construct($overrides = false)
{
parent::__construct(false); // Parent constructor - no exceptions for now
$pref = e107::pref('core');
$tp = e107::getParser();
if(defined('MAIL_DEBUG'))
{
$this->debug = true;
}
else
{
$this->Debugoutput = 'handlePHPMailerDebug';
}
$this->pref = $pref;
$this->CharSet = 'utf-8';
$this->setLanguage(CORE_LC);
if (($overrides === false) || !is_array($overrides))
{
$overrides = array();
}
foreach (array('mailer', 'smtp_server', 'smtp_username', 'smtp_password', 'smtp_port', 'sendmail', 'siteadminemail', 'siteadmin') as $k)
{
if (!isset($overrides[$k]))
{
$overrides[$k] = varset($pref[$k]);
}
}
if(strpos($overrides['smtp_server'],':')!== false)
{
list($smtpServer,$smtpPort) = explode(":", $overrides['smtp_server']);
$overrides['smtp_server'] = $smtpServer;
}
else
{
$smtpPort = varset($overrides['smtp_port'], 25);
}
$this->pause_amount = varset($pref['mail_pause'], 10);
$this->pause_time = varset($pref['mail_pausetime'], 1);
$this->allow_html = varset($pref['mail_sendstyle'],'textonly') == 'texthtml' ? true : 1;
if (vartrue($pref['mail_options'])) $this->general_opts = explode(',',$pref['mail_options'],'');
if ($this->debug)
{
echo 'Mail_options: '.$pref['mail_options'].' Count: '.count($this->general_opts).'<br />';
}
foreach ($this->general_opts as $k => $v)
{
$v = trim($v);
$this->general_opts[$k] = $v;
if (strpos($v,'hostname') === 0)
{
list(,$this->Hostname) = explode('=',$v);
if ($this->debug) echo "Host name set to: {$this->Hostname}<br />";
}
}
list($this->logEnable,$this->add_email) = explode(',',varset($pref['mail_log_options'],'0,0'));
switch ($overrides['mailer'])
{
case 'smtp' :
$smtp_options = array();
$temp_opts = explode(',',varset($pref['smtp_options'],''));
if (vartrue($overrides ['smtp_pop3auth'])) $temp_opts[] = 'pop3auth'; // Legacy option - remove later
if (vartrue($pref['smtp_keepalive'])) $temp_opts[] = 'keepalive'; // Legacy option - remove later
foreach ($temp_opts as $k=>$v)
{
if (strpos($v,'=') !== false)
{
list($v,$k) = explode('=',$v,2);
$smtp_options[trim($v)] = trim($k);
}
else
{
$smtp_options[trim($v)] = true; // Simple on/off option
}
}
unset($temp_opts);
$this->isSMTP(); // Enable SMTP functions
if (vartrue($smtp_options['helo'])) $this->Helo = $smtp_options['helo'];
if (isset($smtp_options['pop3auth'])) // We've made sure this is set
{ // Need POP-before-SMTP authorisation
// require_once(e_HANDLER.'phpmailer/class.pop3.php');
$pop = new POP3();
$pop->authorise($overrides['smtp_server'], 110, 30, $overrides['smtp_username'], $overrides['smtp_password'], 1);
}
$this->Mailer = 'smtp';
$this->localUseVerp = isset($smtp_options['useVERP']);
if (isset($smtp_options['secure']))
{
switch ($smtp_options['secure'])
{
case 'TLS' :
$this->SMTPSecure = 'tls';
$this->Port = ($smtpPort != 465) ? $smtpPort : 25; // Can also use port 587, and maybe even 25
break;
case 'SSL' :
$this->SMTPSecure = 'ssl';
$this->Port = ($smtpPort != 587) ? $smtpPort : 465;
break;
default :
if ($this->debug) echo "Invalid option: {$smtp_options['secure']}<br />";
}
}
$this->SMTPKeepAlive = varset($smtp_options['keepalive'],false); // ***** Control this
$this->Host = $overrides['smtp_server'];
if($overrides['smtp_username'] && $overrides['smtp_password'])
{
$this->SMTPAuth = (!isset($smtp_options['pop3auth']));
$this->Username = $overrides['smtp_username'];
$this->Password = $overrides['smtp_password'];
}
break;
case 'sendmail' :
$this->Mailer = 'sendmail';
$this->Sendmail = ($overrides['sendmail']) ? $overrides['sendmail'] : '/usr/sbin/sendmail -t -i -r '.vartrue($pref['replyto_email'],$overrides['siteadminemail']);
break;
case 'php' :
$this->Mailer = 'mail';
break;
}
$this->FromName = $tp->toHTML(vartrue($pref['replyto_name'],$overrides['siteadmin']),'','RAWTEXT');
$this->From = $tp->toHTML(vartrue($pref['replyto_email'],$overrides['siteadminemail']),'','RAWTEXT');
$this->WordWrap = 76; // Set a sensible default
$this->Sender = (!empty($pref['mail_bounce_email'])) ? $pref['mail_bounce_email'] : $this->From;
$pref['mail_dkim'] = 1;
$privatekeyfile = e_SYSTEM.'dkim_private.key';
if($pref['mail_dkim'] && is_readable($privatekeyfile))
{
$this->DKIM_domain = e_DOMAIN; // 'example.com';
$this->DKIM_private = $privatekeyfile;
$this->DKIM_selector = 'phpmailer';
$this->DKIM_passphrase = ''; //key is not encrypted
$this->DKIM_identifier = $this->From;
}
// Now look for any overrides - slightly cumbersome way of doing it, but does give control over what can be set from here
// Options are those accepted by the arraySet() method.
if(!empty($overrides))
{
foreach ($this->overrides as $key =>$opt)
{
if (isset($overrides[$key]))
{
$this->arraySet(array($opt => $overrides[$key]));
}
elseif(!empty($overrides[$opt]))
{
$this->arraySet(array($opt => $overrides[$opt]));
}
}
}
return null;
}
/**
* Set log level
* @param int $level 0|1|2
* @param int $emailDetails 0|1
* @return object e107Email
*/
public function logEnable($level, $emailDetails = null)
{
$this->logEnable = (int) $level;
if(null !== $this->add_email)
{
$this->add_email = (int) $emailDetails;
}
return $this;
}
/**
* Disable log completely
* @return object e107Email
*/
public function logDisable()
{
$this->logEnable = 0;
$this->add_email = 0;
return $this;
}
/**
* Format 'to' address and name
*
* @param string $email - email address of recipient
* @param string $to - name of recipient
* @return string in form: Fred Bloggs<[email protected]>
*/
public function makePrintableAddress($email,$to)
{
$to = trim($to);
$email = trim($email);
return $to.' <'.$email.'>';
}
/**
* Log functions - write to a log file
* Each entry logged to a separate line
*
* @param bool $logInfo
* @return null
*/
protected function openLog($logInfo = true)
{
if ($this->logEnable && ($this->logHandle === false))
{
$logFileName = MAIL_LOG_PATH.'mailoutlog.log';
$this->logHandle = fopen($logFileName, 'a'); // Always append to file
}
if ($this->logHandle !== false)
{
fwrite($this->logHandle,"\n\n=====".date('H:i:s y.m.d')."----------------------------------------------------------------=====\r\n");
if ($logInfo)
{
fwrite($this->logHandle,' Mailer opened by '.USERNAME." - ID: {$this->MessageID}. Subject: {$this->Subject} Log action: {$this->logEnable}\r\n");
if ($this->add_email)
{
fwrite($this->logHandle, 'From: '.$this->From.' ('.$this->FromName.")\r\n");
fwrite($this->logHandle, 'Sender: '.$this->Sender."\r\n");
fwrite($this->logHandle, 'Subject: '.$this->Subject."\r\n");
// Following are private variables ATM
// fwrite($this->logHandle, 'CC: '.$email_info['copy_to']."\r\n");
// fwrite($this->logHandle, 'BCC: '.$email_info['bcopy_to']."\r\n");
// fwrite($this->logHandle, 'Attach: '.$attach."\r\n");
fwrite($this->logHandle, 'Body: '.$this->Body."\r\n");
fwrite($this->logHandle,"-----------------------------------------------------------\r\n");
}
}
if (defined('LOG_CALLER'))
{
$temp = debug_backtrace();
foreach ($temp as $t)
{
if (!isset($t['class']) || ($t['class'] != 'e107Email'))
{
fwrite($this->logHandle, print_a($t,true)."\r\n"); // Found the caller
break;
}
}
}
}
return null;
}
/**
* Add a line to log file - time/date is prepended, and CRLF is appended
*
* @param string $text - line to add
* @return null
*/
protected function logLine($text)
{
if ($this->logEnable && ($this->logHandle > 0))
{
fwrite($this->logHandle,date('H:i:s y.m.d').' - '.$text."\r\n");
}
return null;
}
/**
* Close log
*/
protected function closeLog()
{
if ($this->logEnable && ($this->logHandle > 0))
{
fclose($this->logHandle);
}
}
/**
* Add a list of addresses to one of the address lists.
* @param string $list - 'to', 'replyto', 'cc', 'bcc'
* @param string $addresses - comma separated
* @param string $names - either a single name (used for all addresses) or a comma-separated list corresponding to the address list
* If the name field for an entry is blank, or there are not enough entries, the address is substituted
* @return bool true if list accepted, false if invalid list name
*/
public function AddAddressList($list = 'to',$addresses='',$names = '')
{
$list = trim(strtolower($list));
$tmp = explode(',',$addresses);
if (strpos($names,',') === false)
{
$names = array_fill(0,count($tmp),$names); // Same value for all addresses
}
else
{
$names = explode(',',$names);
}
foreach($tmp as $k => $adr)
{
$to_name = ($names[$k]) ? $names[$k] : $adr;
switch ($list)
{
case 'to' :
try
{
$this->addAddress($adr, $to_name);
}
catch (Exception $e)
{
$this->logLine($e->getMessage());
}
break;
case 'replyto' :
try
{
$this->addReplyTo($adr, $to_name);
}
catch (Exception $e)
{
$this->logLine($e->getMessage());
}
break;
case 'cc' :
if($this->Mailer == 'mail')
{
$this->addCustomHeader('Cc: '.$adr);
}
else
{
try
{
$this->addCC($adr, $to_name);
}
catch (Exception $e)
{
$this->logLine($e->getMessage());
}
}
break;
case 'bcc' :
if($this->Mailer == 'mail')
{
$this->addCustomHeader('Bcc: '.$adr);
}
else
{
try
{
$this->addBCC($adr, $to_name);
}
catch (Exception $e)
{
$this->logLine($e->getMessage());
}
}
break;
default :
return false;
}
}
return true;
}
/**
* Create email body, primarily using the inbuilt functionality of phpmailer
*
* @param string $message
* @param boolean|int $want_HTML determines whether an HTML part of the email is created. 1 uses default setting for HTML part. Set true to enable, false to disable
* @param boolean $add_HTML_header - if true, a standard HTML header is added to the front of the HTML part
*
* @return null
*/
public function makeBody($message,$want_HTML = 1, $add_HTML_header = false)
{
switch (varset($this->general_opts['textonly'],'off'))
{
case 'pref' : // Disable HTML as default
if ($want_HTML == 1) $want_HTML = false;
break;
case 'force' : // Always disable HTML
$want_HTML = false;
break;
}
$message = str_replace("\t", "", $message); // filter out tabs from templates;
if ($want_HTML !== false)
{
// $message = e107::getParser()->toHTML("[html]".$message."[/html]",true); // using toHtml will break media attachment links. (need to retain {e_XXXX )
if ($this->debug) echo "Generating multipart email<br />";
if ($add_HTML_header)
{
$message = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n
<html xmlns='http://www.w3.org/1999/xhtml' lang='en' >\n".$message;
}
// !preg_match('/<(table|div|font|br|a|img|b)/i', $message)
if ($this->legacyBody && e107::getParser()->isHtml($message) != true) // Assume html if it includes one of these tags
{ // Otherwise assume its a plain text message which needs some conversion to render in HTML
if($this->debug == true)
{
echo 'Running legacyBody mode<br />';
}
$message = htmlspecialchars($message,ENT_QUOTES,$this->CharSet);
$message = preg_replace('%(http|ftp|https)(://\S+)%', '<a href="\1\2">\1\2</a>', $message);
$message = preg_replace('/([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&\/=]+)/i', '\\1<a href="http://\\2">\\2</a>', $message);
$message = preg_replace('/([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})/i', '<a href="mailto:\\1">\\1</a>', $message);
$message = str_replace("\r\n","\n",$message); // Handle alternative newline characters
$message = str_replace("\n\r","\n",$message); // Handle alternative newline characters
$message = str_replace("\r","\n",$message); // Handle alternative newline characters
$message = str_replace("\n", "<br />\n", $message);
}
$this->MsgHTML($message); // Theoretically this should do everything, including handling of inline images.
}
else
{ // generate the plain text as the sole part of the email
if ($this->debug) echo "Generating plain text email<br />";
if (strpos($message,'</style>') !== false)
{
$text = strstr($message,'</style>');
}
else
{
$text = $message;
}
$text = str_replace('<br />', "\n", $text);
$text = strip_tags(str_replace('<br>', "\n", $text));
// TODO: strip bbcodes here
$this->Body = $text;
$this->AltBody = ''; // Single part email
}
return null;
}
/**
* Add attachments to the current email - either a single one as a string, or an array
* Always sent in base64 encoding
*
* @param string|array $attachments - single attachment name as a string, or any number as an array
*
* @return null
*/
public function attach($attachments)
{
if (!$attachments) return;
if (!is_array($attachments)) $attachments = array($attachments);
// $mes = e107::getMessage();
foreach($attachments as $attach)
{
$tempName = basename($attach);
if(is_readable($attach) && $tempName) // First parameter is complete path + filename; second parameter is 'name' of file to send
{
if($this->previewMode === true)
{
$this->previewAttachments[] = array('file'=>$attach, 'status'=>true);
}
else
{
$ext = pathinfo($attach, PATHINFO_EXTENSION);
try
{
$this->addAttachment($attach, $tempName,'base64',$this->_mime_types($ext));
}
catch (Exception $e)
{
$this->logLine($e->getMessage());
}
}
}
elseif($this->previewMode === true)
{
$this->previewAttachments[] = array('file'=>$attach, 'status'=>false);
}
}
return null;
}
/**
* Add inline images (should usually be handled automatically by PHPMailer)
*
* @param string $inline - comma separated list of file names
*/
function addInlineImages($inline)
{
if(!$inline) return;
$tmp = explode(',',$inline);
foreach($tmp as $inline_img)
{
if(is_readable($inline_img) && !is_dir($inline_img))
{
$ext = pathinfo($inline_img, PATHINFO_EXTENSION);
try
{
$this->addEmbeddedImage($inline_img, md5($inline_img), basename($inline_img),'base64',$this->_mime_types($ext));
}
catch (Exception $e)
{
$this->logLine($e->getMessage());
}
}
}
}
/**
* Preview the BODY of an email
* @param $eml - array.
* @return string
*/
public function preview($eml)
{
$this->previewMode = true;
// $mes = e107::getMessage();
if (count($eml))
{
if($error = $this->arraySet($eml)) // Set parameters from list
{
return $error;
}
}
$text = $this->Body;
if($eml['template'] == 'textonly')
{
$text = strip_tags($text);
}
if(!empty($this->previewAttachments))
{
$text .= "<hr />Attachments:";
foreach($this->previewAttachments as $val)
{
$text .= "<div>".$val['file']." - ";
$text .= ($val['status'] !== true) ? "Not Found" : "OK";
$text .= "</div>";
}
}
if($eml['template'] == 'texthtml' || $eml['template'] == 'textonly' )
{
$text = "<body style='background-color:#FFFFFF;'>".$text."</body>";
}
return $text;
}
/**
* @param $eml
* @return mixed
*/
function processShortcodes($eml)
{
$tp = e107::getParser();
$mediaParms = array();
if(strpos($eml['templateHTML']['body'], '{MEDIA') !==false )
{
// check for media sizing.
if(preg_match_all('/\{MEDIA([\d]): w=([\d]*)\}/', $eml['templateHTML']['body'], $match))
{
foreach($match[1] as $k=>$num)
{
//$key = $match[1][$k];
$mediaParms[$num]['w'] = $match[2][$k];
}
}
}
/*
if(!empty($eml['html']) || strip_tags($eml['template']) != $eml['template']) // HTML Email.
{
$eml['shortcodes']['BODY'] = !empty($eml['body']) ? $eml['body'] : ''; // using toEmail() on html templates adds unnecessary <br /> to code.
}
else // Plain Text Email.
{
$eml['shortcodes']['BODY'] = !empty($eml['body']) ? $tp->toEmail($eml['body']) : '';
}
*/
$eml['shortcodes']['BODY'] = !empty($eml['body']) ? $eml['body'] : ''; // $tp->toEmail($eml['body']) : '';
$eml['shortcodes']['SUBJECT'] = !empty($eml['subject']) ? $eml['subject'] : '';
$eml['shortcodes']['THEME'] = ($this->previewMode == true) ? e_THEME_ABS.$this->pref['sitetheme'].'/' : e_THEME.$this->pref['sitetheme'].'/'; // Always use front-end theme path.
if(!empty($eml['media']) && is_array($eml['media']))
{
foreach($eml['media'] as $k=>$val)
{
if(vartrue($val['path']))
{
$nk = ($k+1);
$id = 'MEDIA'.$nk;
if($tp->isVideo($val['path']))
{
$eml['shortcodes'][$id] = "<div class='media media-video'>".$tp->toVideo($val['path'],array('thumb'=>'email'))."</div>";
}
else
{
$size = isset($mediaParms[$nk]) ? "?w=".$mediaParms[$nk]['w'] : '';
//echo $nk.": ".$val['path'].$size."<br />";
$eml['shortcodes'][$id] = "<div class='media media-image'><img class='img-responsive img-fluid ".strtolower($id)."' src='".$val['path'].$size."' alt='' /></div>";
}
}
}
}
return $eml['shortcodes'];
}
/**
* Sets one or more parameters from an array. See @see{sendEmail()} for list of parameters
* Where parameter not present, doesn't change it - so can repeatedly call this function for bulk mailing, or to build up the list
* (Note that there is no requirement to use this method for everything; parameters can be set by mixing this method with individual setting)
*
* @param array $eml - list of parameters to set/change. Key is parameter name. @see{sendEmail()} for list of parameters
*
* @return int zero if no errors detected
*/
public function arraySet($eml)
{
$tp = e107::getParser();
$tmpl = null;
// Cleanup legacy key names. ie. remove 'email_' prefix.
foreach($eml as $k=>$v)
{
if(substr($k,0,6) == 'email_')
{
$nkey = substr($k,6);
$eml[$nkey] = $v;
unset($eml[$k]);
}
}
if(!empty($eml['template'])) // @see e107_core/templates/email_template.php
{
require_once(e_LANGUAGEDIR.e_LANGUAGE."/admin/lan_users.php"); // do not use e107::lan etc.
if(is_array($eml['template']) && !empty($eml['template']['plugin']) && !empty($eml['template']['name']) && !empty($eml['template']['key']))
{
$tmpl = e107::getTemplate($eml['template']['plugin'],$eml['template']['name'], $eml['template']['key']);
}
else
{
$tmpl = e107::getCoreTemplate('email', $eml['template'], 'front', true);
}
if(!empty($tmpl)) //FIXME - Core template is failing with template 'notify'. Works with theme template. Issue with core template registry?
{
$eml['templateHTML'] = $tmpl;
$eml['shortcodes'] = $this->processShortcodes($eml);
if(is_string($eml['template']))
{
$eml['shortcodes']['_WRAPPER_'] = 'email/'.$eml['template'];
}
$emailBody = varset($tmpl['header']). str_replace('{BODY}', $eml['body'], $tmpl['body']) . varset($tmpl['footer']);
$eml['body'] = $tp->parseTemplate($emailBody, true, $eml['shortcodes']);
// $eml['body'] = ($tp->toEmail($tmpl['header']). str_replace('{BODY}', $eml['body'], $tmpl['body']). $tp->toEmail($tmpl['footer']));
if($this->debug)
{
// echo "<h4>e107Email::arraySet() - line ".__LINE__."</h4>";
var_dump($eml['shortcodes']);
var_dump($this->Subject);
// print_a($tmpl);
}
unset($eml['add_html_header']); // disable other headers when template is used.
$this->Subject = $tp->parseTemplate(varset($tmpl['subject'],'{SUBJECT}'), true, varset($eml['shortcodes'],null));
if($this->debug)
{
var_dump($this->Subject);
}
}
else
{
if($this->debug)
{
echo "<h4>Couldn't find email template: ".print_r($eml['template'],true)."</h4>";
}
// $emailBody = $eml['body'];
if (vartrue($eml['subject'])) $this->Subject = $tp->parseTemplate($eml['subject'], true, varset($eml['shortcodes'],null));
e107::getMessage()->addDebug("Couldn't find email template: ".$eml['template']);
}
}
else
{
if (vartrue($eml['subject'])) $this->Subject = $tp->parseTemplate($eml['subject'], true, varset($eml['shortcodes'],null));
// $eml['body'] = ($tp->toEmail($tmpl['header']). str_replace('{BODY}', $eml['body'], $tmpl['body']). $tp->toEmail($tmpl['footer']));
}
$this->Subject = str_replace("'", "'", $this->Subject);
// Perform Override from template.
foreach($this->overrides as $k=>$v)
{
if(!empty($tmpl[$v]))
{
$eml[$v] = $tmpl[$v];
}
}
$identifier = deftrue('MAIL_IDENTIFIER', 'X-e107-id');
if (isset($eml['SMTPDebug'])) { $this->SMTPDebug = $eml['SMTPDebug']; } // 'false' is a valid value!
if (!empty($eml['sender_email']) && !empty($eml['sender_email']))
{
$this->setFrom($eml['sender_email'], $eml['sender_name']);
}
else
{
if (!empty($eml['sender_email'])) { $this->From = $eml['sender_email']; }
if (!empty($eml['sender_name'])) { $this->FromName = $eml['sender_name']; }
}