Passed
Push — master ( bbacda...9d4008 )
by Marcus
43:43
created

src/PHPMailer.php (3 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * PHPMailer - PHP email creation and transport class.
4
 * PHP Version 5.5
5
 *
6
 * @package   PHPMailer
7
 * @see       https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
8
 * @author    Marcus Bointon (Synchro/coolbru) <[email protected]>
9
 * @author    Jim Jagielski (jimjag) <[email protected]>
10
 * @author    Andy Prevost (codeworxtech) <[email protected]>
11
 * @author    Brent R. Matzelle (original founder)
12
 * @copyright 2012 - 2016 Marcus Bointon
13
 * @copyright 2010 - 2012 Jim Jagielski
14
 * @copyright 2004 - 2009 Andy Prevost
15
 * @license   http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
16
 * @note      This program is distributed in the hope that it will be useful - WITHOUT
17
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18
 * FITNESS FOR A PARTICULAR PURPOSE.
19
 */
20
21
namespace PHPMailer\PHPMailer;
22
23
/**
24
 * PHPMailer - PHP email creation and transport class.
25
 *
26
 * @package PHPMailer
27
 * @author  Marcus Bointon (Synchro/coolbru) <[email protected]>
28
 * @author  Jim Jagielski (jimjag) <[email protected]>
29
 * @author  Andy Prevost (codeworxtech) <[email protected]>
30
 * @author  Brent R. Matzelle (original founder)
31
 */
32
class PHPMailer
33
{
34
    /**
35
     * Email priority.
36
     * Options: null (default), 1 = High, 3 = Normal, 5 = low.
37
     * When null, the header is not set at all.
38
     *
39
     * @var integer
40
     */
41
    public $Priority = null;
42
43
    /**
44
     * The character set of the message.
45
     *
46
     * @var string
47
     */
48
    public $CharSet = 'iso-8859-1';
49
50
    /**
51
     * The MIME Content-type of the message.
52
     *
53
     * @var string
54
     */
55
    public $ContentType = 'text/plain';
56
57
    /**
58
     * The message encoding.
59
     * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
60
     *
61
     * @var string
62
     */
63
    public $Encoding = '8bit';
64
65
    /**
66
     * Holds the most recent mailer error message.
67
     *
68
     * @var string
69
     */
70
    public $ErrorInfo = '';
71
72
    /**
73
     * The From email address for the message.
74
     *
75
     * @var string
76
     */
77
    public $From = 'root@localhost';
78
79
    /**
80
     * The From name of the message.
81
     *
82
     * @var string
83
     */
84
    public $FromName = 'Root User';
85
86
    /**
87
     * The envelope sender of the message.
88
     * This will usually be turned into a Return-Path header by the receiver,
89
     * and is the address that bounces will be sent to.
90
     * If not empty, will be passed via `-f` to sendmail or as the 'MAIL FROM' value over SMTP.
91
     *
92
     * @var string
93
     */
94
    public $Sender = '';
95
96
    /**
97
     * The Subject of the message.
98
     *
99
     * @var string
100
     */
101
    public $Subject = '';
102
103
    /**
104
     * An HTML or plain text message body.
105
     * If HTML then call isHTML(true).
106
     *
107
     * @var string
108
     */
109
    public $Body = '';
110
111
    /**
112
     * The plain-text message body.
113
     * This body can be read by mail clients that do not have HTML email
114
     * capability such as mutt & Eudora.
115
     * Clients that can read HTML will view the normal Body.
116
     *
117
     * @var string
118
     */
119
    public $AltBody = '';
120
121
    /**
122
     * An iCal message part body.
123
     * Only supported in simple alt or alt_inline message types
124
     * To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator
125
     *
126
     * @see http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
127
     * @see http://kigkonsult.se/iCalcreator/
128
     * @var string
129
     */
130
    public $Ical = '';
131
132
    /**
133
     * The complete compiled MIME message body.
134
     *
135
     * @var string
136
     */
137
    protected $MIMEBody = '';
138
139
    /**
140
     * The complete compiled MIME message headers.
141
     *
142
     * @var string
143
     */
144
    protected $MIMEHeader = '';
145
146
    /**
147
     * Extra headers that createHeader() doesn't fold in.
148
     *
149
     * @var string
150
     */
151
    protected $mailHeader = '';
152
153
    /**
154
     * Word-wrap the message body to this number of chars.
155
     * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
156
     * @see static::STD_LINE_LENGTH
157
     *
158
     * @var integer
159
     */
160
    public $WordWrap = 0;
161
162
    /**
163
     * Which method to use to send mail.
164
     * Options: "mail", "sendmail", or "smtp".
165
     *
166
     * @var string
167
     */
168
    public $Mailer = 'mail';
169
170
    /**
171
     * The path to the sendmail program.
172
     *
173
     * @var string
174
     */
175
    public $Sendmail = '/usr/sbin/sendmail';
176
177
    /**
178
     * Whether mail() uses a fully sendmail-compatible MTA.
179
     * One which supports sendmail's "-oi -f" options.
180
     *
181
     * @var boolean
182
     */
183
    public $UseSendmailOptions = true;
184
185
    /**
186
     * The email address that a reading confirmation should be sent to, also known as read receipt.
187
     *
188
     * @var string
189
     */
190
    public $ConfirmReadingTo = '';
191
192
    /**
193
     * The hostname to use in the Message-ID header and as default HELO string.
194
     * If empty, PHPMailer attempts to find one with, in order,
195
     * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value
196
     * 'localhost.localdomain'.
197
     *
198
     * @var string
199
     */
200
    public $Hostname = '';
201
202
    /**
203
     * An ID to be used in the Message-ID header.
204
     * If empty, a unique id will be generated.
205
     * You can set your own, but it must be in the format "<id@domain>",
206
     * as defined in RFC5322 section 3.6.4 or it will be ignored.
207
     * @see https://tools.ietf.org/html/rfc5322#section-3.6.4
208
     *
209
     * @var string
210
     */
211
    public $MessageID = '';
212
213
    /**
214
     * The message Date to be used in the Date header.
215
     * If empty, the current date will be added.
216
     *
217
     * @var string
218
     */
219
    public $MessageDate = '';
220
221
    /**
222
     * SMTP hosts.
223
     * Either a single hostname or multiple semicolon-delimited hostnames.
224
     * You can also specify a different port
225
     * for each host by using this format: [hostname:port]
226
     * (e.g. "smtp1.example.com:25;smtp2.example.com").
227
     * You can also specify encryption type, for example:
228
     * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
229
     * Hosts will be tried in order.
230
     *
231
     * @var string
232
     */
233
    public $Host = 'localhost';
234
235
    /**
236
     * The default SMTP server port.
237
     *
238
     * @var integer
239
     */
240
    public $Port = 25;
241
242
    /**
243
     * The SMTP HELO of the message.
244
     * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find
245
     * one with the same method described above for $Hostname.
246
     *
247
     * @var string
248
     * @see PHPMailer::$Hostname
249
     */
250
    public $Helo = '';
251
252
    /**
253
     * What kind of encryption to use on the SMTP connection.
254
     * Options: '', 'ssl' or 'tls'
255
     *
256
     * @var string
257
     */
258
    public $SMTPSecure = '';
259
260
    /**
261
     * Whether to enable TLS encryption automatically if a server supports it,
262
     * even if `SMTPSecure` is not set to 'tls'.
263
     * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
264
     *
265
     * @var boolean
266
     */
267
    public $SMTPAutoTLS = true;
268
269
    /**
270
     * Whether to use SMTP authentication.
271
     * Uses the Username and Password properties.
272
     *
273
     * @var boolean
274
     * @see PHPMailer::$Username
275
     * @see PHPMailer::$Password
276
     */
277
    public $SMTPAuth = false;
278
279
    /**
280
     * Options array passed to stream_context_create when connecting via SMTP.
281
     *
282
     * @var array
283
     */
284
    public $SMTPOptions = [];
285
286
    /**
287
     * SMTP username.
288
     *
289
     * @var string
290
     */
291
    public $Username = '';
292
293
    /**
294
     * SMTP password.
295
     *
296
     * @var string
297
     */
298
    public $Password = '';
299
300
    /**
301
     * SMTP auth type.
302
     * Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2, attempted in that order if not specified
303
     *
304
     * @var string
305
     */
306
    public $AuthType = '';
307
308
    /**
309
     * An instance of the PHPMailer OAuth class.
310
     *
311
     * @var OAuth
312
     */
313
    protected $oauth = null;
314
315
    /**
316
     * The SMTP server timeout in seconds.
317
     * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
318
     *
319
     * @var integer
320
     */
321
    public $Timeout = 300;
322
323
    /**
324
     * SMTP class debug output mode.
325
     * Debug output level.
326
     * Options:
327
     * * `0` No output
328
     * * `1` Commands
329
     * * `2` Data and commands
330
     * * `3` As 2 plus connection status
331
     * * `4` Low-level data output
332
     *
333
     * @var integer
334
     * @see SMTP::$do_debug
335
     */
336
    public $SMTPDebug = 0;
337
338
    /**
339
     * How to handle debug output.
340
     * Options:
341
     * * `echo` Output plain-text as-is, appropriate for CLI
342
     * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
343
     * * `error_log` Output to error log as configured in php.ini
344
     * By default PHPMailer will use `echo` if run from a `cli` or `cli-server` SAPI, `html` otherwise.
345
     * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
346
     * <code>
347
     * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
348
     * </code>
349
     * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug`
350
     * level output is used:
351
     * <code>
352
     * $mail->Debugoutput = new myPsr3Logger;
353
     * </code>
354
     * @var string|callable|\Psr\Log\LoggerInterface
355
     * @see SMTP::$Debugoutput
356
     */
357
    public $Debugoutput = 'echo';
358
359
    /**
360
     * Whether to keep SMTP connection open after each message.
361
     * If this is set to true then to close the connection
362
     * requires an explicit call to smtpClose().
363
     *
364
     * @var boolean
365
     */
366
    public $SMTPKeepAlive = false;
367
368
    /**
369
     * Whether to split multiple to addresses into multiple messages
370
     * or send them all in one message.
371
     * Only supported in `mail` and `sendmail` transports, not in SMTP.
372
     *
373
     * @var boolean
374
     */
375
    public $SingleTo = false;
376
377
    /**
378
     * Storage for addresses when SingleTo is enabled.
379
     *
380
     * @var array
381
     */
382
    protected $SingleToArray = [];
383
384
    /**
385
     * Whether to generate VERP addresses on send.
386
     * Only applicable when sending via SMTP.
387
     *
388
     * @see https://en.wikipedia.org/wiki/Variable_envelope_return_path
389
     * @see http://www.postfix.org/VERP_README.html Postfix VERP info
390
     * @var boolean
391
     */
392
    public $do_verp = false;
393
394
    /**
395
     * Whether to allow sending messages with an empty body.
396
     *
397
     * @var boolean
398
     */
399
    public $AllowEmpty = false;
400
401
    /**
402
     * DKIM selector.
403
     *
404
     * @var string
405
     */
406
    public $DKIM_selector = '';
407
408
    /**
409
     * DKIM Identity.
410
     * Usually the email address used as the source of the email.
411
     *
412
     * @var string
413
     */
414
    public $DKIM_identity = '';
415
416
    /**
417
     * DKIM passphrase.
418
     * Used if your key is encrypted.
419
     *
420
     * @var string
421
     */
422
    public $DKIM_passphrase = '';
423
424
    /**
425
     * DKIM signing domain name.
426
     *
427
     * @example 'example.com'
428
     * @var     string
429
     */
430
    public $DKIM_domain = '';
431
432
    /**
433
     * DKIM private key file path.
434
     *
435
     * @var string
436
     */
437
    public $DKIM_private = '';
438
439
    /**
440
     * DKIM private key string.
441
     *
442
     * If set, takes precedence over `$DKIM_private`.
443
     * @var string
444
     */
445
    public $DKIM_private_string = '';
446
447
    /**
448
     * Callback Action function name.
449
     *
450
     * The function that handles the result of the send email action.
451
     * It is called out by send() for each email sent.
452
     *
453
     * Value can be any php callable: http://www.php.net/is_callable
454
     *
455
     * Parameters:
456
     *   boolean $result        result of the send action
457
     *   array   $to            email addresses of the recipients
458
     *   array   $cc            cc email addresses
459
     *   array   $bcc           bcc email addresses
460
     *   string  $subject       the subject
461
     *   string  $body          the email body
462
     *   string  $from          email address of sender
463
     *
464
     * @var string
465
     */
466
    public $action_function = '';
467
468
    /**
469
     * What to put in the X-Mailer header.
470
     * Options: An empty string for PHPMailer default, whitespace for none, or a string to use
471
     *
472
     * @var string
473
     */
474
    public $XMailer = '';
475
476
    /**
477
     * Which validator to use by default when validating email addresses.
478
     * May be a callable to inject your own validator, but there are several built-in validators.
479
     * The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option.
480
     *
481
     * @see PHPMailer::validateAddress()
482
     * @var string|callable
483
     */
484
    public static $validator = 'php';
485
486
    /**
487
     * An instance of the SMTP sender class.
488
     *
489
     * @var SMTP
490
     */
491
    protected $smtp = null;
492
493
    /**
494
     * The array of 'to' names and addresses.
495
     *
496
     * @var array
497
     */
498
    protected $to = [];
499
500
    /**
501
     * The array of 'cc' names and addresses.
502
     *
503
     * @var array
504
     */
505
    protected $cc = [];
506
507
    /**
508
     * The array of 'bcc' names and addresses.
509
     *
510
     * @var array
511
     */
512
    protected $bcc = [];
513
514
    /**
515
     * The array of reply-to names and addresses.
516
     *
517
     * @var array
518
     */
519
    protected $ReplyTo = [];
520
521
    /**
522
     * An array of all kinds of addresses.
523
     * Includes all of $to, $cc, $bcc
524
     *
525
     * @var array
526
     * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc
527
     */
528
    protected $all_recipients = [];
529
530
    /**
531
     * An array of names and addresses queued for validation.
532
     * In send(), valid and non duplicate entries are moved to $all_recipients
533
     * and one of $to, $cc, or $bcc.
534
     * This array is used only for addresses with IDN.
535
     *
536
     * @var array
537
     * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc
538
     * @see PHPMailer::$all_recipients
539
     */
540
    protected $RecipientsQueue = [];
541
542
    /**
543
     * An array of reply-to names and addresses queued for validation.
544
     * In send(), valid and non duplicate entries are moved to $ReplyTo.
545
     * This array is used only for addresses with IDN.
546
     *
547
     * @var array
548
     * @see PHPMailer::$ReplyTo
549
     */
550
    protected $ReplyToQueue = [];
551
552
    /**
553
     * The array of attachments.
554
     *
555
     * @var array
556
     */
557
    protected $attachment = [];
558
559
    /**
560
     * The array of custom headers.
561
     *
562
     * @var array
563
     */
564
    protected $CustomHeader = [];
565
566
    /**
567
     * The most recent Message-ID (including angular brackets).
568
     *
569
     * @var string
570
     */
571
    protected $lastMessageID = '';
572
573
    /**
574
     * The message's MIME type.
575
     *
576
     * @var string
577
     */
578
    protected $message_type = '';
579
580
    /**
581
     * The array of MIME boundary strings.
582
     *
583
     * @var array
584
     */
585
    protected $boundary = [];
586
587
    /**
588
     * The array of available languages.
589
     *
590
     * @var array
591
     */
592
    protected $language = [];
593
594
    /**
595
     * The number of errors encountered.
596
     *
597
     * @var integer
598
     */
599
    protected $error_count = 0;
600
601
    /**
602
     * The S/MIME certificate file path.
603
     *
604
     * @var string
605
     */
606
    protected $sign_cert_file = '';
607
608
    /**
609
     * The S/MIME key file path.
610
     *
611
     * @var string
612
     */
613
    protected $sign_key_file = '';
614
615
    /**
616
     * The optional S/MIME extra certificates ("CA Chain") file path.
617
     *
618
     * @var string
619
     */
620
    protected $sign_extracerts_file = '';
621
622
    /**
623
     * The S/MIME password for the key.
624
     * Used only if the key is encrypted.
625
     *
626
     * @var string
627
     */
628
    protected $sign_key_pass = '';
629
630
    /**
631
     * Whether to throw exceptions for errors.
632
     *
633
     * @var boolean
634
     */
635
    protected $exceptions = false;
636
637
    /**
638
     * Unique ID used for message ID and boundaries.
639
     *
640
     * @var string
641
     */
642
    protected $uniqueid = '';
643
644
    /**
645
     * The PHPMailer Version number.
646
     *
647
     * @var string
648
     */
649
    const VERSION = '6.0.0';
650
651
    /**
652
     * Error severity: message only, continue processing.
653
     *
654
     * @var integer
655
     */
656
    const STOP_MESSAGE = 0;
657
658
    /**
659
     * Error severity: message, likely ok to continue processing.
660
     *
661
     * @var integer
662
     */
663
    const STOP_CONTINUE = 1;
664
665
    /**
666
     * Error severity: message, plus full stop, critical error reached.
667
     *
668
     * @var integer
669
     */
670
    const STOP_CRITICAL = 2;
671
672
    /**
673
     * SMTP RFC standard line ending.
674
     *
675
     * @var string
676
     */
677
    protected static $LE = "\r\n";
678
679
    /**
680
     * The maximum line length allowed by RFC 2822 section 2.1.1
681
     *
682
     * @var integer
683
     */
684
    const MAX_LINE_LENGTH = 998;
685
686
    /**
687
     * The lower maximum line length allowed by RFC 2822 section 2.1.1
688
     *
689
     * @var integer
690
     */
691
    const STD_LINE_LENGTH = 78;
692
693
    /**
694
     * Constructor.
695
     *
696
     * @param boolean $exceptions Should we throw external exceptions?
697
     */
698
    public function __construct($exceptions = null)
699
    {
700
        if (!is_null($exceptions)) {
701
            $this->exceptions = (boolean)$exceptions;
702
        }
703
        //Pick an appropriate debug output format automatically
704
        $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html');
705
    }
706
707
    /**
708
     * Destructor.
709
     */
710
    public function __destruct()
711
    {
712
        //Close any open SMTP connection nicely
713
        $this->smtpClose();
714
    }
715
716
    /**
717
     * Call mail() in a safe_mode-aware fashion.
718
     * Also, unless sendmail_path points to sendmail (or something that
719
     * claims to be sendmail), don't pass params (not a perfect fix,
720
     * but it will do)
721
     *
722
     * @param string $to To
723
     * @param string $subject Subject
724
     * @param string $body Message Body
725
     * @param string $header Additional Header(s)
726
     * @param ?string $params Params
727
     *
728
     * @return boolean
729
     */
730
    private function mailPassthru($to, $subject, $body, $header, $params)
731
    {
732
        //Check overloading of mail function to avoid double-encoding
733
        if (ini_get('mbstring.func_overload') & 1) {
734
            $subject = $this->secureHeader($subject);
735
        } else {
736
            $subject = $this->encodeHeader($this->secureHeader($subject));
737
        }
738
        //Calling mail() with null params breaks
739
        if (!$this->UseSendmailOptions or is_null($params)) {
740
            $result = @mail($to, $subject, $body, $header);
741
        } else {
742
            $result = @mail($to, $subject, $body, $header, $params);
743
        }
744
        return $result;
745
    }
746
747
    /**
748
     * Output debugging info via user-defined method.
749
     * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
750
     *
751
     * @param string $str
752
     *
753
     * @see PHPMailer::$Debugoutput
754
     * @see PHPMailer::$SMTPDebug
755
     */
756
    protected function edebug($str)
757
    {
758
        if ($this->SMTPDebug <= 0) {
759
            return;
760
        }
761
        //Is this a PSR-3 logger?
762
        if (is_a($this->Debugoutput, 'Psr\Log\LoggerInterface')) {
763
            $this->Debugoutput->debug($str);
764
            return;
765
        }
766
        //Avoid clash with built-in function names
767
        if (!in_array($this->Debugoutput, ['error_log', 'html', 'echo']) and is_callable($this->Debugoutput)) {
768
            call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
769
            return;
770
        }
771
        switch ($this->Debugoutput) {
772
            case 'error_log':
773
                //Don't output, just log
774
                error_log($str);
775
                break;
776
            case 'html':
777
                //Cleans up output a bit for a better looking, HTML-safe output
778
                echo htmlentities(
779
                    preg_replace('/[\r\n]+/', '', $str),
780
                    ENT_QUOTES,
781
                    'UTF-8'
782
                ), "<br>\n";
783
                break;
784
            case 'echo':
785
            default:
786
                //Normalize line breaks
787
                $str = preg_replace('/\r\n|\r/ms', "\n", $str);
788
                echo gmdate('Y-m-d H:i:s'),
789
                    "\t",
790
                    //Trim trailing space
791
                    trim(
792
                        //Indent for readability, except for trailing break
793
                        str_replace(
794
                            "\n",
795
                            "\n                   \t                  ",
796
                            trim($str)
797
                        )
798
                    ),
799
                    "\n";
800
        }
801
    }
802
803
    /**
804
     * Sets message type to HTML or plain.
805
     *
806
     * @param boolean $isHtml True for HTML mode.
807
     */
808
    public function isHTML($isHtml = true)
809
    {
810
        if ($isHtml) {
811
            $this->ContentType = 'text/html';
812
        } else {
813
            $this->ContentType = 'text/plain';
814
        }
815
    }
816
817
    /**
818
     * Send messages using SMTP.
819
     */
820
    public function isSMTP()
821
    {
822
        $this->Mailer = 'smtp';
823
    }
824
825
    /**
826
     * Send messages using PHP's mail() function.
827
     */
828
    public function isMail()
829
    {
830
        $this->Mailer = 'mail';
831
    }
832
833
    /**
834
     * Send messages using $Sendmail.
835
     */
836
    public function isSendmail()
837
    {
838
        $ini_sendmail_path = ini_get('sendmail_path');
839
840
        if (!stristr($ini_sendmail_path, 'sendmail')) {
841
            $this->Sendmail = '/usr/sbin/sendmail';
842
        } else {
843
            $this->Sendmail = $ini_sendmail_path;
844
        }
845
        $this->Mailer = 'sendmail';
846
    }
847
848
    /**
849
     * Send messages using qmail.
850
     */
851
    public function isQmail()
852
    {
853
        $ini_sendmail_path = ini_get('sendmail_path');
854
855
        if (!stristr($ini_sendmail_path, 'qmail')) {
856
            $this->Sendmail = '/var/qmail/bin/qmail-inject';
857
        } else {
858
            $this->Sendmail = $ini_sendmail_path;
859
        }
860
        $this->Mailer = 'qmail';
861
    }
862
863
    /**
864
     * Add a "To" address.
865
     *
866
     * @param string $address The email address to send to
867
     * @param string $name
868
     *
869
     * @return boolean true on success, false if address already used or invalid in some way
870
     */
871
    public function addAddress($address, $name = '')
872
    {
873
        return $this->addOrEnqueueAnAddress('to', $address, $name);
874
    }
875
876
    /**
877
     * Add a "CC" address.
878
     *
879
     * @param string $address The email address to send to
880
     * @param string $name
881
     *
882
     * @return boolean true on success, false if address already used or invalid in some way
883
     */
884
    public function addCC($address, $name = '')
885
    {
886
        return $this->addOrEnqueueAnAddress('cc', $address, $name);
887
    }
888
889
    /**
890
     * Add a "BCC" address.
891
     *
892
     * @param string $address The email address to send to
893
     * @param string $name
894
     *
895
     * @return boolean true on success, false if address already used or invalid in some way
896
     */
897
    public function addBCC($address, $name = '')
898
    {
899
        return $this->addOrEnqueueAnAddress('bcc', $address, $name);
900
    }
901
902
    /**
903
     * Add a "Reply-To" address.
904
     *
905
     * @param string $address The email address to reply to
906
     * @param string $name
907
     *
908
     * @return boolean true on success, false if address already used or invalid in some way
909
     */
910
    public function addReplyTo($address, $name = '')
911
    {
912
        return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);
913
    }
914
915
    /**
916
     * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer
917
     * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still
918
     * be modified after calling this function), addition of such addresses is delayed until send().
919
     * Addresses that have been added already return false, but do not throw exceptions.
920
     *
921
     * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
922
     * @param string $address The email address to send, resp. to reply to
923
     * @param string $name
924
     *
925
     * @throws Exception
926
     * @return boolean true on success, false if address already used or invalid in some way
927
     */
928
    protected function addOrEnqueueAnAddress($kind, $address, $name)
929
    {
930
        $address = trim($address);
931
        $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
932
        $pos = strrpos($address, '@');
933
        if (false === $pos) {
934
            // At-sign is missing.
935
            $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address";
936
            $this->setError($error_message);
937
            $this->edebug($error_message);
938
            if ($this->exceptions) {
939
                throw new Exception($error_message);
940
            }
941
            return false;
942
        }
943
        $params = [$kind, $address, $name];
944
        // Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
945
        if ($this->has8bitChars(substr($address, ++$pos)) and $this->idnSupported()) {
946
            if ('Reply-To' != $kind) {
947
                if (!array_key_exists($address, $this->RecipientsQueue)) {
948
                    $this->RecipientsQueue[$address] = $params;
949
                    return true;
950
                }
951
            } else {
952
                if (!array_key_exists($address, $this->ReplyToQueue)) {
953
                    $this->ReplyToQueue[$address] = $params;
954
                    return true;
955
                }
956
            }
957
            return false;
958
        }
959
        // Immediately add standard addresses without IDN.
960
        return call_user_func_array([$this, 'addAnAddress'], $params);
961
    }
962
963
    /**
964
     * Add an address to one of the recipient arrays or to the ReplyTo array.
965
     * Addresses that have been added already return false, but do not throw exceptions.
966
     *
967
     * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
968
     * @param string $address The email address to send, resp. to reply to
969
     * @param string $name
970
     *
971
     * @throws Exception
972
     * @return boolean true on success, false if address already used or invalid in some way
973
     */
974
    protected function addAnAddress($kind, $address, $name = '')
975
    {
976
        if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) {
977
            $error_message = $this->lang('Invalid recipient kind: ') . $kind;
978
            $this->setError($error_message);
979
            $this->edebug($error_message);
980
            if ($this->exceptions) {
981
                throw new Exception($error_message);
982
            }
983
            return false;
984
        }
985
        if (!static::validateAddress($address)) {
986
            $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address";
987
            $this->setError($error_message);
988
            $this->edebug($error_message);
989
            if ($this->exceptions) {
990
                throw new Exception($error_message);
991
            }
992
            return false;
993
        }
994
        if ('Reply-To' != $kind) {
995
            if (!array_key_exists(strtolower($address), $this->all_recipients)) {
996
                array_push($this->$kind, [$address, $name]);
997
                $this->all_recipients[strtolower($address)] = true;
998
                return true;
999
            }
1000
        } else {
1001
            if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
1002
                $this->ReplyTo[strtolower($address)] = [$address, $name];
1003
                return true;
1004
            }
1005
        }
1006
        return false;
1007
    }
1008
1009
    /**
1010
     * Parse and validate a string containing one or more RFC822-style comma-separated email addresses
1011
     * of the form "display name <address>" into an array of name/address pairs.
1012
     * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
1013
     * Note that quotes in the name part are removed.
1014
     *
1015
     * @param string $addrstr The address list string
1016
     * @param boolean $useimap Whether to use the IMAP extension to parse the list
1017
     *
1018
     * @return array
1019
     * @see    http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
1020
     */
1021
    public static function parseAddresses($addrstr, $useimap = true)
1022
    {
1023
        $addresses = [];
1024
        if ($useimap and function_exists('imap_rfc822_parse_adrlist')) {
1025
            //Use this built-in parser if it's available
1026
            $list = imap_rfc822_parse_adrlist($addrstr, '');
1027
            foreach ($list as $address) {
1028
                if ('.SYNTAX-ERROR.' != $address->host) {
1029
                    if (static::validateAddress($address->mailbox . '@' . $address->host)) {
1030
                        $addresses[] = [
1031
                            'name' => (property_exists($address, 'personal') ? $address->personal : ''),
1032
                            'address' => $address->mailbox . '@' . $address->host
1033
                        ];
1034
                    }
1035
                }
1036
            }
1037
        } else {
1038
            //Use this simpler parser
1039
            $list = explode(',', $addrstr);
1040
            foreach ($list as $address) {
1041
                $address = trim($address);
1042
                //Is there a separate name part?
1043
                if (strpos($address, '<') === false) {
1044
                    //No separate name, just use the whole thing
1045
                    if (static::validateAddress($address)) {
1046
                        $addresses[] = [
1047
                            'name' => '',
1048
                            'address' => $address
1049
                        ];
1050
                    }
1051
                } else {
1052
                    list($name, $email) = explode('<', $address);
1053
                    $email = trim(str_replace('>', '', $email));
1054
                    if (static::validateAddress($email)) {
1055
                        $addresses[] = [
1056
                            'name' => trim(str_replace(['"', "'"], '', $name)),
1057
                            'address' => $email
1058
                        ];
1059
                    }
1060
                }
1061
            }
1062
        }
1063
        return $addresses;
1064
    }
1065
1066
    /**
1067
     * Set the From and FromName properties.
1068
     *
1069
     * @param string $address
1070
     * @param string $name
1071
     * @param boolean $auto Whether to also set the Sender address, defaults to true
1072
     *
1073
     * @throws Exception
1074
     * @return boolean
1075
     */
1076
    public function setFrom($address, $name = '', $auto = true)
1077
    {
1078
        $address = trim($address);
1079
        $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
1080
        // Don't validate now addresses with IDN. Will be done in send().
1081
        $pos = strrpos($address, '@');
1082
        if (false === $pos or
1083
            (!$this->has8bitChars(substr($address, ++$pos)) or !$this->idnSupported()) and
1084
            !static::validateAddress($address)) {
1085
            $error_message = $this->lang('invalid_address') . " (setFrom) $address";
1086
            $this->setError($error_message);
1087
            $this->edebug($error_message);
1088
            if ($this->exceptions) {
1089
                throw new Exception($error_message);
1090
            }
1091
            return false;
1092
        }
1093
        $this->From = $address;
1094
        $this->FromName = $name;
1095
        if ($auto) {
1096
            if (empty($this->Sender)) {
1097
                $this->Sender = $address;
1098
            }
1099
        }
1100
        return true;
1101
    }
1102
1103
    /**
1104
     * Return the Message-ID header of the last email.
1105
     * Technically this is the value from the last time the headers were created,
1106
     * but it's also the message ID of the last sent message except in
1107
     * pathological cases.
1108
     *
1109
     * @return string
1110
     */
1111
    public function getLastMessageID()
1112
    {
1113
        return $this->lastMessageID;
1114
    }
1115
1116
    /**
1117
     * Check that a string looks like an email address.
1118
     *
1119
     * @param string $address The email address to check
1120
     * @param string|callable $patternselect A selector for the validation pattern to use :
1121
     * * `auto` Pick best pattern automatically;
1122
     * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0;
1123
     * * `pcre` Use old PCRE implementation;
1124
     * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;
1125
     * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
1126
     * * `noregex` Don't use a regex: super fast, really dumb.
1127
     * Alternatively you may pass in a callable to inject your own validator, for example:
1128
     * PHPMailer::validateAddress('[email protected]', function($address) {
1129
     *     return (strpos($address, '@') !== false);
1130
     * });
1131
     * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator.
1132
     *
1133
     * @return boolean
1134
     */
1135
    public static function validateAddress($address, $patternselect = null)
1136
    {
1137
        if (is_null($patternselect)) {
1138
            $patternselect = static::$validator;
1139
        }
1140
        if (is_callable($patternselect)) {
1141
            return call_user_func($patternselect, $address);
1142
        }
1143
        //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
1144
        if (strpos($address, "\n") !== false or strpos($address, "\r") !== false) {
1145
            return false;
1146
        }
1147
        switch ($patternselect) {
1148
            case 'pcre': //Kept for BC
1149
            case 'pcre8':
1150
                /**
1151
                 * A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL
1152
                 * is based.
1153
                 * In addition to the addresses allowed by filter_var, also permits:
1154
                 *  * dotless domains: `a@b`
1155
                 *  * comments: `1234 @ local(blah) .machine .example`
1156
                 *  * quoted elements: `'"test blah"@example.org'`
1157
                 *  * numeric TLDs: `[email protected]`
1158
                 *  * unbracketed IPv4 literals: `[email protected]`
1159
                 *  * IPv6 literals: 'first.last@[IPv6:a1::]'
1160
                 * Not all of these will necessarily work for sending!
1161
                 *
1162
                 * @see       http://squiloople.com/2009/12/20/email-address-validation/
1163
                 * @copyright 2009-2010 Michael Rushton
1164
                 * Feel free to use and redistribute this code. But please keep this copyright notice.
1165
                 */
1166
                return (boolean)preg_match(
1167
                    '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
1168
                    '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
1169
                    '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
1170
                    '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
1171
                    '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
1172
                    '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
1173
                    '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
1174
                    '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
1175
                    '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
1176
                    $address
1177
                );
1178
            case 'html5':
1179
                /**
1180
                 * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
1181
                 *
1182
                 * @see http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
1183
                 */
1184
                return (boolean)preg_match(
1185
                    '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
1186
                    '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
1187
                    $address
1188
                );
1189
            case 'noregex': //Kept for BC
1190
            case 'php':
1191
            default:
1192
                return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL);
1193
        }
1194
    }
1195
1196
    /**
1197
     * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the
1198
     * `intl` and `mbstring` PHP extensions.
1199
     *
1200
     * @return boolean `true` if required functions for IDN support are present
1201
     */
1202
    public function idnSupported()
1203
    {
1204
        return function_exists('idn_to_ascii') and function_exists('mb_convert_encoding');
1205
    }
1206
1207
    /**
1208
     * Converts IDN in given email address to its ASCII form, also known as punycode, if possible.
1209
     * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet.
1210
     * This function silently returns unmodified address if:
1211
     * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
1212
     * - Conversion to punycode is impossible (e.g. required PHP functions are not available)
1213
     *   or fails for any reason (e.g. domain has characters not allowed in an IDN)
1214
     *
1215
     * @param string $address The email address to convert
1216
     *
1217
     * @see    PHPMailer::$CharSet
1218
     * @return string The encoded address in ASCII form
1219
     */
1220
    public function punyencodeAddress($address)
1221
    {
1222
        // Verify we have required functions, CharSet, and at-sign.
1223
        $pos = strrpos($address, '@');
1224
        if ($this->idnSupported() and
1225
            !empty($this->CharSet) and
1226
            false !== $pos
1227
        ) {
1228
            $domain = substr($address, ++$pos);
1229
            // Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
1230
            if ($this->has8bitChars($domain) and @mb_check_encoding($domain, $this->CharSet)) {
1231
                $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet);
1232
                //Ignore IDE complaints about this line - method signature changed in PHP 5.4
1233
                $errorcode = 0;
1234
                $punycode = idn_to_ascii($domain, $errorcode, INTL_IDNA_VARIANT_UTS46);
1235
                if (false !== $punycode) {
1236
                    return substr($address, 0, $pos) . $punycode;
1237
                }
1238
            }
1239
        }
1240
        return $address;
1241
    }
1242
1243
    /**
1244
     * Create a message and send it.
1245
     * Uses the sending method specified by $Mailer.
1246
     *
1247
     * @return boolean false on error - See the ErrorInfo property for details of the error.
1248
     * @throws Exception
1249
     */
1250
    public function send()
1251
    {
1252
        try {
1253
            if (!$this->preSend()) {
1254
                return false;
1255
            }
1256
            return $this->postSend();
1257
        } catch (Exception $exc) {
1258
            $this->mailHeader = '';
1259
            $this->setError($exc->getMessage());
1260
            if ($this->exceptions) {
1261
                throw $exc;
1262
            }
1263
            return false;
1264
        }
1265
    }
1266
1267
    /**
1268
     * Prepare a message for sending.
1269
     *
1270
     * @throws Exception
1271
     * @return boolean
1272
     */
1273
    public function preSend()
1274
    {
1275
        if ('smtp' == $this->Mailer or
1276
            ('mail' == $this->Mailer and stripos(PHP_OS, 'WIN') === 0)
1277
        ) {
1278
            //SMTP mandates RFC-compliant line endings
1279
            //and it's also used with mail() on Windows
1280
            static::setLE("\r\n");
1281
        } else {
1282
            //Maintain backward compatibility with legacy Linux command line mailers
1283
            static::setLE(PHP_EOL);
1284
        }
1285
        //Check for buggy PHP versions that add a header with an incorrect line break
1286
        if (ini_get('mail.add_x_header') == 1
1287
            and 'mail' == $this->Mailer
1288
            and stripos(PHP_OS, 'WIN') === 0
1289
            and ((version_compare(PHP_VERSION, '7.0.0', '>=')
1290
                    and version_compare(PHP_VERSION, '7.0.17', '<'))
1291
                or (version_compare(PHP_VERSION, '7.1.0', '>=')
1292
                    and version_compare(PHP_VERSION, '7.1.3', '<')))
1293
        ) {
1294
            trigger_error(
1295
                'Your version of PHP is affected by a bug that may result in corrupted messages.' .
1296
                ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' .
1297
                ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.',
1298
                E_USER_WARNING
1299
            );
1300
        }
1301
1302
        try {
1303
            $this->error_count = 0; // Reset errors
1304
            $this->mailHeader = '';
1305
1306
            // Dequeue recipient and Reply-To addresses with IDN
1307
            foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
1308
                $params[1] = $this->punyencodeAddress($params[1]);
1309
                call_user_func_array([$this, 'addAnAddress'], $params);
1310
            }
1311
            if (count($this->to) + count($this->cc) + count($this->bcc) < 1) {
1312
                throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL);
1313
            }
1314
1315
            // Validate From, Sender, and ConfirmReadingTo addresses
1316
            foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) {
1317
                $this->$address_kind = trim($this->$address_kind);
1318
                if (empty($this->$address_kind)) {
1319
                    continue;
1320
                }
1321
                $this->$address_kind = $this->punyencodeAddress($this->$address_kind);
1322
                if (!static::validateAddress($this->$address_kind)) {
1323
                    $error_message = $this->lang('invalid_address') . ' (punyEncode) ' . $this->$address_kind;
1324
                    $this->setError($error_message);
1325
                    $this->edebug($error_message);
1326
                    if ($this->exceptions) {
1327
                        throw new Exception($error_message);
1328
                    }
1329
                    return false;
1330
                }
1331
            }
1332
1333
            // Set whether the message is multipart/alternative
1334
            if ($this->alternativeExists()) {
1335
                $this->ContentType = 'multipart/alternative';
1336
            }
1337
1338
            $this->setMessageType();
1339
            // Refuse to send an empty message unless we are specifically allowing it
1340
            if (!$this->AllowEmpty and empty($this->Body)) {
1341
                throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
1342
            }
1343
1344
            //Trim subject consistently
1345
            $this->Subject = trim($this->Subject);
1346
            // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
1347
            $this->MIMEHeader = '';
1348
            $this->MIMEBody = $this->createBody();
1349
            // createBody may have added some headers, so retain them
1350
            $tempheaders = $this->MIMEHeader;
1351
            $this->MIMEHeader = $this->createHeader();
1352
            $this->MIMEHeader .= $tempheaders;
1353
1354
            // To capture the complete message when using mail(), create
1355
            // an extra header list which createHeader() doesn't fold in
1356
            if ('mail' == $this->Mailer) {
1357
                if (count($this->to) > 0) {
1358
                    $this->mailHeader .= $this->addrAppend('To', $this->to);
1359
                } else {
1360
                    $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
1361
                }
1362
                $this->mailHeader .= $this->headerLine(
1363
                    'Subject',
1364
                    $this->encodeHeader($this->secureHeader($this->Subject))
1365
                );
1366
            }
1367
1368
            // Sign with DKIM if enabled
1369
            if (!empty($this->DKIM_domain)
1370
                and !empty($this->DKIM_selector)
1371
                and (!empty($this->DKIM_private_string)
1372
                   or (!empty($this->DKIM_private) and file_exists($this->DKIM_private))
1373
                )
1374
            ) {
1375
                $header_dkim = $this->DKIM_Add(
1376
                    $this->MIMEHeader . $this->mailHeader,
1377
                    $this->encodeHeader($this->secureHeader($this->Subject)),
1378
                    $this->MIMEBody
1379
                );
1380
                $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . static::$LE .
1381
                    static::normalizeBreaks($header_dkim) . static::$LE;
1382
            }
1383
            return true;
1384
        } catch (Exception $exc) {
1385
            $this->setError($exc->getMessage());
1386
            if ($this->exceptions) {
1387
                throw $exc;
1388
            }
1389
            return false;
1390
        }
1391
    }
1392
1393
    /**
1394
     * Actually send a message.
1395
     * Send the email via the selected mechanism
1396
     *
1397
     * @return boolean
1398
     * @throws Exception
1399
     */
1400
    public function postSend()
1401
    {
1402
        try {
1403
            // Choose the mailer and send through it
1404
            switch ($this->Mailer) {
1405
                case 'sendmail':
1406
                case 'qmail':
1407
                    return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
1408
                case 'smtp':
1409
                    return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
1410
                case 'mail':
1411
                    return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1412
                default:
1413
                    $sendMethod = $this->Mailer.'Send';
1414
                    if (method_exists($this, $sendMethod)) {
1415
                        return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
1416
                    }
1417
1418
                    return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1419
            }
1420
        } catch (Exception $exc) {
1421
            $this->setError($exc->getMessage());
1422
            $this->edebug($exc->getMessage());
1423
            if ($this->exceptions) {
1424
                throw $exc;
1425
            }
1426
        }
1427
        return false;
1428
    }
1429
1430
    /**
1431
     * Send mail using the $Sendmail program.
1432
     *
1433
     * @param string $header The message headers
1434
     * @param string $body The message body
1435
     *
1436
     * @see    PHPMailer::$Sendmail
1437
     * @throws Exception
1438
     * @return boolean
1439
     */
1440
    protected function sendmailSend($header, $body)
1441
    {
1442
        // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1443
        if (!empty($this->Sender) and self::isShellSafe($this->Sender)) {
1444
            if ('qmail' == $this->Mailer) {
1445
                $sendmailFmt = '%s -f%s';
1446
            } else {
1447
                $sendmailFmt = '%s -oi -f%s -t';
1448
            }
1449
        } else {
1450
            if ('qmail' == $this->Mailer) {
1451
                $sendmailFmt = '%s';
1452
            } else {
1453
                $sendmailFmt = '%s -oi -t';
1454
            }
1455
        }
1456
1457
        $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);
1458
1459
        if ($this->SingleTo) {
1460
            foreach ($this->SingleToArray as $toAddr) {
1461
                $mail = @popen($sendmail, 'w');
1462
                if (!$mail) {
1463
                    throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1464
                }
1465
                fwrite($mail, 'To: ' . $toAddr . "\n");
1466
                fwrite($mail, $header);
1467
                fwrite($mail, $body);
1468
                $result = pclose($mail);
1469
                $this->doCallback(
1470
                    ($result == 0),
1471
                    [$toAddr],
1472
                    $this->cc,
1473
                    $this->bcc,
1474
                    $this->Subject,
1475
                    $body,
1476
                    $this->From
1477
                );
1478
                if (0 !== $result) {
1479
                    throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1480
                }
1481
            }
1482
        } else {
1483
            $mail = @popen($sendmail, 'w');
1484
            if (!$mail) {
1485
                throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1486
            }
1487
            fwrite($mail, $header);
1488
            fwrite($mail, $body);
1489
            $result = pclose($mail);
1490
            $this->doCallback(
1491
                ($result == 0),
1492
                $this->to,
1493
                $this->cc,
1494
                $this->bcc,
1495
                $this->Subject,
1496
                $body,
1497
                $this->From
1498
            );
1499
            if (0 !== $result) {
1500
                throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1501
            }
1502
        }
1503
        return true;
1504
    }
1505
1506
    /**
1507
     * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters.
1508
     *
1509
     * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows.
1510
     * @param string $string The string to be validated
1511
     * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report
1512
     * @access protected
1513
     * @return boolean
1514
     */
1515
    protected static function isShellSafe($string)
1516
    {
1517
        // Future-proof
1518
        if (escapeshellcmd($string) !== $string
1519
            or !in_array(escapeshellarg($string), ["'$string'", "\"$string\""])
1520
        ) {
1521
            return false;
1522
        }
1523
1524
        $length = strlen($string);
1525
1526
        for ($i = 0; $i < $length; ++$i) {
1527
            $c = $string[$i];
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $c. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
1528
1529
            // All other characters have a special meaning in at least one common shell, including = and +.
1530
            // Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
1531
            // Note that this does permit non-Latin alphanumeric characters based on the current locale.
1532
            if (!ctype_alnum($c) && strpos('@_-.', $c) === false) {
1533
                return false;
1534
            }
1535
        }
1536
1537
        return true;
1538
    }
1539
1540
    /**
1541
     * Send mail using the PHP mail() function.
1542
     *
1543
     * @param string $header The message headers
1544
     * @param string $body The message body
1545
     *
1546
     * @see    http://www.php.net/manual/en/book.mail.php
1547
     * @throws Exception
1548
     * @return boolean
1549
     */
1550
    protected function mailSend($header, $body)
1551
    {
1552
        $toArr = [];
1553
        foreach ($this->to as $toaddr) {
1554
            $toArr[] = $this->addrFormat($toaddr);
1555
        }
1556
        $to = implode(', ', $toArr);
1557
1558
        $params = null;
1559
        //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
1560
        if (!empty($this->Sender) and static::validateAddress($this->Sender)) {
1561
            //A space after `-f` is optional, but there is a long history of its presence
1562
            //causing problems, so we don't use one
1563
            //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
1564
            //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html
1565
            //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html
1566
            //Example problem: https://www.drupal.org/node/1057954
1567
            // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1568
            if (self::isShellSafe($this->Sender)) {
1569
                $params = sprintf('-f%s', $this->Sender);
1570
            }
1571
        }
1572
        if (!empty($this->Sender)and static::validateAddress($this->Sender)) {
1573
            $old_from = ini_get('sendmail_from');
1574
            ini_set('sendmail_from', $this->Sender);
1575
        }
1576
        $result = false;
1577
        if ($this->SingleTo and count($toArr) > 1) {
1578
            foreach ($toArr as $toAddr) {
1579
                $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
1580
                $this->doCallback($result, [$toAddr], $this->cc, $this->bcc, $this->Subject, $body, $this->From);
1581
            }
1582
        } else {
1583
            $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
1584
            $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
1585
        }
1586
        if (isset($old_from)) {
1587
            ini_set('sendmail_from', $old_from);
1588
        }
1589
        if (!$result) {
1590
            throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL);
1591
        }
1592
        return true;
1593
    }
1594
1595
    /**
1596
     * Get an instance to use for SMTP operations.
1597
     * Override this function to load your own SMTP implementation,
1598
     * or set one with setSMTPInstance.
1599
     *
1600
     * @return SMTP
1601
     */
1602
    public function getSMTPInstance()
1603
    {
1604
        if (!is_object($this->smtp)) {
1605
            $this->smtp = new SMTP;
1606
        }
1607
        return $this->smtp;
1608
    }
1609
1610
    /**
1611
     * Provide an instance to use for SMTP operations.
1612
     *
1613
     * @param SMTP $smtp
1614
     * @return SMTP
1615
     */
1616
    public function setSMTPInstance(SMTP $smtp)
1617
    {
1618
        $this->smtp = $smtp;
1619
        return $this->smtp;
1620
    }
1621
1622
    /**
1623
     * Send mail via SMTP.
1624
     * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
1625
     * Uses the PHPMailerSMTP class by default.
1626
     *
1627
     * @param string $header The message headers
1628
     * @param string $body The message body
1629
     *
1630
     * @see    PHPMailer::getSMTPInstance() to use a different class.
1631
     * @throws Exception
1632
     * @uses   SMTP
1633
     * @return boolean
1634
     */
1635
    protected function smtpSend($header, $body)
1636
    {
1637
        $bad_rcpt = [];
1638
        if (!$this->smtpConnect($this->SMTPOptions)) {
1639
            throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
1640
        }
1641
        //Sender already validated in preSend()
1642
        if ('' == $this->Sender) {
1643
            $smtp_from = $this->From;
1644
        } else {
1645
            $smtp_from = $this->Sender;
1646
        }
1647
        if (!$this->smtp->mail($smtp_from)) {
1648
            $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
1649
            throw new Exception($this->ErrorInfo, self::STOP_CRITICAL);
1650
        }
1651
1652
        // Attempt to send to all recipients
1653
        foreach ([$this->to, $this->cc, $this->bcc] as $togroup) {
1654
            foreach ($togroup as $to) {
1655
                if (!$this->smtp->recipient($to[0])) {
1656
                    $error = $this->smtp->getError();
1657
                    $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']];
1658
                    $isSent = false;
1659
                } else {
1660
                    $isSent = true;
1661
                }
1662
                $this->doCallback($isSent, [$to[0]], [], [], $this->Subject, $body, $this->From);
1663
            }
1664
        }
1665
1666
        // Only send the DATA command if we have viable recipients
1667
        if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
1668
            throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL);
1669
        }
1670
        if ($this->SMTPKeepAlive) {
1671
            $this->smtp->reset();
1672
        } else {
1673
            $this->smtp->quit();
1674
            $this->smtp->close();
1675
        }
1676
        //Create error message for any bad addresses
1677
        if (count($bad_rcpt) > 0) {
1678
            $errstr = '';
1679
            foreach ($bad_rcpt as $bad) {
1680
                $errstr .= $bad['to'] . ': ' . $bad['error'];
1681
            }
1682
            throw new Exception(
1683
                $this->lang('recipients_failed') . $errstr,
1684
                self::STOP_CONTINUE
1685
            );
1686
        }
1687
        return true;
1688
    }
1689
1690
    /**
1691
     * Initiate a connection to an SMTP server.
1692
     * Returns false if the operation failed.
1693
     *
1694
     * @param array $options An array of options compatible with stream_context_create()
1695
     *
1696
     * @return boolean
1697
     * @throws Exception
1698
     * @uses   SMTP
1699
     */
1700
    public function smtpConnect($options = null)
1701
    {
1702
        if (is_null($this->smtp)) {
1703
            $this->smtp = $this->getSMTPInstance();
1704
        }
1705
1706
        //If no options are provided, use whatever is set in the instance
1707
        if (is_null($options)) {
1708
            $options = $this->SMTPOptions;
1709
        }
1710
1711
        // Already connected?
1712
        if ($this->smtp->connected()) {
1713
            return true;
1714
        }
1715
1716
        $this->smtp->setTimeout($this->Timeout);
1717
        $this->smtp->setDebugLevel($this->SMTPDebug);
1718
        $this->smtp->setDebugOutput($this->Debugoutput);
1719
        $this->smtp->setVerp($this->do_verp);
1720
        $hosts = explode(';', $this->Host);
1721
        $lastexception = null;
1722
1723
        foreach ($hosts as $hostentry) {
1724
            $hostinfo = [];
1725
            if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*|\[[a-fA-F0-9:]+\]):?([0-9]*)$/', trim($hostentry), $hostinfo)) {
1726
                static::edebug($this->lang('connect_host') . ' ' . $hostentry);
1727
                // Not a valid host entry
1728
                continue;
1729
            }
1730
            // $hostinfo[2]: optional ssl or tls prefix
1731
            // $hostinfo[3]: the hostname
1732
            // $hostinfo[4]: optional port number
1733
            // The host string prefix can temporarily override the current setting for SMTPSecure
1734
            // If it's not specified, the default value is used
1735
1736
            //Check the host name is a valid name or IP address before trying to use it
1737
            if (!static::isValidHost($hostinfo[3])) {
1738
                static::edebug($this->lang('connect_host'). ' ' . $hostentry);
1739
                continue;
1740
            }
1741
            $prefix = '';
1742
            $secure = $this->SMTPSecure;
1743
            $tls = ('tls' == $this->SMTPSecure);
1744
            if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
1745
                $prefix = 'ssl://';
1746
                $tls = false; // Can't have SSL and TLS at the same time
1747
                $secure = 'ssl';
1748
            } elseif ('tls' == $hostinfo[2]) {
1749
                $tls = true;
1750
                // tls doesn't use a prefix
1751
                $secure = 'tls';
1752
            }
1753
            //Do we need the OpenSSL extension?
1754
            $sslext = defined('OPENSSL_ALGO_SHA256');
1755
            if ('tls' === $secure or 'ssl' === $secure) {
1756
                //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
1757
                if (!$sslext) {
1758
                    throw new Exception($this->lang('extension_missing').'openssl', self::STOP_CRITICAL);
1759
                }
1760
            }
1761
            $host = $hostinfo[3];
1762
            $port = $this->Port;
1763
            $tport = (integer)$hostinfo[4];
1764
            if ($tport > 0 and $tport < 65536) {
1765
                $port = $tport;
1766
            }
1767
            if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
1768
                try {
1769
                    if ($this->Helo) {
1770
                        $hello = $this->Helo;
1771
                    } else {
1772
                        $hello = $this->serverHostname();
1773
                    }
1774
                    $this->smtp->hello($hello);
1775
                    //Automatically enable TLS encryption if:
1776
                    // * it's not disabled
1777
                    // * we have openssl extension
1778
                    // * we are not already using SSL
1779
                    // * the server offers STARTTLS
1780
                    if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) {
1781
                        $tls = true;
1782
                    }
1783
                    if ($tls) {
1784
                        if (!$this->smtp->startTLS()) {
1785
                            throw new Exception($this->lang('connect_host'));
1786
                        }
1787
                        // We must resend EHLO after TLS negotiation
1788
                        $this->smtp->hello($hello);
1789
                    }
1790
                    if ($this->SMTPAuth) {
1791
                        if (!$this->smtp->authenticate(
1792
                            $this->Username,
1793
                            $this->Password,
1794
                            $this->AuthType,
1795
                            $this->oauth
1796
                        )
1797
                        ) {
1798
                            throw new Exception($this->lang('authenticate'));
1799
                        }
1800
                    }
1801
                    return true;
1802
                } catch (Exception $exc) {
1803
                    $lastexception = $exc;
1804
                    $this->edebug($exc->getMessage());
1805
                    // We must have connected, but then failed TLS or Auth, so close connection nicely
1806
                    $this->smtp->quit();
1807
                }
1808
            }
1809
        }
1810
        // If we get here, all connection attempts have failed, so close connection hard
1811
        $this->smtp->close();
1812
        // As we've caught all exceptions, just report whatever the last one was
1813
        if ($this->exceptions and !is_null($lastexception)) {
1814
            throw $lastexception;
1815
        }
1816
        return false;
1817
    }
1818
1819
    /**
1820
     * Close the active SMTP session if one exists.
1821
     */
1822
    public function smtpClose()
1823
    {
1824
        if (!is_null($this->smtp)) {
1825
            if ($this->smtp->connected()) {
1826
                $this->smtp->quit();
1827
                $this->smtp->close();
1828
            }
1829
        }
1830
    }
1831
1832
    /**
1833
     * Set the language for error messages.
1834
     * Returns false if it cannot load the language file.
1835
     * The default language is English.
1836
     *
1837
     * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
1838
     * @param string $lang_path Path to the language file directory, with trailing separator (slash)
1839
     *
1840
     * @return boolean
1841
     */
1842
    public function setLanguage($langcode = 'en', $lang_path = '')
1843
    {
1844
        // Backwards compatibility for renamed language codes
1845
        $renamed_langcodes = [
1846
            'br' => 'pt_br',
1847
            'cz' => 'cs',
1848
            'dk' => 'da',
1849
            'no' => 'nb',
1850
            'se' => 'sv',
1851
            'sr' => 'rs'
1852
        ];
1853
1854
        if (isset($renamed_langcodes[$langcode])) {
1855
            $langcode = $renamed_langcodes[$langcode];
1856
        }
1857
1858
        // Define full set of translatable strings in English
1859
        $PHPMAILER_LANG = [
1860
            'authenticate' => 'SMTP Error: Could not authenticate.',
1861
            'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
1862
            'data_not_accepted' => 'SMTP Error: data not accepted.',
1863
            'empty_message' => 'Message body empty',
1864
            'encoding' => 'Unknown encoding: ',
1865
            'execute' => 'Could not execute: ',
1866
            'file_access' => 'Could not access file: ',
1867
            'file_open' => 'File Error: Could not open file: ',
1868
            'from_failed' => 'The following From address failed: ',
1869
            'instantiate' => 'Could not instantiate mail function.',
1870
            'invalid_address' => 'Invalid address: ',
1871
            'mailer_not_supported' => ' mailer is not supported.',
1872
            'provide_address' => 'You must provide at least one recipient email address.',
1873
            'recipients_failed' => 'SMTP Error: The following recipients failed: ',
1874
            'signing' => 'Signing Error: ',
1875
            'smtp_connect_failed' => 'SMTP connect() failed.',
1876
            'smtp_error' => 'SMTP server error: ',
1877
            'variable_set' => 'Cannot set or reset variable: ',
1878
            'extension_missing' => 'Extension missing: '
1879
        ];
1880
        if (empty($lang_path)) {
1881
            // Calculate an absolute path so it can work if CWD is not here
1882
            $lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR;
1883
        }
1884
        //Validate $langcode
1885
        if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) {
1886
            $langcode = 'en';
1887
        }
1888
        $foundlang = true;
1889
        $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
1890
        // There is no English translation file
1891
        if ('en' != $langcode) {
1892
            // Make sure language file path is readable
1893
            if (!file_exists($lang_file)) {
1894
                $foundlang = false;
1895
            } else {
1896
                // Overwrite language-specific strings.
1897
                // This way we'll never have missing translation keys.
1898
                $foundlang = include $lang_file;
1899
            }
1900
        }
1901
        $this->language = $PHPMAILER_LANG;
1902
        return (boolean)$foundlang; // Returns false if language not found
1903
    }
1904
1905
    /**
1906
     * Get the array of strings for the current language.
1907
     *
1908
     * @return array
1909
     */
1910
    public function getTranslations()
1911
    {
1912
        return $this->language;
1913
    }
1914
1915
    /**
1916
     * Create recipient headers.
1917
     *
1918
     * @param string $type
1919
     * @param array $addr An array of recipient,
1920
     * where each recipient is a 2-element indexed array with element 0 containing an address
1921
     * and element 1 containing a name, like:
1922
     * [['[email protected]', 'Joe User'], ['[email protected]', 'Zoe User']]
1923
     *
1924
     * @return string
1925
     */
1926
    public function addrAppend($type, $addr)
1927
    {
1928
        $addresses = [];
1929
        foreach ($addr as $address) {
1930
            $addresses[] = $this->addrFormat($address);
1931
        }
1932
        return $type . ': ' . implode(', ', $addresses) . static::$LE;
1933
    }
1934
1935
    /**
1936
     * Format an address for use in a message header.
1937
     *
1938
     * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name
1939
     *      like ['[email protected]', 'Joe User']
1940
     *
1941
     * @return string
1942
     */
1943
    public function addrFormat($addr)
1944
    {
1945
        if (empty($addr[1])) { // No name provided
1946
            return $this->secureHeader($addr[0]);
1947
        } else {
1948
            return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
1949
                $addr[0]
1950
            ) . '>';
1951
        }
1952
    }
1953
1954
    /**
1955
     * Word-wrap message.
1956
     * For use with mailers that do not automatically perform wrapping
1957
     * and for quoted-printable encoded messages.
1958
     * Original written by philippe.
1959
     *
1960
     * @param string $message The message to wrap
1961
     * @param integer $length The line length to wrap to
1962
     * @param boolean $qp_mode Whether to run in Quoted-Printable mode
1963
     *
1964
     * @return string
1965
     */
1966
    public function wrapText($message, $length, $qp_mode = false)
1967
    {
1968
        if ($qp_mode) {
1969
            $soft_break = sprintf(' =%s', static::$LE);
1970
        } else {
1971
            $soft_break = static::$LE;
1972
        }
1973
        // If utf-8 encoding is used, we will need to make sure we don't
1974
        // split multibyte characters when we wrap
1975
        $is_utf8 = (strtolower($this->CharSet) == 'utf-8');
1976
        $lelen = strlen(static::$LE);
1977
        $crlflen = strlen(static::$LE);
1978
1979
        $message = static::normalizeBreaks($message);
1980
        //Remove a trailing line break
1981
        if (substr($message, -$lelen) == static::$LE) {
1982
            $message = substr($message, 0, -$lelen);
1983
        }
1984
1985
        //Split message into lines
1986
        $lines = explode(static::$LE, $message);
1987
        //Message will be rebuilt in here
1988
        $message = '';
1989
        foreach ($lines as $line) {
1990
            $words = explode(' ', $line);
1991
            $buf = '';
1992
            $firstword = true;
1993
            foreach ($words as $word) {
1994
                if ($qp_mode and (strlen($word) > $length)) {
1995
                    $space_left = $length - strlen($buf) - $crlflen;
1996
                    if (!$firstword) {
1997
                        if ($space_left > 20) {
1998
                            $len = $space_left;
1999
                            if ($is_utf8) {
2000
                                $len = $this->utf8CharBoundary($word, $len);
2001
                            } elseif (substr($word, $len - 1, 1) == '=') {
2002
                                --$len;
2003
                            } elseif (substr($word, $len - 2, 1) == '=') {
2004
                                $len -= 2;
2005
                            }
2006
                            $part = substr($word, 0, $len);
2007
                            $word = substr($word, $len);
2008
                            $buf .= ' ' . $part;
2009
                            $message .= $buf . sprintf('=%s', static::$LE);
2010
                        } else {
2011
                            $message .= $buf . $soft_break;
2012
                        }
2013
                        $buf = '';
2014
                    }
2015
                    while (strlen($word) > 0) {
2016
                        if ($length <= 0) {
2017
                            break;
2018
                        }
2019
                        $len = $length;
2020
                        if ($is_utf8) {
2021
                            $len = $this->utf8CharBoundary($word, $len);
2022
                        } elseif (substr($word, $len - 1, 1) == '=') {
2023
                            --$len;
2024
                        } elseif (substr($word, $len - 2, 1) == '=') {
2025
                            $len -= 2;
2026
                        }
2027
                        $part = substr($word, 0, $len);
2028
                        $word = substr($word, $len);
2029
2030
                        if (strlen($word) > 0) {
2031
                            $message .= $part . sprintf('=%s', static::$LE);
2032
                        } else {
2033
                            $buf = $part;
2034
                        }
2035
                    }
2036
                } else {
2037
                    $buf_o = $buf;
2038
                    if (!$firstword) {
2039
                        $buf .= ' ';
2040
                    }
2041
                    $buf .= $word;
2042
2043
                    if (strlen($buf) > $length and $buf_o != '') {
2044
                        $message .= $buf_o . $soft_break;
2045
                        $buf = $word;
2046
                    }
2047
                }
2048
                $firstword = false;
2049
            }
2050
            $message .= $buf . static::$LE;
2051
        }
2052
2053
        return $message;
2054
    }
2055
2056
    /**
2057
     * Find the last character boundary prior to $maxLength in a utf-8
2058
     * quoted-printable encoded string.
2059
     * Original written by Colin Brown.
2060
     *
2061
     * @param string $encodedText utf-8 QP text
2062
     * @param integer $maxLength Find the last character boundary prior to this length
2063
     *
2064
     * @return integer
2065
     */
2066
    public function utf8CharBoundary($encodedText, $maxLength)
2067
    {
2068
        $foundSplitPos = false;
2069
        $lookBack = 3;
2070
        while (!$foundSplitPos) {
2071
            $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
2072
            $encodedCharPos = strpos($lastChunk, '=');
2073
            if (false !== $encodedCharPos) {
2074
                // Found start of encoded character byte within $lookBack block.
2075
                // Check the encoded byte value (the 2 chars after the '=')
2076
                $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
2077
                $dec = hexdec($hex);
2078
                if ($dec < 128) {
2079
                    // Single byte character.
2080
                    // If the encoded char was found at pos 0, it will fit
2081
                    // otherwise reduce maxLength to start of the encoded char
2082
                    if ($encodedCharPos > 0) {
2083
                        $maxLength -= $lookBack - $encodedCharPos;
2084
                    }
2085
                    $foundSplitPos = true;
2086
                } elseif ($dec >= 192) {
2087
                    // First byte of a multi byte character
2088
                    // Reduce maxLength to split at start of character
2089
                    $maxLength -= $lookBack - $encodedCharPos;
2090
                    $foundSplitPos = true;
2091
                } elseif ($dec < 192) {
2092
                    // Middle byte of a multi byte character, look further back
2093
                    $lookBack += 3;
2094
                }
2095
            } else {
2096
                // No encoded character found
2097
                $foundSplitPos = true;
2098
            }
2099
        }
2100
        return $maxLength;
2101
    }
2102
2103
    /**
2104
     * Apply word wrapping to the message body.
2105
     * Wraps the message body to the number of chars set in the WordWrap property.
2106
     * You should only do this to plain-text bodies as wrapping HTML tags may break them.
2107
     * This is called automatically by createBody(), so you don't need to call it yourself.
2108
     */
2109
    public function setWordWrap()
2110
    {
2111
        if ($this->WordWrap < 1) {
2112
            return;
2113
        }
2114
2115
        switch ($this->message_type) {
2116
            case 'alt':
2117
            case 'alt_inline':
2118
            case 'alt_attach':
2119
            case 'alt_inline_attach':
2120
                $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
2121
                break;
2122
            default:
2123
                $this->Body = $this->wrapText($this->Body, $this->WordWrap);
2124
                break;
2125
        }
2126
    }
2127
2128
    /**
2129
     * Assemble message headers.
2130
     *
2131
     * @return string The assembled headers
2132
     */
2133
    public function createHeader()
2134
    {
2135
        $result = '';
2136
2137
        $result .= $this->headerLine('Date', '' == $this->MessageDate ? self::rfcDate() : $this->MessageDate);
2138
2139
        // To be created automatically by mail()
2140
        if ($this->SingleTo) {
2141
            if ('mail' != $this->Mailer) {
2142
                foreach ($this->to as $toaddr) {
2143
                    $this->SingleToArray[] = $this->addrFormat($toaddr);
2144
                }
2145
            }
2146
        } else {
2147
            if (count($this->to) > 0) {
2148
                if ('mail' != $this->Mailer) {
2149
                    $result .= $this->addrAppend('To', $this->to);
2150
                }
2151
            } elseif (count($this->cc) == 0) {
2152
                $result .= $this->headerLine('To', 'undisclosed-recipients:;');
2153
            }
2154
        }
2155
2156
        $result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]);
2157
2158
        // sendmail and mail() extract Cc from the header before sending
2159
        if (count($this->cc) > 0) {
2160
            $result .= $this->addrAppend('Cc', $this->cc);
2161
        }
2162
2163
        // sendmail and mail() extract Bcc from the header before sending
2164
        if ((
2165
            'sendmail' == $this->Mailer or 'qmail' == $this->Mailer or 'mail' == $this->Mailer
2166
            )
2167
            and count($this->bcc) > 0
2168
        ) {
2169
            $result .= $this->addrAppend('Bcc', $this->bcc);
2170
        }
2171
2172
        if (count($this->ReplyTo) > 0) {
2173
            $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
2174
        }
2175
2176
        // mail() sets the subject itself
2177
        if ('mail' != $this->Mailer) {
2178
            $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
2179
        }
2180
2181
        // Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4
2182
        // https://tools.ietf.org/html/rfc5322#section-3.6.4
2183
        if ('' != $this->MessageID and preg_match('/^<.*@.*>$/', $this->MessageID)) {
2184
            $this->lastMessageID = $this->MessageID;
2185
        } else {
2186
            $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());
2187
        }
2188
        $result .= $this->headerLine('Message-ID', $this->lastMessageID);
2189
        if (!is_null($this->Priority)) {
2190
            $result .= $this->headerLine('X-Priority', $this->Priority);
2191
        }
2192
        if ('' == $this->XMailer) {
2193
            $result .= $this->headerLine(
2194
                'X-Mailer',
2195
                'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)'
2196
            );
2197
        } else {
2198
            $myXmailer = trim($this->XMailer);
2199
            if ($myXmailer) {
2200
                $result .= $this->headerLine('X-Mailer', $myXmailer);
2201
            }
2202
        }
2203
2204
        if ('' != $this->ConfirmReadingTo) {
2205
            $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
2206
        }
2207
2208
        // Add custom headers
2209
        foreach ($this->CustomHeader as $header) {
2210
            $result .= $this->headerLine(
2211
                trim($header[0]),
2212
                $this->encodeHeader(trim($header[1]))
2213
            );
2214
        }
2215
        if (!$this->sign_key_file) {
2216
            $result .= $this->headerLine('MIME-Version', '1.0');
2217
            $result .= $this->getMailMIME();
2218
        }
2219
2220
        return $result;
2221
    }
2222
2223
    /**
2224
     * Get the message MIME type headers.
2225
     *
2226
     * @return string
2227
     */
2228
    public function getMailMIME()
2229
    {
2230
        $result = '';
2231
        $ismultipart = true;
2232
        switch ($this->message_type) {
2233
            case 'inline':
2234
                $result .= $this->headerLine('Content-Type', 'multipart/related;');
2235
                $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
2236
                break;
2237
            case 'attach':
2238
            case 'inline_attach':
2239
            case 'alt_attach':
2240
            case 'alt_inline_attach':
2241
                $result .= $this->headerLine('Content-Type', 'multipart/mixed;');
2242
                $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
2243
                break;
2244
            case 'alt':
2245
            case 'alt_inline':
2246
                $result .= $this->headerLine('Content-Type', 'multipart/alternative;');
2247
                $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
2248
                break;
2249
            default:
2250
                // Catches case 'plain': and case '':
2251
                $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
2252
                $ismultipart = false;
2253
                break;
2254
        }
2255
        // RFC1341 part 5 says 7bit is assumed if not specified
2256
        if ('7bit' != $this->Encoding) {
2257
            // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
2258
            if ($ismultipart) {
2259
                if ('8bit' == $this->Encoding) {
2260
                    $result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
2261
                }
2262
                // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
2263
            } else {
2264
                $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
2265
            }
2266
        }
2267
2268
        if ('mail' != $this->Mailer) {
2269
            $result .= static::$LE;
2270
        }
2271
2272
        return $result;
2273
    }
2274
2275
    /**
2276
     * Returns the whole MIME message.
2277
     * Includes complete headers and body.
2278
     * Only valid post preSend().
2279
     *
2280
     * @see    PHPMailer::preSend()
2281
     * @return string
2282
     */
2283
    public function getSentMIMEMessage()
2284
    {
2285
        return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . static::$LE . static::$LE . $this->MIMEBody;
2286
    }
2287
2288
    /**
2289
     * Create a unique ID to use for boundaries.
2290
     *
2291
     * @return string
2292
     */
2293
    protected function generateId()
2294
    {
2295
        $len = 23;
2296
        if (function_exists("random_bytes")) {
2297
            $bytes = random_bytes($len);
2298
        } elseif (function_exists("openssl_random_pseudo_bytes")) {
2299
            $bytes = openssl_random_pseudo_bytes($len);
2300
        } else {
2301
            $bytes = uniqid((string)mt_rand(), true);
2302
        }
2303
        return hash('sha256', $bytes);
2304
    }
2305
2306
    /**
2307
     * Assemble the message body.
2308
     * Returns an empty string on failure.
2309
     *
2310
     * @throws Exception
2311
     * @return string The assembled message body
2312
     */
2313
    public function createBody()
2314
    {
2315
        $body = '';
2316
        //Create unique IDs and preset boundaries
2317
        $this->uniqueid = $this->generateId();
2318
        $this->boundary[1] = 'b1_' . $this->uniqueid;
2319
        $this->boundary[2] = 'b2_' . $this->uniqueid;
2320
        $this->boundary[3] = 'b3_' . $this->uniqueid;
2321
2322
        if ($this->sign_key_file) {
2323
            $body .= $this->getMailMIME() . static::$LE;
2324
        }
2325
2326
        $this->setWordWrap();
2327
2328
        $bodyEncoding = $this->Encoding;
2329
        $bodyCharSet = $this->CharSet;
2330
        //Can we do a 7-bit downgrade?
2331
        if ('8bit' == $bodyEncoding and !$this->has8bitChars($this->Body)) {
2332
            $bodyEncoding = '7bit';
2333
            //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
2334
            $bodyCharSet = 'us-ascii';
2335
        }
2336
        //If lines are too long, and we're not already using an encoding that will shorten them,
2337
        //change to quoted-printable transfer encoding for the body part only
2338
        if ('base64' != $this->Encoding and static::hasLineLongerThanMax($this->Body)) {
2339
            $bodyEncoding = 'quoted-printable';
2340
        }
2341
2342
        $altBodyEncoding = $this->Encoding;
2343
        $altBodyCharSet = $this->CharSet;
2344
        //Can we do a 7-bit downgrade?
2345
        if ('8bit' == $altBodyEncoding and !$this->has8bitChars($this->AltBody)) {
2346
            $altBodyEncoding = '7bit';
2347
            //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
2348
            $altBodyCharSet = 'us-ascii';
2349
        }
2350
        //If lines are too long, and we're not already using an encoding that will shorten them,
2351
        //change to quoted-printable transfer encoding for the alt body part only
2352
        if ('base64' != $altBodyEncoding and static::hasLineLongerThanMax($this->AltBody)) {
2353
            $altBodyEncoding = 'quoted-printable';
2354
        }
2355
        //Use this as a preamble in all multipart message types
2356
        $mimepre = "This is a multi-part message in MIME format." . static::$LE;
2357
        switch ($this->message_type) {
2358
            case 'inline':
2359
                $body .= $mimepre;
2360
                $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
2361
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2362
                $body .= static::$LE;
2363
                $body .= $this->attachAll('inline', $this->boundary[1]);
2364
                break;
2365
            case 'attach':
2366
                $body .= $mimepre;
2367
                $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
2368
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2369
                $body .= static::$LE;
2370
                $body .= $this->attachAll('attachment', $this->boundary[1]);
2371
                break;
2372
            case 'inline_attach':
2373
                $body .= $mimepre;
2374
                $body .= $this->textLine('--' . $this->boundary[1]);
2375
                $body .= $this->headerLine('Content-Type', 'multipart/related;');
2376
                $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
2377
                $body .= static::$LE;
2378
                $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
2379
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2380
                $body .= static::$LE;
2381
                $body .= $this->attachAll('inline', $this->boundary[2]);
2382
                $body .= static::$LE;
2383
                $body .= $this->attachAll('attachment', $this->boundary[1]);
2384
                break;
2385
            case 'alt':
2386
                $body .= $mimepre;
2387
                $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2388
                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2389
                $body .= static::$LE;
2390
                $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
2391
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2392
                $body .= static::$LE;
2393
                if (!empty($this->Ical)) {
2394
                    $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
2395
                    $body .= $this->encodeString($this->Ical, $this->Encoding);
2396
                    $body .= static::$LE;
2397
                }
2398
                $body .= $this->endBoundary($this->boundary[1]);
2399
                break;
2400
            case 'alt_inline':
2401
                $body .= $mimepre;
2402
                $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2403
                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2404
                $body .= static::$LE;
2405
                $body .= $this->textLine('--' . $this->boundary[1]);
2406
                $body .= $this->headerLine('Content-Type', 'multipart/related;');
2407
                $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
2408
                $body .= static::$LE;
2409
                $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
2410
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2411
                $body .= static::$LE;
2412
                $body .= $this->attachAll('inline', $this->boundary[2]);
2413
                $body .= static::$LE;
2414
                $body .= $this->endBoundary($this->boundary[1]);
2415
                break;
2416
            case 'alt_attach':
2417
                $body .= $mimepre;
2418
                $body .= $this->textLine('--' . $this->boundary[1]);
2419
                $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
2420
                $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
2421
                $body .= static::$LE;
2422
                $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2423
                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2424
                $body .= static::$LE;
2425
                $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
2426
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2427
                $body .= static::$LE;
2428
                if (!empty($this->Ical)) {
2429
                    $body .= $this->getBoundary($this->boundary[2], '', 'text/calendar; method=REQUEST', '');
2430
                    $body .= $this->encodeString($this->Ical, $this->Encoding);
2431
                }
2432
                $body .= $this->endBoundary($this->boundary[2]);
2433
                $body .= static::$LE;
2434
                $body .= $this->attachAll('attachment', $this->boundary[1]);
2435
                break;
2436
            case 'alt_inline_attach':
2437
                $body .= $mimepre;
2438
                $body .= $this->textLine('--' . $this->boundary[1]);
2439
                $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
2440
                $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
2441
                $body .= static::$LE;
2442
                $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2443
                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2444
                $body .= static::$LE;
2445
                $body .= $this->textLine('--' . $this->boundary[2]);
2446
                $body .= $this->headerLine('Content-Type', 'multipart/related;');
2447
                $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
2448
                $body .= static::$LE;
2449
                $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
2450
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2451
                $body .= static::$LE;
2452
                $body .= $this->attachAll('inline', $this->boundary[3]);
2453
                $body .= static::$LE;
2454
                $body .= $this->endBoundary($this->boundary[2]);
2455
                $body .= static::$LE;
2456
                $body .= $this->attachAll('attachment', $this->boundary[1]);
2457
                break;
2458
            default:
2459
                // Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types
2460
                //Reset the `Encoding` property in case we changed it for line length reasons
2461
                $this->Encoding = $bodyEncoding;
2462
                $body .= $this->encodeString($this->Body, $this->Encoding);
2463
                break;
2464
        }
2465
2466
        if ($this->isError()) {
2467
            $body = '';
2468
            if ($this->exceptions) {
2469
                throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
2470
            }
2471
        } elseif ($this->sign_key_file) {
2472
            try {
2473
                if (!defined('PKCS7_TEXT')) {
2474
                    throw new Exception($this->lang('extension_missing') . 'openssl');
2475
                }
2476
                // @TODO would be nice to use php://temp streams here
2477
                $file = tempnam(sys_get_temp_dir(), 'mail');
2478
                if (false === file_put_contents($file, $body)) {
2479
                    throw new Exception($this->lang('signing') . ' Could not write temp file');
2480
                }
2481
                $signed = tempnam(sys_get_temp_dir(), 'signed');
2482
                //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
2483
                if (empty($this->sign_extracerts_file)) {
2484
                    $sign = @openssl_pkcs7_sign(
2485
                        $file,
2486
                        $signed,
2487
                        'file://' . realpath($this->sign_cert_file),
2488
                        ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
2489
                        []
2490
                    );
2491
                } else {
2492
                    $sign = @openssl_pkcs7_sign(
2493
                        $file,
2494
                        $signed,
2495
                        'file://' . realpath($this->sign_cert_file),
2496
                        ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
2497
                        [],
2498
                        PKCS7_DETACHED,
2499
                        $this->sign_extracerts_file
2500
                    );
2501
                }
2502
                @unlink($file);
2503
                if ($sign) {
2504
                    $body = file_get_contents($signed);
2505
                    @unlink($signed);
2506
                    //The message returned by openssl contains both headers and body, so need to split them up
2507
                    $parts = explode("\n\n", $body, 2);
2508
                    $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE;
2509
                    $body = $parts[1];
2510
                } else {
2511
                    @unlink($signed);
2512
                    throw new Exception($this->lang('signing') . openssl_error_string());
2513
                }
2514
            } catch (Exception $exc) {
2515
                $body = '';
2516
                if ($this->exceptions) {
2517
                    throw $exc;
2518
                }
2519
            }
2520
        }
2521
        return $body;
2522
    }
2523
2524
    /**
2525
     * Return the start of a message boundary.
2526
     *
2527
     * @param string $boundary
2528
     * @param string $charSet
2529
     * @param string $contentType
2530
     * @param string $encoding
2531
     *
2532
     * @return string
2533
     */
2534
    protected function getBoundary($boundary, $charSet, $contentType, $encoding)
2535
    {
2536
        $result = '';
2537
        if ('' == $charSet) {
2538
            $charSet = $this->CharSet;
2539
        }
2540
        if ('' == $contentType) {
2541
            $contentType = $this->ContentType;
2542
        }
2543
        if ('' == $encoding) {
2544
            $encoding = $this->Encoding;
2545
        }
2546
        $result .= $this->textLine('--' . $boundary);
2547
        $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
2548
        $result .= static::$LE;
2549
        // RFC1341 part 5 says 7bit is assumed if not specified
2550
        if ('7bit' != $encoding) {
2551
            $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
2552
        }
2553
        $result .= static::$LE;
2554
2555
        return $result;
2556
    }
2557
2558
    /**
2559
     * Return the end of a message boundary.
2560
     *
2561
     * @param string $boundary
2562
     *
2563
     * @return string
2564
     */
2565
    protected function endBoundary($boundary)
2566
    {
2567
        return static::$LE . '--' . $boundary . '--' . static::$LE;
2568
    }
2569
2570
    /**
2571
     * Set the message type.
2572
     * PHPMailer only supports some preset message types, not arbitrary MIME structures.
2573
     */
2574
    protected function setMessageType()
2575
    {
2576
        $type = [];
2577
        if ($this->alternativeExists()) {
2578
            $type[] = 'alt';
2579
        }
2580
        if ($this->inlineImageExists()) {
2581
            $type[] = 'inline';
2582
        }
2583
        if ($this->attachmentExists()) {
2584
            $type[] = 'attach';
2585
        }
2586
        $this->message_type = implode('_', $type);
2587
        if ('' == $this->message_type) {
2588
            //The 'plain' message_type refers to the message having a single body element, not that it is plain-text
2589
            $this->message_type = 'plain';
2590
        }
2591
    }
2592
2593
    /**
2594
     * Format a header line.
2595
     *
2596
     * @param string $name
2597
     * @param string|integer $value
2598
     *
2599
     * @return string
2600
     */
2601
    public function headerLine($name, $value)
2602
    {
2603
        return $name . ': ' . $value . static::$LE;
2604
    }
2605
2606
    /**
2607
     * Return a formatted mail line.
2608
     *
2609
     * @param string $value
2610
     *
2611
     * @return string
2612
     */
2613
    public function textLine($value)
2614
    {
2615
        return $value . static::$LE;
2616
    }
2617
2618
    /**
2619
     * Add an attachment from a path on the filesystem.
2620
     * Never use a user-supplied path to a file!
2621
     * Returns false if the file could not be found or read.
2622
     *
2623
     * @param string $path Path to the attachment.
2624
     * @param string $name Overrides the attachment name.
2625
     * @param string $encoding File encoding (see $Encoding).
2626
     * @param string $type File extension (MIME) type.
2627
     * @param string $disposition Disposition to use
2628
     *
2629
     * @throws Exception
2630
     * @return boolean
2631
     */
2632
    public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment')
2633
    {
2634
        try {
2635
            if (!@is_file($path)) {
2636
                throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
2637
            }
2638
2639
            // If a MIME type is not specified, try to work it out from the file name
2640
            if ('' == $type) {
2641
                $type = static::filenameToType($path);
2642
            }
2643
2644
            $filename = basename($path);
2645
            if ('' == $name) {
2646
                $name = $filename;
2647
            }
2648
2649
            $this->attachment[] = [
2650
                0 => $path,
2651
                1 => $filename,
2652
                2 => $name,
2653
                3 => $encoding,
2654
                4 => $type,
2655
                5 => false, // isStringAttachment
2656
                6 => $disposition,
2657
                7 => 0
2658
            ];
2659
        } catch (Exception $exc) {
2660
            $this->setError($exc->getMessage());
2661
            $this->edebug($exc->getMessage());
2662
            if ($this->exceptions) {
2663
                throw $exc;
2664
            }
2665
            return false;
2666
        }
2667
        return true;
2668
    }
2669
2670
    /**
2671
     * Return the array of attachments.
2672
     *
2673
     * @return array
2674
     */
2675
    public function getAttachments()
2676
    {
2677
        return $this->attachment;
2678
    }
2679
2680
    /**
2681
     * Attach all file, string, and binary attachments to the message.
2682
     * Returns an empty string on failure.
2683
     *
2684
     * @param string $disposition_type
2685
     * @param string $boundary
2686
     *
2687
     * @return string
2688
     */
2689
    protected function attachAll($disposition_type, $boundary)
2690
    {
2691
        // Return text of body
2692
        $mime = [];
2693
        $cidUniq = [];
2694
        $incl = [];
2695
2696
        // Add all attachments
2697
        foreach ($this->attachment as $attachment) {
2698
            // Check if it is a valid disposition_filter
2699
            if ($attachment[6] == $disposition_type) {
2700
                // Check for string attachment
2701
                $string = '';
2702
                $path = '';
2703
                $bString = $attachment[5];
2704
                if ($bString) {
2705
                    $string = $attachment[0];
2706
                } else {
2707
                    $path = $attachment[0];
2708
                }
2709
2710
                $inclhash = hash('sha256', serialize($attachment));
2711
                if (in_array($inclhash, $incl)) {
2712
                    continue;
2713
                }
2714
                $incl[] = $inclhash;
2715
                $name = $attachment[2];
2716
                $encoding = $attachment[3];
2717
                $type = $attachment[4];
2718
                $disposition = $attachment[6];
2719
                $cid = $attachment[7];
2720
                if ('inline' == $disposition and array_key_exists($cid, $cidUniq)) {
2721
                    continue;
2722
                }
2723
                $cidUniq[$cid] = true;
2724
2725
                $mime[] = sprintf('--%s%s', $boundary, static::$LE);
2726
                //Only include a filename property if we have one
2727
                if (!empty($name)) {
2728
                    $mime[] = sprintf(
2729
                        'Content-Type: %s; name="%s"%s',
2730
                        $type,
2731
                        $this->encodeHeader($this->secureHeader($name)),
2732
                        static::$LE
2733
                    );
2734
                } else {
2735
                    $mime[] = sprintf(
2736
                        'Content-Type: %s%s',
2737
                        $type,
2738
                        static::$LE
2739
                    );
2740
                }
2741
                // RFC1341 part 5 says 7bit is assumed if not specified
2742
                if ('7bit' != $encoding) {
2743
                    $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE);
2744
                }
2745
2746
                if ('inline' == $disposition) {
2747
                    $mime[] = sprintf('Content-ID: <%s>%s', $cid, static::$LE);
2748
                }
2749
2750
                // If a filename contains any of these chars, it should be quoted,
2751
                // but not otherwise: RFC2183 & RFC2045 5.1
2752
                // Fixes a warning in IETF's msglint MIME checker
2753
                // Allow for bypassing the Content-Disposition header totally
2754
                if (!(empty($disposition))) {
2755
                    $encoded_name = $this->encodeHeader($this->secureHeader($name));
2756
                    if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
2757
                        $mime[] = sprintf(
2758
                            'Content-Disposition: %s; filename="%s"%s',
2759
                            $disposition,
2760
                            $encoded_name,
2761
                            static::$LE . static::$LE
2762
                        );
2763
                    } else {
2764
                        if (!empty($encoded_name)) {
2765
                            $mime[] = sprintf(
2766
                                'Content-Disposition: %s; filename=%s%s',
2767
                                $disposition,
2768
                                $encoded_name,
2769
                                static::$LE . static::$LE
2770
                            );
2771
                        } else {
2772
                            $mime[] = sprintf(
2773
                                'Content-Disposition: %s%s',
2774
                                $disposition,
2775
                                static::$LE . static::$LE
2776
                            );
2777
                        }
2778
                    }
2779
                } else {
2780
                    $mime[] = static::$LE;
2781
                }
2782
2783
                // Encode as string attachment
2784
                if ($bString) {
2785
                    $mime[] = $this->encodeString($string, $encoding);
2786
                } else {
2787
                    $mime[] = $this->encodeFile($path, $encoding);
2788
                }
2789
                if ($this->isError()) {
2790
                    return '';
2791
                }
2792
                $mime[] = static::$LE;
2793
            }
2794
        }
2795
2796
        $mime[] = sprintf('--%s--%s', $boundary, static::$LE);
2797
2798
        return implode('', $mime);
2799
    }
2800
2801
    /**
2802
     * Encode a file attachment in requested format.
2803
     * Returns an empty string on failure.
2804
     *
2805
     * @param string $path The full path to the file
2806
     * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
2807
     *
2808
     * @throws Exception
2809
     * @return string
2810
     */
2811
    protected function encodeFile($path, $encoding = 'base64')
2812
    {
2813
        try {
2814
            if (!file_exists($path)) {
2815
                throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
2816
            }
2817
            $file_buffer = file_get_contents($path);
2818
            if (false === $file_buffer) {
2819
                throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
2820
            }
2821
            $file_buffer = $this->encodeString($file_buffer, $encoding);
2822
            return $file_buffer;
2823
        } catch (Exception $exc) {
2824
            $this->setError($exc->getMessage());
2825
            return '';
2826
        }
2827
    }
2828
2829
    /**
2830
     * Encode a string in requested format.
2831
     * Returns an empty string on failure.
2832
     *
2833
     * @param string $str The text to encode
2834
     * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable
2835
     *
2836
     * @return string
2837
     */
2838
    public function encodeString($str, $encoding = 'base64')
2839
    {
2840
        $encoded = '';
2841
        switch (strtolower($encoding)) {
2842
            case 'base64':
2843
                $encoded = chunk_split(
2844
                    base64_encode($str),
2845
                    static::STD_LINE_LENGTH - strlen(static::$LE),
2846
                    static::$LE
2847
                );
2848
                break;
2849
            case '7bit':
2850
            case '8bit':
2851
                $encoded = static::normalizeBreaks($str);
2852
                // Make sure it ends with a line break
2853
                if (substr($encoded, -(strlen(static::$LE))) != static::$LE) {
2854
                    $encoded .= static::$LE;
2855
                }
2856
                break;
2857
            case 'binary':
2858
                $encoded = $str;
2859
                break;
2860
            case 'quoted-printable':
2861
                $encoded = $this->encodeQP($str);
2862
                break;
2863
            default:
2864
                $this->setError($this->lang('encoding') . $encoding);
2865
                break;
2866
        }
2867
        return $encoded;
2868
    }
2869
2870
    /**
2871
     * Encode a header value (not including its label) optimally.
2872
     * Picks shortest of Q, B, or none. Result includes folding if needed.
2873
     *
2874
     * @param string $str The header value to encode.
2875
     * @param string $position What context the string will be used in.
2876
     * See RFC822 definitions for phrase, comment and text.
2877
     *
2878
     * @return string
2879
     */
2880
    public function encodeHeader($str, $position = 'text')
2881
    {
2882
        $matchcount = 0;
2883
        switch (strtolower($position)) {
2884
            case 'phrase':
2885
                if (!preg_match('/[\200-\377]/', $str)) {
2886
                    // Can't use addslashes as we don't know the value of magic_quotes_sybase
2887
                    $encoded = addcslashes($str, "\0..\37\177\\\"");
2888
                    if (($str == $encoded) and !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
2889
                        return $encoded;
2890
                    } else {
2891
                        return "\"$encoded\"";
2892
                    }
2893
                }
2894
                $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
2895
                break;
2896
            /** @noinspection PhpMissingBreakStatementInspection */
2897
            case 'comment':
2898
                $matchcount = preg_match_all('/[()"]/', $str, $matches);
2899
                //fallthrough
2900
            case 'text':
2901
            default:
2902
                $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
2903
                break;
2904
        }
2905
2906
        //RFCs specify a maximum line length of 78 chars, however mail() will sometimes
2907
        //corrupt messages with headers longer than 65 chars. See #818
2908
        $lengthsub = 'mail' == $this->Mailer ? 13: 0;
2909
        $maxlen = static::STD_LINE_LENGTH - $lengthsub;
2910
        // Try to select the encoding which should produce the shortest output
2911
        if ($matchcount > strlen($str) / 3) {
2912
            // More than a third of the content will need encoding, so B encoding will be most efficient
2913
            $encoding = 'B';
2914
            //This calculation is:
2915
            // max line length
2916
            // - shorten to avoid mail() corruption
2917
            // - Q/B encoding char overhead ("` =?<charset>?[QB]?<content>?=`")
2918
            // - charset name length
2919
            $maxlen = static::STD_LINE_LENGTH - $lengthsub - 8 - strlen($this->CharSet);
2920
            if ($this->hasMultiBytes($str)) {
2921
                // Use a custom function which correctly encodes and wraps long
2922
                // multibyte strings without breaking lines within a character
2923
                $encoded = $this->base64EncodeWrapMB($str, "\n");
2924
            } else {
2925
                $encoded = base64_encode($str);
2926
                $maxlen -= $maxlen % 4;
2927
                $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
2928
            }
2929
            $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
2930
        } elseif ($matchcount > 0) {
2931
            //1 or more chars need encoding, use Q-encode
2932
            $encoding = 'Q';
2933
            //Recalc max line length for Q encoding - see comments on B encode
2934
            $maxlen = static::STD_LINE_LENGTH - $lengthsub - 8 - strlen($this->CharSet);
2935
            $encoded = $this->encodeQ($str, $position);
2936
            $encoded = $this->wrapText($encoded, $maxlen, true);
2937
            $encoded = str_replace('=' . static::$LE, "\n", trim($encoded));
2938
            $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
2939
        } elseif (strlen($str) > $maxlen) {
2940
            //No chars need encoding, but line is too long, so fold it
2941
            $encoded = trim($this->wrapText($str, $maxlen, false));
2942
            if ($str == $encoded) {
2943
                //Wrapping nicely didn't work, wrap hard instead
2944
                $encoded = trim(chunk_split($str, static::STD_LINE_LENGTH, static::$LE));
2945
            }
2946
            $encoded = str_replace(static::$LE, "\n", trim($encoded));
2947
            $encoded = preg_replace('/^(.*)$/m', ' \\1', $encoded);
2948
        } else {
2949
            //No reformatting needed
2950
            return $str;
2951
        }
2952
2953
        return trim(static::normalizeBreaks($encoded));
2954
    }
2955
2956
    /**
2957
     * Check if a string contains multi-byte characters.
2958
     *
2959
     * @param string $str multi-byte text to wrap encode
2960
     *
2961
     * @return boolean
2962
     */
2963
    public function hasMultiBytes($str)
2964
    {
2965
        if (function_exists('mb_strlen')) {
2966
            return strlen($str) > mb_strlen($str, $this->CharSet);
2967
        } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
2968
            return false;
2969
        }
2970
    }
2971
2972
    /**
2973
     * Does a string contain any 8-bit chars (in any charset)?
2974
     *
2975
     * @param string $text
2976
     *
2977
     * @return boolean
2978
     */
2979
    public function has8bitChars($text)
2980
    {
2981
        return (boolean)preg_match('/[\x80-\xFF]/', $text);
2982
    }
2983
2984
    /**
2985
     * Encode and wrap long multibyte strings for mail headers
2986
     * without breaking lines within a character.
2987
     * Adapted from a function by paravoid
2988
     *
2989
     * @param string $str multi-byte text to wrap encode
2990
     * @param string $linebreak string to use as linefeed/end-of-line
2991
     *
2992
     * @return string
2993
     * @see    http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
2994
     */
2995
    public function base64EncodeWrapMB($str, $linebreak = null)
2996
    {
2997
        $start = '=?' . $this->CharSet . '?B?';
2998
        $end = '?=';
2999
        $encoded = '';
3000
        if (is_null($linebreak)) {
3001
            $linebreak = static::$LE;
3002
        }
3003
3004
        $mb_length = mb_strlen($str, $this->CharSet);
3005
        // Each line must have length <= 75, including $start and $end
3006
        $length = 75 - strlen($start) - strlen($end);
3007
        // Average multi-byte ratio
3008
        $ratio = $mb_length / strlen($str);
3009
        // Base64 has a 4:3 ratio
3010
        $avgLength = floor($length * $ratio * .75);
3011
3012
        for ($i = 0; $i < $mb_length; $i += $offset) {
3013
            $lookBack = 0;
3014
            do {
3015
                $offset = $avgLength - $lookBack;
3016
                $chunk = mb_substr($str, $i, $offset, $this->CharSet);
3017
                $chunk = base64_encode($chunk);
3018
                ++$lookBack;
3019
            } while (strlen($chunk) > $length);
3020
            $encoded .= $chunk . $linebreak;
3021
        }
3022
3023
        // Chomp the last linefeed
3024
        $encoded = substr($encoded, 0, -strlen($linebreak));
3025
        return $encoded;
3026
    }
3027
3028
    /**
3029
     * Encode a string in quoted-printable format.
3030
     * According to RFC2045 section 6.7.
3031
     *
3032
     * @param string $string The text to encode
3033
     *
3034
     * @return string
3035
     */
3036
    public function encodeQP($string)
3037
    {
3038
        return static::normalizeBreaks(quoted_printable_encode($string));
3039
    }
3040
3041
    /**
3042
     * Encode a string using Q encoding.
3043
     *
3044
     * @param string $str the text to encode
3045
     * @param string $position Where the text is going to be used, see the RFC for what that means
3046
     *
3047
     * @return string
3048
     * @see    http://tools.ietf.org/html/rfc2047
3049
     */
3050
    public function encodeQ($str, $position = 'text')
3051
    {
3052
        // There should not be any EOL in the string
3053
        $pattern = '';
3054
        $encoded = str_replace(["\r", "\n"], '', $str);
3055
        switch (strtolower($position)) {
3056
            case 'phrase':
3057
                // RFC 2047 section 5.3
3058
                $pattern = '^A-Za-z0-9!*+\/ -';
3059
                break;
3060
            /**
3061
             * RFC 2047 section 5.2.
3062
             * Build $pattern without including delimiters and []
3063
             */
3064
            /** @noinspection PhpMissingBreakStatementInspection */
3065
            case 'comment':
3066
                 $pattern = '\(\)"';
3067
                /* Intentional fall through */
3068
            case 'text':
3069
            default:
3070
                // RFC 2047 section 5.1
3071
                // Replace every high ascii, control, =, ? and _ characters
3072
                $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
3073
                break;
3074
        }
3075
        $matches = [];
3076
        if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
3077
            // If the string contains an '=', make sure it's the first thing we replace
3078
            // so as to avoid double-encoding
3079
            $eqkey = array_search('=', $matches[0]);
3080
            if (false !== $eqkey) {
3081
                unset($matches[0][$eqkey]);
3082
                array_unshift($matches[0], '=');
3083
            }
3084
            foreach (array_unique($matches[0]) as $char) {
3085
                $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
3086
            }
3087
        }
3088
        // Replace spaces with _ (more readable than =20)
3089
        // RFC 2047 section 4.2(2)
3090
        return str_replace(' ', '_', $encoded);
3091
    }
3092
3093
    /**
3094
     * Add a string or binary attachment (non-filesystem).
3095
     * This method can be used to attach ascii or binary data,
3096
     * such as a BLOB record from a database.
3097
     *
3098
     * @param string $string String attachment data.
3099
     * @param string $filename Name of the attachment.
3100
     * @param string $encoding File encoding (see $Encoding).
3101
     * @param string $type File extension (MIME) type.
3102
     * @param string $disposition Disposition to use
3103
     */
3104
    public function addStringAttachment(
3105
        $string,
3106
        $filename,
3107
        $encoding = 'base64',
3108
        $type = '',
3109
        $disposition = 'attachment'
3110
    ) {
3111
        // If a MIME type is not specified, try to work it out from the file name
3112
        if ('' == $type) {
3113
            $type = static::filenameToType($filename);
3114
        }
3115
        // Append to $attachment array
3116
        $this->attachment[] = [
3117
            0 => $string,
3118
            1 => $filename,
3119
            2 => basename($filename),
3120
            3 => $encoding,
3121
            4 => $type,
3122
            5 => true, // isStringAttachment
3123
            6 => $disposition,
3124
            7 => 0
3125
        ];
3126
    }
3127
3128
    /**
3129
     * Add an embedded (inline) attachment from a file.
3130
     * This can include images, sounds, and just about any other document type.
3131
     * These differ from 'regular' attachments in that they are intended to be
3132
     * displayed inline with the message, not just attached for download.
3133
     * This is used in HTML messages that embed the images
3134
     * the HTML refers to using the $cid value.
3135
     * Never use a user-supplied path to a file!
3136
     *
3137
     * @param string $path Path to the attachment.
3138
     * @param string $cid Content ID of the attachment; Use this to reference
3139
     *        the content when using an embedded image in HTML.
3140
     * @param string $name Overrides the attachment name.
3141
     * @param string $encoding File encoding (see $Encoding).
3142
     * @param string $type File MIME type.
3143
     * @param string $disposition Disposition to use
3144
     *
3145
     * @return boolean True on successfully adding an attachment
3146
     */
3147
    public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline')
3148
    {
3149
        if (!@is_file($path)) {
3150
            $this->setError($this->lang('file_access') . $path);
3151
            return false;
3152
        }
3153
3154
        // If a MIME type is not specified, try to work it out from the file name
3155
        if ('' == $type) {
3156
            $type = static::filenameToType($path);
3157
        }
3158
3159
        $filename = basename($path);
3160
        if ('' == $name) {
3161
            $name = $filename;
3162
        }
3163
3164
        // Append to $attachment array
3165
        $this->attachment[] = [
3166
            0 => $path,
3167
            1 => $filename,
3168
            2 => $name,
3169
            3 => $encoding,
3170
            4 => $type,
3171
            5 => false, // isStringAttachment
3172
            6 => $disposition,
3173
            7 => $cid
3174
        ];
3175
        return true;
3176
    }
3177
3178
    /**
3179
     * Add an embedded stringified attachment.
3180
     * This can include images, sounds, and just about any other document type.
3181
     * Be sure to set the $type to an image type for images:
3182
     * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
3183
     *
3184
     * @param string $string The attachment binary data.
3185
     * @param string $cid Content ID of the attachment; Use this to reference
3186
     *        the content when using an embedded image in HTML.
3187
     * @param string $name
3188
     * @param string $encoding File encoding (see $Encoding).
3189
     * @param string $type MIME type.
3190
     * @param string $disposition Disposition to use
3191
     *
3192
     * @return boolean True on successfully adding an attachment
3193
     */
3194
    public function addStringEmbeddedImage(
3195
        $string,
3196
        $cid,
3197
        $name = '',
3198
        $encoding = 'base64',
3199
        $type = '',
3200
        $disposition = 'inline'
3201
    ) {
3202
        // If a MIME type is not specified, try to work it out from the name
3203
        if ('' == $type and !empty($name)) {
3204
            $type = static::filenameToType($name);
3205
        }
3206
3207
        // Append to $attachment array
3208
        $this->attachment[] = [
3209
            0 => $string,
3210
            1 => $name,
3211
            2 => $name,
3212
            3 => $encoding,
3213
            4 => $type,
3214
            5 => true, // isStringAttachment
3215
            6 => $disposition,
3216
            7 => $cid
3217
        ];
3218
        return true;
3219
    }
3220
3221
    /**
3222
     * Check if an embedded attachment is present with this cid.
3223
     *
3224
     * @param string $cid
3225
     *
3226
     * @return boolean
3227
     */
3228
    protected function cidExists($cid)
3229
    {
3230
        foreach ($this->attachment as $attachment) {
3231
            if ('inline' == $attachment[6] and $cid == $attachment[7]) {
3232
                return true;
3233
            }
3234
        }
3235
        return false;
3236
    }
3237
3238
    /**
3239
     * Check if an inline attachment is present.
3240
     *
3241
     * @return boolean
3242
     */
3243
    public function inlineImageExists()
3244
    {
3245
        foreach ($this->attachment as $attachment) {
3246
            if ($attachment[6] == 'inline') {
3247
                return true;
3248
            }
3249
        }
3250
        return false;
3251
    }
3252
3253
    /**
3254
     * Check if an attachment (non-inline) is present.
3255
     *
3256
     * @return boolean
3257
     */
3258
    public function attachmentExists()
3259
    {
3260
        foreach ($this->attachment as $attachment) {
3261
            if ($attachment[6] == 'attachment') {
3262
                return true;
3263
            }
3264
        }
3265
        return false;
3266
    }
3267
3268
    /**
3269
     * Check if this message has an alternative body set.
3270
     *
3271
     * @return boolean
3272
     */
3273
    public function alternativeExists()
3274
    {
3275
        return !empty($this->AltBody);
3276
    }
3277
3278
    /**
3279
     * Clear queued addresses of given kind.
3280
     *
3281
     * @param string $kind 'to', 'cc', or 'bcc'
3282
     */
3283
    public function clearQueuedAddresses($kind)
3284
    {
3285
        $this->RecipientsQueue = array_filter(
3286
            $this->RecipientsQueue,
3287
            function ($params) use ($kind) {
3288
                return $params[0] != $kind;
3289
            }
3290
        );
3291
    }
3292
3293
    /**
3294
     * Clear all To recipients.
3295
     */
3296
    public function clearAddresses()
3297
    {
3298
        foreach ($this->to as $to) {
3299
            unset($this->all_recipients[strtolower($to[0])]);
3300
        }
3301
        $this->to = [];
3302
        $this->clearQueuedAddresses('to');
3303
    }
3304
3305
    /**
3306
     * Clear all CC recipients.
3307
     */
3308
    public function clearCCs()
3309
    {
3310
        foreach ($this->cc as $cc) {
3311
            unset($this->all_recipients[strtolower($cc[0])]);
3312
        }
3313
        $this->cc = [];
3314
        $this->clearQueuedAddresses('cc');
3315
    }
3316
3317
    /**
3318
     * Clear all BCC recipients.
3319
     */
3320
    public function clearBCCs()
3321
    {
3322
        foreach ($this->bcc as $bcc) {
3323
            unset($this->all_recipients[strtolower($bcc[0])]);
3324
        }
3325
        $this->bcc = [];
3326
        $this->clearQueuedAddresses('bcc');
3327
    }
3328
3329
    /**
3330
     * Clear all ReplyTo recipients.
3331
     */
3332
    public function clearReplyTos()
3333
    {
3334
        $this->ReplyTo = [];
3335
        $this->ReplyToQueue = [];
3336
    }
3337
3338
    /**
3339
     * Clear all recipient types.
3340
     */
3341
    public function clearAllRecipients()
3342
    {
3343
        $this->to = [];
3344
        $this->cc = [];
3345
        $this->bcc = [];
3346
        $this->all_recipients = [];
3347
        $this->RecipientsQueue = [];
3348
    }
3349
3350
    /**
3351
     * Clear all filesystem, string, and binary attachments.
3352
     */
3353
    public function clearAttachments()
3354
    {
3355
        $this->attachment = [];
3356
    }
3357
3358
    /**
3359
     * Clear all custom headers.
3360
     */
3361
    public function clearCustomHeaders()
3362
    {
3363
        $this->CustomHeader = [];
3364
    }
3365
3366
    /**
3367
     * Add an error message to the error container.
3368
     *
3369
     * @param string $msg
3370
     */
3371
    protected function setError($msg)
3372
    {
3373
        ++$this->error_count;
3374
        if ('smtp' == $this->Mailer and !is_null($this->smtp)) {
3375
            $lasterror = $this->smtp->getError();
3376
            if (!empty($lasterror['error'])) {
3377
                $msg .= $this->lang('smtp_error') . $lasterror['error'];
3378
                if (!empty($lasterror['detail'])) {
3379
                    $msg .= ' Detail: '. $lasterror['detail'];
3380
                }
3381
                if (!empty($lasterror['smtp_code'])) {
3382
                    $msg .= ' SMTP code: ' . $lasterror['smtp_code'];
3383
                }
3384
                if (!empty($lasterror['smtp_code_ex'])) {
3385
                    $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex'];
3386
                }
3387
            }
3388
        }
3389
        $this->ErrorInfo = $msg;
3390
    }
3391
3392
    /**
3393
     * Return an RFC 822 formatted date.
3394
     *
3395
     * @return string
3396
     */
3397
    public static function rfcDate()
3398
    {
3399
        // Set the time zone to whatever the default is to avoid 500 errors
3400
        // Will default to UTC if it's not set properly in php.ini
3401
        date_default_timezone_set(@date_default_timezone_get());
3402
        return date('D, j M Y H:i:s O');
3403
    }
3404
3405
    /**
3406
     * Get the server hostname.
3407
     * Returns 'localhost.localdomain' if unknown.
3408
     *
3409
     * @return string
3410
     */
3411
    protected function serverHostname()
3412
    {
3413
        $result = '';
3414
        if (!empty($this->Hostname)) {
3415
            $result = $this->Hostname;
3416
        } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER)) {
3417
            $result = $_SERVER['SERVER_NAME'];
3418
        } elseif (function_exists('gethostname') and gethostname() !== false) {
3419
            $result = gethostname();
3420
        } elseif (php_uname('n') !== false) {
3421
            $result = php_uname('n');
3422
        }
3423
        if (!static::isValidHost($result)) {
3424
            return 'localhost.localdomain';
3425
        } else {
3426
            return $result;
3427
        }
3428
    }
3429
3430
    /**
3431
     * Validate whether a string contains a valid value to use as a hostname or IP address.
3432
     * IPv6 addresses must include [], e.g. `[::1]`, not just `::1`.
3433
     *
3434
     * @param string $host The host name or IP address to check
3435
     * @return bool
3436
     */
3437
    public static function isValidHost($host)
3438
    {
3439
        //Simple syntax limits
3440
        if (empty($host)
3441
            or !is_string($host)
3442
            or strlen($host) > 256
3443
        ) {
3444
            return false;
3445
        }
3446
        //Looks like a bracketed IPv6 address
3447
        if (trim($host, '[]') != $host) {
3448
            return (boolean)filter_var(trim($host, '[]'), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
3449
        }
3450
        //If removing all the dots results in a numeric string, it must be an IPv4 address.
3451
        //Need to check this first because otherwise things like `999.0.0.0` are considered valid host names
3452
        if (is_numeric(str_replace('.', '', $host))) {
3453
            //Is it a valid IPv4 address?
3454
            return (boolean)filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
3455
        }
3456
        if (filter_var('http://' . $host, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)) {
3457
            //Is it a syntactically valid hostname?
3458
            return true;
3459
        }
3460
        return false;
3461
    }
3462
3463
    /**
3464
     * Get an error message in the current language.
3465
     *
3466
     * @param string $key
3467
     *
3468
     * @return string
3469
     */
3470
    protected function lang($key)
3471
    {
3472
        if (count($this->language) < 1) {
3473
            $this->setLanguage('en'); // set the default language
3474
        }
3475
3476
        if (array_key_exists($key, $this->language)) {
3477
            if ('smtp_connect_failed' == $key) {
3478
                //Include a link to troubleshooting docs on SMTP connection failure
3479
                //this is by far the biggest cause of support questions
3480
                //but it's usually not PHPMailer's fault.
3481
                return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
3482
            }
3483
            return $this->language[$key];
3484
        } else {
3485
            //Return the key as a fallback
3486
            return $key;
3487
        }
3488
    }
3489
3490
    /**
3491
     * Check if an error occurred.
3492
     *
3493
     * @return boolean True if an error did occur.
3494
     */
3495
    public function isError()
3496
    {
3497
        return ($this->error_count > 0);
3498
    }
3499
3500
    /**
3501
     * Add a custom header.
3502
     * $name value can be overloaded to contain
3503
     * both header name and value (name:value)
3504
     *
3505
     * @param string $name Custom header name
3506
     * @param string $value Header value
3507
     */
3508
    public function addCustomHeader($name, $value = null)
3509
    {
3510
        if (is_null($value)) {
3511
            // Value passed in as name:value
3512
            $this->CustomHeader[] = explode(':', $name, 2);
3513
        } else {
3514
            $this->CustomHeader[] = [$name, $value];
3515
        }
3516
    }
3517
3518
    /**
3519
     * Returns all custom headers.
3520
     *
3521
     * @return array
3522
     */
3523
    public function getCustomHeaders()
3524
    {
3525
        return $this->CustomHeader;
3526
    }
3527
3528
    /**
3529
     * Create a message body from an HTML string.
3530
     * Automatically inlines images and creates a plain-text version by converting the HTML,
3531
     * overwriting any existing values in Body and AltBody.
3532
     * Do not source $message content from user input!
3533
     * $basedir is prepended when handling relative URLs, e.g. <img src="/images/a.png"> and must not be empty
3534
     * will look for an image file in $basedir/images/a.png and convert it to inline.
3535
     * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email)
3536
     * Converts data-uri images into embedded attachments.
3537
     * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly.
3538
     *
3539
     * @access public
3540
     * @param string $message HTML message string
3541
     * @param string $basedir Absolute path to a base directory to prepend to relative paths to images
3542
     * @param boolean|callable $advanced Whether to use the internal HTML to text converter
3543
     *    or your own custom converter @see PHPMailer::html2text()
3544
     * @return string $message The transformed message Body
3545
     *
3546
     * @return string $message
3547
     */
3548
    public function msgHTML($message, $basedir = '', $advanced = false)
3549
    {
3550
        preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
3551
        if (array_key_exists(2, $images)) {
3552
            if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
3553
                // Ensure $basedir has a trailing /
3554
                $basedir .= '/';
3555
            }
3556
            foreach ($images[2] as $imgindex => $url) {
3557
                // Convert data URIs into embedded images
3558
                //e.g. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
3559
                if (preg_match('#^data:(image/(?:jpe?g|gif|png));?(base64)?,(.+)#', $url, $match)) {
3560
                    if (count($match) == 4 and 'base64' == $match[2]) {
3561
                        $data = base64_decode($match[3]);
3562
                    } elseif ('' == $match[2]) {
3563
                        $data = rawurldecode($match[3]);
3564
                    } else {
3565
                        //Not recognised so leave it alone
3566
                        continue;
3567
                    }
3568
                    //Hash the decoded data, not the URL so that the same data-URI image used in multiple places
3569
                    //will only be embedded once, even if it used a different encoding
3570
                    $cid = hash('sha256', $data) . '@phpmailer.0'; // RFC2392 S 2
3571
3572
                    if (!$this->cidExists($cid)) {
3573
                        $this->addStringEmbeddedImage($data, $cid, 'embed' . $imgindex, 'base64', $match[1]);
3574
                    }
3575
                    $message = str_replace(
3576
                        $images[0][$imgindex],
3577
                        $images[1][$imgindex] . '="cid:' . $cid . '"',
3578
                        $message
3579
                    );
3580
                    continue;
3581
                }
3582
                if (// Only process relative URLs if a basedir is provided (i.e. no absolute local paths)
3583
                    !empty($basedir)
3584
                    // Ignore URLs containing parent dir traversal (..)
3585
                    and (strpos($url, '..') === false)
3586
                    // Do not change urls that are already inline images
3587
                    and substr($url, 0, 4) !== 'cid:'
3588
                    // Do not change absolute URLs, including anonymous protocol
3589
                    and !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url)
3590
                ) {
3591
                    $filename = basename($url);
3592
                    $directory = dirname($url);
3593
                    if ('.' == $directory) {
3594
                        $directory = '';
3595
                    }
3596
                    $cid = hash('sha256', $url) . '@phpmailer.0'; // RFC2392 S 2
3597
                    if (strlen($basedir) > 1 and substr($basedir, -1) != '/') {
3598
                        $basedir .= '/';
3599
                    }
3600
                    if (strlen($directory) > 1 and substr($directory, -1) != '/') {
3601
                        $directory .= '/';
3602
                    }
3603
                    if ($this->addEmbeddedImage(
3604
                        $basedir . $directory . $filename,
3605
                        $cid,
3606
                        $filename,
3607
                        'base64',
3608
                        static::_mime_types((string)static::mb_pathinfo($filename, PATHINFO_EXTENSION))
3609
                    )
3610
                    ) {
3611
                        $message = preg_replace(
3612
                            '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
3613
                            $images[1][$imgindex] . '="cid:' . $cid . '"',
3614
                            $message
3615
                        );
3616
                    }
3617
                }
3618
            }
3619
        }
3620
        $this->isHTML(true);
3621
        // Convert all message body line breaks to LE, makes quoted-printable encoding work much better
3622
        $this->Body = static::normalizeBreaks($message);
3623
        $this->AltBody = static::normalizeBreaks($this->html2text($message, $advanced));
3624
        if (!$this->alternativeExists()) {
3625
            $this->AltBody = 'This is an HTML-only message. To view it, activate HTML in your email application.'
3626
                . static::$LE;
3627
        }
3628
        return $this->Body;
3629
    }
3630
3631
    /**
3632
     * Convert an HTML string into plain text.
3633
     * This is used by msgHTML().
3634
     * Note - older versions of this function used a bundled advanced converter
3635
     * which was removed for license reasons in #232.
3636
     * Example usage:
3637
     * <code>
3638
     * // Use default conversion
3639
     * $plain = $mail->html2text($html);
3640
     * // Use your own custom converter
3641
     * $plain = $mail->html2text($html, function($html) {
3642
     *     $converter = new MyHtml2text($html);
3643
     *     return $converter->get_text();
3644
     * });
3645
     * </code>
3646
     *
3647
     * @param string $html The HTML text to convert
3648
     * @param boolean|callable $advanced Any boolean value to use the internal converter,
3649
     *   or provide your own callable for custom conversion.
3650
     *
3651
     * @return string
3652
     */
3653
    public function html2text($html, $advanced = false)
3654
    {
3655
        if (is_callable($advanced)) {
3656
            return call_user_func($advanced, $html);
3657
        }
3658
        return html_entity_decode(
3659
            trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
3660
            ENT_QUOTES,
3661
            $this->CharSet
3662
        );
3663
    }
3664
3665
    /**
3666
     * Get the MIME type for a file extension.
3667
     *
3668
     * @param string $ext File extension
3669
     *
3670
     * @return string MIME type of file.
3671
     */
3672
    public static function _mime_types($ext = '')
3673
    {
3674
        $mimes = [
3675
            'xl'    => 'application/excel',
3676
            'js'    => 'application/javascript',
3677
            'hqx'   => 'application/mac-binhex40',
3678
            'cpt'   => 'application/mac-compactpro',
3679
            'bin'   => 'application/macbinary',
3680
            'doc'   => 'application/msword',
3681
            'word'  => 'application/msword',
3682
            'xlsx'  => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
3683
            'xltx'  => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
3684
            'potx'  => 'application/vnd.openxmlformats-officedocument.presentationml.template',
3685
            'ppsx'  => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
3686
            'pptx'  => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
3687
            'sldx'  => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
3688
            'docx'  => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
3689
            'dotx'  => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
3690
            'xlam'  => 'application/vnd.ms-excel.addin.macroEnabled.12',
3691
            'xlsb'  => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
3692
            'class' => 'application/octet-stream',
3693
            'dll'   => 'application/octet-stream',
3694
            'dms'   => 'application/octet-stream',
3695
            'exe'   => 'application/octet-stream',
3696
            'lha'   => 'application/octet-stream',
3697
            'lzh'   => 'application/octet-stream',
3698
            'psd'   => 'application/octet-stream',
3699
            'sea'   => 'application/octet-stream',
3700
            'so'    => 'application/octet-stream',
3701
            'oda'   => 'application/oda',
3702
            'pdf'   => 'application/pdf',
3703
            'ai'    => 'application/postscript',
3704
            'eps'   => 'application/postscript',
3705
            'ps'    => 'application/postscript',
3706
            'smi'   => 'application/smil',
3707
            'smil'  => 'application/smil',
3708
            'mif'   => 'application/vnd.mif',
3709
            'xls'   => 'application/vnd.ms-excel',
3710
            'ppt'   => 'application/vnd.ms-powerpoint',
3711
            'wbxml' => 'application/vnd.wap.wbxml',
3712
            'wmlc'  => 'application/vnd.wap.wmlc',
3713
            'dcr'   => 'application/x-director',
3714
            'dir'   => 'application/x-director',
3715
            'dxr'   => 'application/x-director',
3716
            'dvi'   => 'application/x-dvi',
3717
            'gtar'  => 'application/x-gtar',
3718
            'php3'  => 'application/x-httpd-php',
3719
            'php4'  => 'application/x-httpd-php',
3720
            'php'   => 'application/x-httpd-php',
3721
            'phtml' => 'application/x-httpd-php',
3722
            'phps'  => 'application/x-httpd-php-source',
3723
            'swf'   => 'application/x-shockwave-flash',
3724
            'sit'   => 'application/x-stuffit',
3725
            'tar'   => 'application/x-tar',
3726
            'tgz'   => 'application/x-tar',
3727
            'xht'   => 'application/xhtml+xml',
3728
            'xhtml' => 'application/xhtml+xml',
3729
            'zip'   => 'application/zip',
3730
            'mid'   => 'audio/midi',
3731
            'midi'  => 'audio/midi',
3732
            'mp2'   => 'audio/mpeg',
3733
            'mp3'   => 'audio/mpeg',
3734
            'mpga'  => 'audio/mpeg',
3735
            'aif'   => 'audio/x-aiff',
3736
            'aifc'  => 'audio/x-aiff',
3737
            'aiff'  => 'audio/x-aiff',
3738
            'ram'   => 'audio/x-pn-realaudio',
3739
            'rm'    => 'audio/x-pn-realaudio',
3740
            'rpm'   => 'audio/x-pn-realaudio-plugin',
3741
            'ra'    => 'audio/x-realaudio',
3742
            'wav'   => 'audio/x-wav',
3743
            'bmp'   => 'image/bmp',
3744
            'gif'   => 'image/gif',
3745
            'jpeg'  => 'image/jpeg',
3746
            'jpe'   => 'image/jpeg',
3747
            'jpg'   => 'image/jpeg',
3748
            'png'   => 'image/png',
3749
            'tiff'  => 'image/tiff',
3750
            'tif'   => 'image/tiff',
3751
            'eml'   => 'message/rfc822',
3752
            'css'   => 'text/css',
3753
            'html'  => 'text/html',
3754
            'htm'   => 'text/html',
3755
            'shtml' => 'text/html',
3756
            'log'   => 'text/plain',
3757
            'text'  => 'text/plain',
3758
            'txt'   => 'text/plain',
3759
            'rtx'   => 'text/richtext',
3760
            'rtf'   => 'text/rtf',
3761
            'vcf'   => 'text/vcard',
3762
            'vcard' => 'text/vcard',
3763
            'ics'   => 'text/calendar',
3764
            'xml'   => 'text/xml',
3765
            'xsl'   => 'text/xml',
3766
            'mpeg'  => 'video/mpeg',
3767
            'mpe'   => 'video/mpeg',
3768
            'mpg'   => 'video/mpeg',
3769
            'mov'   => 'video/quicktime',
3770
            'qt'    => 'video/quicktime',
3771
            'rv'    => 'video/vnd.rn-realvideo',
3772
            'avi'   => 'video/x-msvideo',
3773
            'movie' => 'video/x-sgi-movie'
3774
        ];
3775
        if (array_key_exists(strtolower($ext), $mimes)) {
3776
            return $mimes[strtolower($ext)];
3777
        }
3778
        return 'application/octet-stream';
3779
    }
3780
3781
    /**
3782
     * Map a file name to a MIME type.
3783
     * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
3784
     *
3785
     * @param string $filename A file name or full path, does not need to exist as a file
3786
     *
3787
     * @return string
3788
     */
3789
    public static function filenameToType($filename)
3790
    {
3791
        // In case the path is a URL, strip any query string before getting extension
3792
        $qpos = strpos($filename, '?');
3793
        if (false !== $qpos) {
3794
            $filename = substr($filename, 0, $qpos);
3795
        }
3796
        $ext = static::mb_pathinfo($filename, PATHINFO_EXTENSION);
3797
        return static::_mime_types($ext);
3798
    }
3799
3800
    /**
3801
     * Multi-byte-safe pathinfo replacement.
3802
     * Drop-in replacement for pathinfo(), but multibyte- and cross-platform-safe
3803
     *
3804
     * @param string $path A filename or path, does not need to exist as a file
3805
     * @param integer|string $options Either a PATHINFO_* constant,
3806
     *      or a string name to return only the specified piece
3807
     *
3808
     * @see    http://www.php.net/manual/en/function.pathinfo.php#107461
3809
     * @return string|array
3810
     */
3811
    public static function mb_pathinfo($path, $options = null)
3812
    {
3813
        $ret = ['dirname' => '', 'basename' => '', 'extension' => '', 'filename' => ''];
3814
        $pathinfo = [];
3815
        if (preg_match('#^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$#im', $path, $pathinfo)) {
3816
            if (array_key_exists(1, $pathinfo)) {
3817
                $ret['dirname'] = $pathinfo[1];
3818
            }
3819
            if (array_key_exists(2, $pathinfo)) {
3820
                $ret['basename'] = $pathinfo[2];
3821
            }
3822
            if (array_key_exists(5, $pathinfo)) {
3823
                $ret['extension'] = $pathinfo[5];
3824
            }
3825
            if (array_key_exists(3, $pathinfo)) {
3826
                $ret['filename'] = $pathinfo[3];
3827
            }
3828
        }
3829
        switch ($options) {
3830
            case PATHINFO_DIRNAME:
3831
            case 'dirname':
3832
                return $ret['dirname'];
3833
            case PATHINFO_BASENAME:
3834
            case 'basename':
3835
                return $ret['basename'];
3836
            case PATHINFO_EXTENSION:
3837
            case 'extension':
3838
                return $ret['extension'];
3839
            case PATHINFO_FILENAME:
3840
            case 'filename':
3841
                return $ret['filename'];
3842
            default:
3843
                return $ret;
3844
        }
3845
    }
3846
3847
    /**
3848
     * Set or reset instance properties.
3849
     * You should avoid this function - it's more verbose, less efficient, more error-prone and
3850
     * harder to debug than setting properties directly.
3851
     * Usage Example:
3852
     * `$mail->set('SMTPSecure', 'tls');`
3853
     *   is the same as:
3854
     * `$mail->SMTPSecure = 'tls';`
3855
     *
3856
     * @param string $name The property name to set
3857
     * @param mixed $value The value to set the property to
3858
     *
3859
     * @return boolean
3860
     */
3861
    public function set($name, $value = '')
3862
    {
3863
        if (property_exists($this, $name)) {
3864
            $this->$name = $value;
3865
            return true;
3866
        } else {
3867
            $this->setError($this->lang('variable_set') . $name);
3868
            return false;
3869
        }
3870
    }
3871
3872
    /**
3873
     * Strip newlines to prevent header injection.
3874
     *
3875
     * @param string $str
3876
     *
3877
     * @return string
3878
     */
3879
    public function secureHeader($str)
3880
    {
3881
        return trim(str_replace(["\r", "\n"], '', $str));
3882
    }
3883
3884
    /**
3885
     * Normalize line breaks in a string.
3886
     * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
3887
     * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
3888
     *
3889
     * @param string $text
3890
     * @param string $breaktype What kind of line break to use; defaults to static::$LE.
3891
     *
3892
     * @return string
3893
     */
3894
    public static function normalizeBreaks($text, $breaktype = null)
3895
    {
3896
        if (is_null($breaktype)) {
3897
            $breaktype = static::$LE;
3898
        }
3899
        // Normalise to \n
3900
        $text = str_replace(["\r\n", "\r"], "\n", $text);
3901
        // Now convert LE as needed
3902
        if ("\n" !== static::$LE) {
3903
            $text = str_replace("\n", $breaktype, $text);
3904
        }
3905
        return $text;
3906
    }
3907
3908
    /**
3909
     * Return the current line break format string.
3910
     *
3911
     * @return string
3912
     */
3913
    public static function getLE()
3914
    {
3915
        return static::$LE;
3916
    }
3917
3918
    /**
3919
     * Set the line break format string, e.g. "\r\n".
3920
     *
3921
     * @param string $le
3922
     */
3923
    protected static function setLE($le)
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $le. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
3924
    {
3925
        static::$LE = $le;
3926
    }
3927
3928
    /**
3929
     * Set the public and private key files and password for S/MIME signing.
3930
     *
3931
     * @param string $cert_filename
3932
     * @param string $key_filename
3933
     * @param string $key_pass Password for private key
3934
     * @param string $extracerts_filename Optional path to chain certificate
3935
     */
3936
    public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
3937
    {
3938
        $this->sign_cert_file = $cert_filename;
3939
        $this->sign_key_file = $key_filename;
3940
        $this->sign_key_pass = $key_pass;
3941
        $this->sign_extracerts_file = $extracerts_filename;
3942
    }
3943
3944
    /**
3945
     * Quoted-Printable-encode a DKIM header.
3946
     *
3947
     * @param string $txt
3948
     *
3949
     * @return string
3950
     */
3951
    public function DKIM_QP($txt)
3952
    {
3953
        $line = '';
3954
        $len = strlen($txt);
3955
        for ($i = 0; $i < $len; ++$i) {
3956
            $ord = ord($txt[$i]);
3957
            if (((0x21 <= $ord) and ($ord <= 0x3A)) or $ord == 0x3C or ((0x3E <= $ord) and ($ord <= 0x7E))) {
3958
                $line .= $txt[$i];
3959
            } else {
3960
                $line .= '=' . sprintf('%02X', $ord);
3961
            }
3962
        }
3963
        return $line;
3964
    }
3965
3966
    /**
3967
     * Generate a DKIM signature.
3968
     *
3969
     * @param string $signHeader
3970
     *
3971
     * @throws Exception
3972
     * @return string The DKIM signature value
3973
     */
3974
    public function DKIM_Sign($signHeader)
3975
    {
3976
        if (!defined('PKCS7_TEXT')) {
3977
            if ($this->exceptions) {
3978
                throw new Exception($this->lang('extension_missing') . 'openssl');
3979
            }
3980
            return '';
3981
        }
3982
        $privKeyStr = !empty($this->DKIM_private_string) ?
3983
                $this->DKIM_private_string :
3984
                file_get_contents($this->DKIM_private);
3985
        if ('' != $this->DKIM_passphrase) {
3986
            $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
3987
        } else {
3988
            $privKey = openssl_pkey_get_private($privKeyStr);
3989
        }
3990
        if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) {
3991
            openssl_pkey_free($privKey);
3992
            return base64_encode($signature);
3993
        }
3994
        openssl_pkey_free($privKey);
3995
        return '';
3996
    }
3997
3998
    /**
3999
     * Generate a DKIM canonicalization header.
4000
     * Uses the 'relaxed' algorithm from RFC6376 section 3.4.2
4001
     *
4002
     * @param string $signHeader Header
4003
     *
4004
     * @return string
4005
     * @see    https://tools.ietf.org/html/rfc6376#section-3.4.2
4006
     */
4007
    public function DKIM_HeaderC($signHeader)
4008
    {
4009
        //Unfold all header continuation lines
4010
        //Also collapses folded whitespace.
4011
        //Note PCRE \s is too broad a definition of whitespace; RFC5322 defines it as [ \t]
4012
        //@see https://tools.ietf.org/html/rfc5322#section-2.2
4013
        //That means this may break if you do something daft like put vertical tabs in your headers.
4014
        $signHeader = preg_replace('/\r\n[ \t]+/', ' ', $signHeader);
4015
        $lines = explode("\r\n", $signHeader);
4016
        foreach ($lines as $key => $line) {
4017
            //If the header is missing a :, skip it as it's invalid
4018
            //This is likely to happen because the explode() above will also split
4019
            //on the trailing LE, leaving an empty line
4020
            if (strpos($line, ':') === false) {
4021
                continue;
4022
            }
4023
            list($heading, $value) = explode(':', $line, 2);
4024
            //Lower-case header name
4025
            $heading = strtolower($heading);
4026
            //Collapse white space within the value
4027
            $value = preg_replace('/[ \t]{2,}/', ' ', $value);
4028
            //RFC6376 is slightly unclear here - it says to delete space at the *end* of each value
4029
            //But then says to delete space before and after the colon.
4030
            //Net result is the same as trimming both ends of the value.
4031
            //by elimination, the same applies to the field name
4032
            $lines[$key] = trim($heading, " \t") . ':' . trim($value, " \t");
4033
        }
4034
        $signHeader = implode(static::$LE, $lines);
4035
        return $signHeader;
4036
    }
4037
4038
    /**
4039
     * Generate a DKIM canonicalization body.
4040
     * Uses the 'simple' algorithm from RFC6376 section 3.4.3
4041
     *
4042
     * @param string $body Message Body
4043
     *
4044
     * @return string
4045
     * @see    https://tools.ietf.org/html/rfc6376#section-3.4.3
4046
     */
4047
    public function DKIM_BodyC($body)
4048
    {
4049
        if (empty($body)) {
4050
            return static::$LE;
4051
        }
4052
        // Normalize line endings
4053
        $body = static::normalizeBreaks($body);
4054
        //Reduce multiple trailing line breaks to a single one
4055
        return rtrim($body, "\r\n") . static::$LE;
4056
    }
4057
4058
    /**
4059
     * Create the DKIM header and body in a new message header.
4060
     *
4061
     * @param string $headers_line Header lines
4062
     * @param string $subject Subject
4063
     * @param string $body Body
4064
     *
4065
     * @return string
4066
     */
4067
    public function DKIM_Add($headers_line, $subject, $body)
4068
    {
4069
        $DKIMsignatureType = 'rsa-sha256'; // Signature & hash algorithms
4070
        $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
4071
        $DKIMquery = 'dns/txt'; // Query method
4072
        $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
4073
        $subject_header = "Subject: $subject";
4074
        $headers = explode(static::$LE, $headers_line);
4075
        $from_header = '';
4076
        $to_header = '';
4077
        $date_header = '';
4078
        $current = '';
4079
        foreach ($headers as $header) {
4080
            if (strpos($header, 'From:') === 0) {
4081
                $from_header = $header;
4082
                $current = 'from_header';
4083
            } elseif (strpos($header, 'To:') === 0) {
4084
                $to_header = $header;
4085
                $current = 'to_header';
4086
            } elseif (strpos($header, 'Date:') === 0) {
4087
                $date_header = $header;
4088
                $current = 'date_header';
4089
            } else {
4090
                if (!empty($$current) and strpos($header, ' =?') === 0) {
4091
                    $$current .= $header;
4092
                } else {
4093
                    $current = '';
4094
                }
4095
            }
4096
        }
4097
        $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
4098
        $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
4099
        $date = str_replace('|', '=7C', $this->DKIM_QP($date_header));
4100
        $subject = str_replace(
4101
            '|',
4102
            '=7C',
4103
            $this->DKIM_QP($subject_header)
4104
        ); // Copied header fields (dkim-quoted-printable)
4105
        $body = $this->DKIM_BodyC($body);
4106
        $DKIMlen = strlen($body); // Length of body
4107
        $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); // Base64 of packed binary SHA-256 hash of body
4108
        if ('' == $this->DKIM_identity) {
4109
            $ident = '';
4110
        } else {
4111
            $ident = ' i=' . $this->DKIM_identity . ';';
4112
        }
4113
        $dkimhdrs = 'DKIM-Signature: v=1; a=' .
4114
            $DKIMsignatureType . '; q=' .
4115
            $DKIMquery . '; l=' .
4116
            $DKIMlen . '; s=' .
4117
            $this->DKIM_selector .
4118
            ";\r\n" .
4119
            "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
4120
            "\th=From:To:Date:Subject;\r\n" .
4121
            "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" .
4122
            "\tz=$from\r\n" .
4123
            "\t|$to\r\n" .
4124
            "\t|$date\r\n" .
4125
            "\t|$subject;\r\n" .
4126
            "\tbh=" . $DKIMb64 . ";\r\n" .
4127
            "\tb=";
4128
        $toSign = $this->DKIM_HeaderC(
4129
            $from_header . "\r\n" .
4130
            $to_header . "\r\n" .
4131
            $date_header . "\r\n" .
4132
            $subject_header . "\r\n" .
4133
            $dkimhdrs
4134
        );
4135
        $signed = $this->DKIM_Sign($toSign);
4136
        return static::normalizeBreaks($dkimhdrs . $signed) . static::$LE;
4137
    }
4138
4139
    /**
4140
     * Detect if a string contains a line longer than the maximum line length
4141
     * allowed by RFC 2822 section 2.1.1.
4142
     *
4143
     * @param string $str
4144
     *
4145
     * @return boolean
4146
     */
4147
    public static function hasLineLongerThanMax($str)
4148
    {
4149
        return (boolean)preg_match('/^(.{'.(self::MAX_LINE_LENGTH + strlen(static::$LE)).',})/m', $str);
4150
    }
4151
4152
    /**
4153
     * Allows for public read access to 'to' property.
4154
     *
4155
     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4156
     *
4157
     * @return array
4158
     */
4159
    public function getToAddresses()
4160
    {
4161
        return $this->to;
4162
    }
4163
4164
    /**
4165
     * Allows for public read access to 'cc' property.
4166
     *
4167
     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4168
     *
4169
     * @return array
4170
     */
4171
    public function getCcAddresses()
4172
    {
4173
        return $this->cc;
4174
    }
4175
4176
    /**
4177
     * Allows for public read access to 'bcc' property.
4178
     *
4179
     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4180
     *
4181
     * @return array
4182
     */
4183
    public function getBccAddresses()
4184
    {
4185
        return $this->bcc;
4186
    }
4187
4188
    /**
4189
     * Allows for public read access to 'ReplyTo' property.
4190
     *
4191
     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4192
     *
4193
     * @return array
4194
     */
4195
    public function getReplyToAddresses()
4196
    {
4197
        return $this->ReplyTo;
4198
    }
4199
4200
    /**
4201
     * Allows for public read access to 'all_recipients' property.
4202
     *
4203
     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4204
     *
4205
     * @return array
4206
     */
4207
    public function getAllRecipientAddresses()
4208
    {
4209
        return $this->all_recipients;
4210
    }
4211
4212
    /**
4213
     * Perform a callback.
4214
     *
4215
     * @param boolean $isSent
4216
     * @param array $to
4217
     * @param array $cc
4218
     * @param array $bcc
4219
     * @param string $subject
4220
     * @param string $body
4221
     * @param string $from
4222
     */
4223
    protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from)
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $cc. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
4224
    {
4225
        if (!empty($this->action_function) and is_callable($this->action_function)) {
4226
            call_user_func_array($this->action_function, [$isSent, $to, $cc, $bcc, $subject, $body, $from]);
4227
        }
4228
    }
4229
4230
    /**
4231
     * Get the OAuth instance.
4232
     *
4233
     * @return OAuth
4234
     */
4235
    public function getOAuth()
4236
    {
4237
        return $this->oauth;
4238
    }
4239
4240
    /**
4241
     * Set an OAuth instance.
4242
     *
4243
     * @param OAuth $oauth
4244
     */
4245
    public function setOAuth(OAuth $oauth)
4246
    {
4247
        $this->oauth = $oauth;
4248
    }
4249
}
4250