Completed
Push — master ( 6ae518...b294b4 )
by Marcus
04:42
created

PHPMailer::stripTrailingWSP()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
/**
3
 * PHPMailer - PHP email creation and transport class.
4
 * PHP Version 5.5.
5
 *
6
 * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
7
 *
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 - 2019 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
 * @author Marcus Bointon (Synchro/coolbru) <[email protected]>
27
 * @author Jim Jagielski (jimjag) <[email protected]>
28
 * @author Andy Prevost (codeworxtech) <[email protected]>
29
 * @author Brent R. Matzelle (original founder)
30
 */
31
class PHPMailer
32
{
33
    const CHARSET_ASCII = 'us-ascii';
34
    const CHARSET_ISO88591 = 'iso-8859-1';
35
    const CHARSET_UTF8 = 'utf-8';
36
37
    const CONTENT_TYPE_PLAINTEXT = 'text/plain';
38
    const CONTENT_TYPE_TEXT_CALENDAR = 'text/calendar';
39
    const CONTENT_TYPE_TEXT_HTML = 'text/html';
40
    const CONTENT_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative';
41
    const CONTENT_TYPE_MULTIPART_MIXED = 'multipart/mixed';
42
    const CONTENT_TYPE_MULTIPART_RELATED = 'multipart/related';
43
44
    const ENCODING_7BIT = '7bit';
45
    const ENCODING_8BIT = '8bit';
46
    const ENCODING_BASE64 = 'base64';
47
    const ENCODING_BINARY = 'binary';
48
    const ENCODING_QUOTED_PRINTABLE = 'quoted-printable';
49
50
    const ENCRYPTION_STARTTLS = 'tls';
51
    const ENCRYPTION_SMTPS = 'ssl';
52
53
    const ICAL_METHOD_REQUEST = 'REQUEST';
54
    const ICAL_METHOD_PUBLISH = 'PUBLISH';
55
    const ICAL_METHOD_REPLY = 'REPLY';
56
    const ICAL_METHOD_ADD = 'ADD';
57
    const ICAL_METHOD_CANCEL = 'CANCEL';
58
    const ICAL_METHOD_REFRESH = 'REFRESH';
59
    const ICAL_METHOD_COUNTER = 'COUNTER';
60
    const ICAL_METHOD_DECLINECOUNTER = 'DECLINECOUNTER';
61
62
    /**
63
     * Email priority.
64
     * Options: null (default), 1 = High, 3 = Normal, 5 = low.
65
     * When null, the header is not set at all.
66
     *
67
     * @var int
68
     */
69
    public $Priority;
70
71
    /**
72
     * The character set of the message.
73
     *
74
     * @var string
75
     */
76
    public $CharSet = self::CHARSET_ISO88591;
77
78
    /**
79
     * The MIME Content-type of the message.
80
     *
81
     * @var string
82
     */
83
    public $ContentType = self::CONTENT_TYPE_PLAINTEXT;
84
85
    /**
86
     * The message encoding.
87
     * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
88
     *
89
     * @var string
90
     */
91
    public $Encoding = self::ENCODING_8BIT;
92
93
    /**
94
     * Holds the most recent mailer error message.
95
     *
96
     * @var string
97
     */
98
    public $ErrorInfo = '';
99
100
    /**
101
     * The From email address for the message.
102
     *
103
     * @var string
104
     */
105
    public $From = 'root@localhost';
106
107
    /**
108
     * The From name of the message.
109
     *
110
     * @var string
111
     */
112
    public $FromName = 'Root User';
113
114
    /**
115
     * The envelope sender of the message.
116
     * This will usually be turned into a Return-Path header by the receiver,
117
     * and is the address that bounces will be sent to.
118
     * If not empty, will be passed via `-f` to sendmail or as the 'MAIL FROM' value over SMTP.
119
     *
120
     * @var string
121
     */
122
    public $Sender = '';
123
124
    /**
125
     * The Subject of the message.
126
     *
127
     * @var string
128
     */
129
    public $Subject = '';
130
131
    /**
132
     * An HTML or plain text message body.
133
     * If HTML then call isHTML(true).
134
     *
135
     * @var string
136
     */
137
    public $Body = '';
138
139
    /**
140
     * The plain-text message body.
141
     * This body can be read by mail clients that do not have HTML email
142
     * capability such as mutt & Eudora.
143
     * Clients that can read HTML will view the normal Body.
144
     *
145
     * @var string
146
     */
147
    public $AltBody = '';
148
149
    /**
150
     * An iCal message part body.
151
     * Only supported in simple alt or alt_inline message types
152
     * To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator.
153
     *
154
     * @see http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
155
     * @see http://kigkonsult.se/iCalcreator/
156
     *
157
     * @var string
158
     */
159
    public $Ical = '';
160
161
    /**
162
     * Value-array of "method" in Contenttype header "text/calendar"
163
     *
164
     * @var string[]
165
     */
166
    protected static $IcalMethods = [
167
        self::ICAL_METHOD_REQUEST,
168
        self::ICAL_METHOD_PUBLISH,
169
        self::ICAL_METHOD_REPLY,
170
        self::ICAL_METHOD_ADD,
171
        self::ICAL_METHOD_CANCEL,
172
        self::ICAL_METHOD_REFRESH,
173
        self::ICAL_METHOD_COUNTER,
174
        self::ICAL_METHOD_DECLINECOUNTER,
175
    ];
176
177
    /**
178
     * The complete compiled MIME message body.
179
     *
180
     * @var string
181
     */
182
    protected $MIMEBody = '';
183
184
    /**
185
     * The complete compiled MIME message headers.
186
     *
187
     * @var string
188
     */
189
    protected $MIMEHeader = '';
190
191
    /**
192
     * Extra headers that createHeader() doesn't fold in.
193
     *
194
     * @var string
195
     */
196
    protected $mailHeader = '';
197
198
    /**
199
     * Word-wrap the message body to this number of chars.
200
     * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
201
     *
202
     * @see static::STD_LINE_LENGTH
203
     *
204
     * @var int
205
     */
206
    public $WordWrap = 0;
207
208
    /**
209
     * Which method to use to send mail.
210
     * Options: "mail", "sendmail", or "smtp".
211
     *
212
     * @var string
213
     */
214
    public $Mailer = 'mail';
215
216
    /**
217
     * The path to the sendmail program.
218
     *
219
     * @var string
220
     */
221
    public $Sendmail = '/usr/sbin/sendmail';
222
223
    /**
224
     * Whether mail() uses a fully sendmail-compatible MTA.
225
     * One which supports sendmail's "-oi -f" options.
226
     *
227
     * @var bool
228
     */
229
    public $UseSendmailOptions = true;
230
231
    /**
232
     * The email address that a reading confirmation should be sent to, also known as read receipt.
233
     *
234
     * @var string
235
     */
236
    public $ConfirmReadingTo = '';
237
238
    /**
239
     * The hostname to use in the Message-ID header and as default HELO string.
240
     * If empty, PHPMailer attempts to find one with, in order,
241
     * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value
242
     * 'localhost.localdomain'.
243
     *
244
     * @see PHPMailer::$Helo
245
     *
246
     * @var string
247
     */
248
    public $Hostname = '';
249
250
    /**
251
     * An ID to be used in the Message-ID header.
252
     * If empty, a unique id will be generated.
253
     * You can set your own, but it must be in the format "<id@domain>",
254
     * as defined in RFC5322 section 3.6.4 or it will be ignored.
255
     *
256
     * @see https://tools.ietf.org/html/rfc5322#section-3.6.4
257
     *
258
     * @var string
259
     */
260
    public $MessageID = '';
261
262
    /**
263
     * The message Date to be used in the Date header.
264
     * If empty, the current date will be added.
265
     *
266
     * @var string
267
     */
268
    public $MessageDate = '';
269
270
    /**
271
     * SMTP hosts.
272
     * Either a single hostname or multiple semicolon-delimited hostnames.
273
     * You can also specify a different port
274
     * for each host by using this format: [hostname:port]
275
     * (e.g. "smtp1.example.com:25;smtp2.example.com").
276
     * You can also specify encryption type, for example:
277
     * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
278
     * Hosts will be tried in order.
279
     *
280
     * @var string
281
     */
282
    public $Host = 'localhost';
283
284
    /**
285
     * The default SMTP server port.
286
     *
287
     * @var int
288
     */
289
    public $Port = 25;
290
291
    /**
292
     * The SMTP HELO/EHLO name used for the SMTP connection.
293
     * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find
294
     * one with the same method described above for $Hostname.
295
     *
296
     * @see PHPMailer::$Hostname
297
     *
298
     * @var string
299
     */
300
    public $Helo = '';
301
302
    /**
303
     * What kind of encryption to use on the SMTP connection.
304
     * Options: '', static::ENCRYPTION_STARTTLS, or static::ENCRYPTION_SMTPS.
305
     *
306
     * @var string
307
     */
308
    public $SMTPSecure = '';
309
310
    /**
311
     * Whether to enable TLS encryption automatically if a server supports it,
312
     * even if `SMTPSecure` is not set to 'tls'.
313
     * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
314
     *
315
     * @var bool
316
     */
317
    public $SMTPAutoTLS = true;
318
319
    /**
320
     * Whether to use SMTP authentication.
321
     * Uses the Username and Password properties.
322
     *
323
     * @see PHPMailer::$Username
324
     * @see PHPMailer::$Password
325
     *
326
     * @var bool
327
     */
328
    public $SMTPAuth = false;
329
330
    /**
331
     * Options array passed to stream_context_create when connecting via SMTP.
332
     *
333
     * @var array
334
     */
335
    public $SMTPOptions = [];
336
337
    /**
338
     * SMTP username.
339
     *
340
     * @var string
341
     */
342
    public $Username = '';
343
344
    /**
345
     * SMTP password.
346
     *
347
     * @var string
348
     */
349
    public $Password = '';
350
351
    /**
352
     * SMTP auth type.
353
     * Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2, attempted in that order if not specified.
354
     *
355
     * @var string
356
     */
357
    public $AuthType = '';
358
359
    /**
360
     * An instance of the PHPMailer OAuth class.
361
     *
362
     * @var OAuth
363
     */
364
    protected $oauth;
365
366
    /**
367
     * The SMTP server timeout in seconds.
368
     * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.
369
     *
370
     * @var int
371
     */
372
    public $Timeout = 300;
373
374
    /**
375
     * Comma separated list of DSN notifications
376
     * 'NEVER' under no circumstances a DSN must be returned to the sender.
377
     *         If you use NEVER all other notifications will be ignored.
378
     * 'SUCCESS' will notify you when your mail has arrived at its destination.
379
     * 'FAILURE' will arrive if an error occurred during delivery.
380
     * 'DELAY'   will notify you if there is an unusual delay in delivery, but the actual
381
     *           delivery's outcome (success or failure) is not yet decided.
382
     *
383
     * @see https://tools.ietf.org/html/rfc3461 See section 4.1 for more information about NOTIFY
384
     */
385
    public $dsn = '';
386
387
    /**
388
     * SMTP class debug output mode.
389
     * Debug output level.
390
     * Options:
391
     * * SMTP::DEBUG_OFF: No output
392
     * * SMTP::DEBUG_CLIENT: Client messages
393
     * * SMTP::DEBUG_SERVER: Client and server messages
394
     * * SMTP::DEBUG_CONNECTION: As SERVER plus connection status
395
     * * SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, rarely needed
396
     *
397
     * @see SMTP::$do_debug
398
     *
399
     * @var int
400
     */
401
    public $SMTPDebug = 0;
402
403
    /**
404
     * How to handle debug output.
405
     * Options:
406
     * * `echo` Output plain-text as-is, appropriate for CLI
407
     * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
408
     * * `error_log` Output to error log as configured in php.ini
409
     * By default PHPMailer will use `echo` if run from a `cli` or `cli-server` SAPI, `html` otherwise.
410
     * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
411
     *
412
     * ```php
413
     * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
414
     * ```
415
     *
416
     * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug`
417
     * level output is used:
418
     *
419
     * ```php
420
     * $mail->Debugoutput = new myPsr3Logger;
421
     * ```
422
     *
423
     * @see SMTP::$Debugoutput
424
     *
425
     * @var string|callable|\Psr\Log\LoggerInterface
426
     */
427
    public $Debugoutput = 'echo';
428
429
    /**
430
     * Whether to keep SMTP connection open after each message.
431
     * If this is set to true then to close the connection
432
     * requires an explicit call to smtpClose().
433
     *
434
     * @var bool
435
     */
436
    public $SMTPKeepAlive = false;
437
438
    /**
439
     * Whether to split multiple to addresses into multiple messages
440
     * or send them all in one message.
441
     * Only supported in `mail` and `sendmail` transports, not in SMTP.
442
     *
443
     * @var bool
444
     */
445
    public $SingleTo = false;
446
447
    /**
448
     * Storage for addresses when SingleTo is enabled.
449
     *
450
     * @var array
451
     */
452
    protected $SingleToArray = [];
453
454
    /**
455
     * Whether to generate VERP addresses on send.
456
     * Only applicable when sending via SMTP.
457
     *
458
     * @see https://en.wikipedia.org/wiki/Variable_envelope_return_path
459
     * @see http://www.postfix.org/VERP_README.html Postfix VERP info
460
     *
461
     * @var bool
462
     */
463
    public $do_verp = false;
464
465
    /**
466
     * Whether to allow sending messages with an empty body.
467
     *
468
     * @var bool
469
     */
470
    public $AllowEmpty = false;
471
472
    /**
473
     * DKIM selector.
474
     *
475
     * @var string
476
     */
477
    public $DKIM_selector = '';
478
479
    /**
480
     * DKIM Identity.
481
     * Usually the email address used as the source of the email.
482
     *
483
     * @var string
484
     */
485
    public $DKIM_identity = '';
486
487
    /**
488
     * DKIM passphrase.
489
     * Used if your key is encrypted.
490
     *
491
     * @var string
492
     */
493
    public $DKIM_passphrase = '';
494
495
    /**
496
     * DKIM signing domain name.
497
     *
498
     * @example 'example.com'
499
     *
500
     * @var string
501
     */
502
    public $DKIM_domain = '';
503
504
    /**
505
     * DKIM Copy header field values for diagnostic use.
506
     *
507
     * @var bool
508
     */
509
    public $DKIM_copyHeaderFields = true;
510
511
    /**
512
     * DKIM Extra signing headers.
513
     *
514
     * @example ['List-Unsubscribe', 'List-Help']
515
     *
516
     * @var array
517
     */
518
    public $DKIM_extraHeaders = [];
519
520
    /**
521
     * DKIM private key file path.
522
     *
523
     * @var string
524
     */
525
    public $DKIM_private = '';
526
527
    /**
528
     * DKIM private key string.
529
     *
530
     * If set, takes precedence over `$DKIM_private`.
531
     *
532
     * @var string
533
     */
534
    public $DKIM_private_string = '';
535
536
    /**
537
     * Callback Action function name.
538
     *
539
     * The function that handles the result of the send email action.
540
     * It is called out by send() for each email sent.
541
     *
542
     * Value can be any php callable: http://www.php.net/is_callable
543
     *
544
     * Parameters:
545
     *   bool $result        result of the send action
546
     *   array   $to            email addresses of the recipients
547
     *   array   $cc            cc email addresses
548
     *   array   $bcc           bcc email addresses
549
     *   string  $subject       the subject
550
     *   string  $body          the email body
551
     *   string  $from          email address of sender
552
     *   string  $extra         extra information of possible use
553
     *                          "smtp_transaction_id' => last smtp transaction id
554
     *
555
     * @var string
556
     */
557
    public $action_function = '';
558
559
    /**
560
     * What to put in the X-Mailer header.
561
     * Options: An empty string for PHPMailer default, whitespace/null for none, or a string to use.
562
     *
563
     * @var string|null
564
     */
565
    public $XMailer = '';
566
567
    /**
568
     * Which validator to use by default when validating email addresses.
569
     * May be a callable to inject your own validator, but there are several built-in validators.
570
     * The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option.
571
     *
572
     * @see PHPMailer::validateAddress()
573
     *
574
     * @var string|callable
575
     */
576
    public static $validator = 'php';
577
578
    /**
579
     * An instance of the SMTP sender class.
580
     *
581
     * @var SMTP
582
     */
583
    protected $smtp;
584
585
    /**
586
     * The array of 'to' names and addresses.
587
     *
588
     * @var array
589
     */
590
    protected $to = [];
591
592
    /**
593
     * The array of 'cc' names and addresses.
594
     *
595
     * @var array
596
     */
597
    protected $cc = [];
598
599
    /**
600
     * The array of 'bcc' names and addresses.
601
     *
602
     * @var array
603
     */
604
    protected $bcc = [];
605
606
    /**
607
     * The array of reply-to names and addresses.
608
     *
609
     * @var array
610
     */
611
    protected $ReplyTo = [];
612
613
    /**
614
     * An array of all kinds of addresses.
615
     * Includes all of $to, $cc, $bcc.
616
     *
617
     * @see PHPMailer::$to
618
     * @see PHPMailer::$cc
619
     * @see PHPMailer::$bcc
620
     *
621
     * @var array
622
     */
623
    protected $all_recipients = [];
624
625
    /**
626
     * An array of names and addresses queued for validation.
627
     * In send(), valid and non duplicate entries are moved to $all_recipients
628
     * and one of $to, $cc, or $bcc.
629
     * This array is used only for addresses with IDN.
630
     *
631
     * @see PHPMailer::$to
632
     * @see PHPMailer::$cc
633
     * @see PHPMailer::$bcc
634
     * @see PHPMailer::$all_recipients
635
     *
636
     * @var array
637
     */
638
    protected $RecipientsQueue = [];
639
640
    /**
641
     * An array of reply-to names and addresses queued for validation.
642
     * In send(), valid and non duplicate entries are moved to $ReplyTo.
643
     * This array is used only for addresses with IDN.
644
     *
645
     * @see PHPMailer::$ReplyTo
646
     *
647
     * @var array
648
     */
649
    protected $ReplyToQueue = [];
650
651
    /**
652
     * The array of attachments.
653
     *
654
     * @var array
655
     */
656
    protected $attachment = [];
657
658
    /**
659
     * The array of custom headers.
660
     *
661
     * @var array
662
     */
663
    protected $CustomHeader = [];
664
665
    /**
666
     * The most recent Message-ID (including angular brackets).
667
     *
668
     * @var string
669
     */
670
    protected $lastMessageID = '';
671
672
    /**
673
     * The message's MIME type.
674
     *
675
     * @var string
676
     */
677
    protected $message_type = '';
678
679
    /**
680
     * The array of MIME boundary strings.
681
     *
682
     * @var array
683
     */
684
    protected $boundary = [];
685
686
    /**
687
     * The array of available languages.
688
     *
689
     * @var array
690
     */
691
    protected $language = [];
692
693
    /**
694
     * The number of errors encountered.
695
     *
696
     * @var int
697
     */
698
    protected $error_count = 0;
699
700
    /**
701
     * The S/MIME certificate file path.
702
     *
703
     * @var string
704
     */
705
    protected $sign_cert_file = '';
706
707
    /**
708
     * The S/MIME key file path.
709
     *
710
     * @var string
711
     */
712
    protected $sign_key_file = '';
713
714
    /**
715
     * The optional S/MIME extra certificates ("CA Chain") file path.
716
     *
717
     * @var string
718
     */
719
    protected $sign_extracerts_file = '';
720
721
    /**
722
     * The S/MIME password for the key.
723
     * Used only if the key is encrypted.
724
     *
725
     * @var string
726
     */
727
    protected $sign_key_pass = '';
728
729
    /**
730
     * Whether to throw exceptions for errors.
731
     *
732
     * @var bool
733
     */
734
    protected $exceptions = false;
735
736
    /**
737
     * Unique ID used for message ID and boundaries.
738
     *
739
     * @var string
740
     */
741
    protected $uniqueid = '';
742
743
    /**
744
     * The PHPMailer Version number.
745
     *
746
     * @var string
747
     */
748
    const VERSION = '6.1.4';
749
750
    /**
751
     * Error severity: message only, continue processing.
752
     *
753
     * @var int
754
     */
755
    const STOP_MESSAGE = 0;
756
757
    /**
758
     * Error severity: message, likely ok to continue processing.
759
     *
760
     * @var int
761
     */
762
    const STOP_CONTINUE = 1;
763
764
    /**
765
     * Error severity: message, plus full stop, critical error reached.
766
     *
767
     * @var int
768
     */
769
    const STOP_CRITICAL = 2;
770
771
    /**
772
     * The SMTP standard CRLF line break.
773
     * If you want to change line break format, change static::$LE, not this.
774
     */
775
    const CRLF = "\r\n";
776
777
    /**
778
     * "Folding White Space" a white space string used for line folding.
779
     */
780
    const FWS = ' ';
781
782
    /**
783
     * SMTP RFC standard line ending; Carriage Return, Line Feed.
784
     *
785
     * @var string
786
     */
787
    protected static $LE = self::CRLF;
788
789
    /**
790
     * The maximum line length supported by mail().
791
     *
792
     * Background: mail() will sometimes corrupt messages
793
     * with headers headers longer than 65 chars, see #818.
794
     *
795
     * @var int
796
     */
797
    const MAIL_MAX_LINE_LENGTH = 63;
798
799
    /**
800
     * The maximum line length allowed by RFC 2822 section 2.1.1.
801
     *
802
     * @var int
803
     */
804
    const MAX_LINE_LENGTH = 998;
805
806
    /**
807
     * The lower maximum line length allowed by RFC 2822 section 2.1.1.
808
     * This length does NOT include the line break
809
     * 76 means that lines will be 77 or 78 chars depending on whether
810
     * the line break format is LF or CRLF; both are valid.
811
     *
812
     * @var int
813
     */
814
    const STD_LINE_LENGTH = 76;
815
816
    /**
817
     * Constructor.
818
     *
819
     * @param bool $exceptions Should we throw external exceptions?
820
     */
821
    public function __construct($exceptions = null)
822
    {
823
        if (null !== $exceptions) {
824
            $this->exceptions = (bool) $exceptions;
825
        }
826
        //Pick an appropriate debug output format automatically
827
        $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html');
828
    }
829
830
    /**
831
     * Destructor.
832
     */
833
    public function __destruct()
834
    {
835
        //Close any open SMTP connection nicely
836
        $this->smtpClose();
837
    }
838
839
    /**
840
     * Call mail() in a safe_mode-aware fashion.
841
     * Also, unless sendmail_path points to sendmail (or something that
842
     * claims to be sendmail), don't pass params (not a perfect fix,
843
     * but it will do).
844
     *
845
     * @param string      $to      To
846
     * @param string      $subject Subject
847
     * @param string      $body    Message Body
848
     * @param string      $header  Additional Header(s)
849
     * @param string|null $params  Params
850
     *
851
     * @return bool
852
     */
853
    private function mailPassthru($to, $subject, $body, $header, $params)
854
    {
855
        //Check overloading of mail function to avoid double-encoding
856
        if (ini_get('mbstring.func_overload') & 1) {
857
            $subject = $this->secureHeader($subject);
858
        } else {
859
            $subject = $this->encodeHeader($this->secureHeader($subject));
860
        }
861
        //Calling mail() with null params breaks
862
        if (!$this->UseSendmailOptions || null === $params) {
863
            $result = @mail($to, $subject, $body, $header);
864
        } else {
865
            $result = @mail($to, $subject, $body, $header, $params);
866
        }
867
868
        return $result;
869
    }
870
871
    /**
872
     * Output debugging info via user-defined method.
873
     * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
874
     *
875
     * @see PHPMailer::$Debugoutput
876
     * @see PHPMailer::$SMTPDebug
877
     *
878
     * @param string $str
879
     */
880
    protected function edebug($str)
881
    {
882
        if ($this->SMTPDebug <= 0) {
883
            return;
884
        }
885
        //Is this a PSR-3 logger?
886
        if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) {
887
            $this->Debugoutput->debug($str);
888
889
            return;
890
        }
891
        //Avoid clash with built-in function names
892
        if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) {
893
            call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
894
895
            return;
896
        }
897
        switch ($this->Debugoutput) {
898
            case 'error_log':
899
                //Don't output, just log
900
                error_log($str);
901
                break;
902
            case 'html':
903
                //Cleans up output a bit for a better looking, HTML-safe output
904
                echo htmlentities(
905
                    preg_replace('/[\r\n]+/', '', $str),
906
                    ENT_QUOTES,
907
                    'UTF-8'
908
                ), "<br>\n";
909
                break;
910
            case 'echo':
911
            default:
912
                //Normalize line breaks
913
                $str = preg_replace('/\r\n|\r/m', "\n", $str);
914
                echo gmdate('Y-m-d H:i:s'),
915
                "\t",
916
                    //Trim trailing space
917
                trim(
918
                    //Indent for readability, except for trailing break
919
                    str_replace(
920
                        "\n",
921
                        "\n                   \t                  ",
922
                        trim($str)
923
                    )
924
                ),
925
                "\n";
926
        }
927
    }
928
929
    /**
930
     * Sets message type to HTML or plain.
931
     *
932
     * @param bool $isHtml True for HTML mode
933
     */
934
    public function isHTML($isHtml = true)
935
    {
936
        if ($isHtml) {
937
            $this->ContentType = static::CONTENT_TYPE_TEXT_HTML;
938
        } else {
939
            $this->ContentType = static::CONTENT_TYPE_PLAINTEXT;
940
        }
941
    }
942
943
    /**
944
     * Send messages using SMTP.
945
     */
946
    public function isSMTP()
947
    {
948
        $this->Mailer = 'smtp';
949
    }
950
951
    /**
952
     * Send messages using PHP's mail() function.
953
     */
954
    public function isMail()
955
    {
956
        $this->Mailer = 'mail';
957
    }
958
959
    /**
960
     * Send messages using $Sendmail.
961
     */
962
    public function isSendmail()
963
    {
964
        $ini_sendmail_path = ini_get('sendmail_path');
965
966
        if (false === stripos($ini_sendmail_path, 'sendmail')) {
967
            $this->Sendmail = '/usr/sbin/sendmail';
968
        } else {
969
            $this->Sendmail = $ini_sendmail_path;
970
        }
971
        $this->Mailer = 'sendmail';
972
    }
973
974
    /**
975
     * Send messages using qmail.
976
     */
977
    public function isQmail()
978
    {
979
        $ini_sendmail_path = ini_get('sendmail_path');
980
981
        if (false === stripos($ini_sendmail_path, 'qmail')) {
982
            $this->Sendmail = '/var/qmail/bin/qmail-inject';
983
        } else {
984
            $this->Sendmail = $ini_sendmail_path;
985
        }
986
        $this->Mailer = 'qmail';
987
    }
988
989
    /**
990
     * Add a "To" address.
991
     *
992
     * @param string $address The email address to send to
993
     * @param string $name
994
     *
995
     * @throws Exception
996
     *
997
     * @return bool true on success, false if address already used or invalid in some way
998
     */
999
    public function addAddress($address, $name = '')
1000
    {
1001
        return $this->addOrEnqueueAnAddress('to', $address, $name);
1002
    }
1003
1004
    /**
1005
     * Add a "CC" address.
1006
     *
1007
     * @param string $address The email address to send to
1008
     * @param string $name
1009
     *
1010
     * @throws Exception
1011
     *
1012
     * @return bool true on success, false if address already used or invalid in some way
1013
     */
1014
    public function addCC($address, $name = '')
1015
    {
1016
        return $this->addOrEnqueueAnAddress('cc', $address, $name);
1017
    }
1018
1019
    /**
1020
     * Add a "BCC" address.
1021
     *
1022
     * @param string $address The email address to send to
1023
     * @param string $name
1024
     *
1025
     * @throws Exception
1026
     *
1027
     * @return bool true on success, false if address already used or invalid in some way
1028
     */
1029
    public function addBCC($address, $name = '')
1030
    {
1031
        return $this->addOrEnqueueAnAddress('bcc', $address, $name);
1032
    }
1033
1034
    /**
1035
     * Add a "Reply-To" address.
1036
     *
1037
     * @param string $address The email address to reply to
1038
     * @param string $name
1039
     *
1040
     * @throws Exception
1041
     *
1042
     * @return bool true on success, false if address already used or invalid in some way
1043
     */
1044
    public function addReplyTo($address, $name = '')
1045
    {
1046
        return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);
1047
    }
1048
1049
    /**
1050
     * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer
1051
     * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still
1052
     * be modified after calling this function), addition of such addresses is delayed until send().
1053
     * Addresses that have been added already return false, but do not throw exceptions.
1054
     *
1055
     * @param string $kind    One of 'to', 'cc', 'bcc', or 'ReplyTo'
1056
     * @param string $address The email address to send, resp. to reply to
1057
     * @param string $name
1058
     *
1059
     * @throws Exception
1060
     *
1061
     * @return bool true on success, false if address already used or invalid in some way
1062
     */
1063
    protected function addOrEnqueueAnAddress($kind, $address, $name)
1064
    {
1065
        $address = trim($address);
1066
        $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
1067
        $pos = strrpos($address, '@');
1068
        if (false === $pos) {
1069
            // At-sign is missing.
1070
            $error_message = sprintf(
1071
                '%s (%s): %s',
1072
                $this->lang('invalid_address'),
1073
                $kind,
1074
                $address
1075
            );
1076
            $this->setError($error_message);
1077
            $this->edebug($error_message);
1078
            if ($this->exceptions) {
1079
                throw new Exception($error_message);
1080
            }
1081
1082
            return false;
1083
        }
1084
        $params = [$kind, $address, $name];
1085
        // Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
1086
        if (static::idnSupported() && $this->has8bitChars(substr($address, ++$pos))) {
1087
            if ('Reply-To' !== $kind) {
1088
                if (!array_key_exists($address, $this->RecipientsQueue)) {
1089
                    $this->RecipientsQueue[$address] = $params;
1090
1091
                    return true;
1092
                }
1093
            } elseif (!array_key_exists($address, $this->ReplyToQueue)) {
1094
                $this->ReplyToQueue[$address] = $params;
1095
1096
                return true;
1097
            }
1098
1099
            return false;
1100
        }
1101
1102
        // Immediately add standard addresses without IDN.
1103
        return call_user_func_array([$this, 'addAnAddress'], $params);
1104
    }
1105
1106
    /**
1107
     * Add an address to one of the recipient arrays or to the ReplyTo array.
1108
     * Addresses that have been added already return false, but do not throw exceptions.
1109
     *
1110
     * @param string $kind    One of 'to', 'cc', 'bcc', or 'ReplyTo'
1111
     * @param string $address The email address to send, resp. to reply to
1112
     * @param string $name
1113
     *
1114
     * @throws Exception
1115
     *
1116
     * @return bool true on success, false if address already used or invalid in some way
1117
     */
1118
    protected function addAnAddress($kind, $address, $name = '')
1119
    {
1120
        if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) {
1121
            $error_message = sprintf(
1122
                '%s: %s',
1123
                $this->lang('Invalid recipient kind'),
1124
                $kind
1125
            );
1126
            $this->setError($error_message);
1127
            $this->edebug($error_message);
1128
            if ($this->exceptions) {
1129
                throw new Exception($error_message);
1130
            }
1131
1132
            return false;
1133
        }
1134
        if (!static::validateAddress($address)) {
1135
            $error_message = sprintf(
1136
                '%s (%s): %s',
1137
                $this->lang('invalid_address'),
1138
                $kind,
1139
                $address
1140
            );
1141
            $this->setError($error_message);
1142
            $this->edebug($error_message);
1143
            if ($this->exceptions) {
1144
                throw new Exception($error_message);
1145
            }
1146
1147
            return false;
1148
        }
1149
        if ('Reply-To' !== $kind) {
1150
            if (!array_key_exists(strtolower($address), $this->all_recipients)) {
1151
                $this->{$kind}[] = [$address, $name];
1152
                $this->all_recipients[strtolower($address)] = true;
1153
1154
                return true;
1155
            }
1156
        } elseif (!array_key_exists(strtolower($address), $this->ReplyTo)) {
1157
            $this->ReplyTo[strtolower($address)] = [$address, $name];
1158
1159
            return true;
1160
        }
1161
1162
        return false;
1163
    }
1164
1165
    /**
1166
     * Parse and validate a string containing one or more RFC822-style comma-separated email addresses
1167
     * of the form "display name <address>" into an array of name/address pairs.
1168
     * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
1169
     * Note that quotes in the name part are removed.
1170
     *
1171
     * @see http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
1172
     *
1173
     * @param string $addrstr The address list string
1174
     * @param bool   $useimap Whether to use the IMAP extension to parse the list
1175
     *
1176
     * @return array
1177
     */
1178
    public static function parseAddresses($addrstr, $useimap = true)
1179
    {
1180
        $addresses = [];
1181
        if ($useimap && function_exists('imap_rfc822_parse_adrlist')) {
1182
            //Use this built-in parser if it's available
1183
            $list = imap_rfc822_parse_adrlist($addrstr, '');
1184
            foreach ($list as $address) {
1185
                if (('.SYNTAX-ERROR.' !== $address->host) && static::validateAddress(
1186
                    $address->mailbox . '@' . $address->host
1187
                )) {
1188
                    $addresses[] = [
1189
                        'name' => (property_exists($address, 'personal') ? $address->personal : ''),
1190
                        'address' => $address->mailbox . '@' . $address->host,
1191
                    ];
1192
                }
1193
            }
1194
        } else {
1195
            //Use this simpler parser
1196
            $list = explode(',', $addrstr);
1197
            foreach ($list as $address) {
1198
                $address = trim($address);
1199
                //Is there a separate name part?
1200
                if (strpos($address, '<') === false) {
1201
                    //No separate name, just use the whole thing
1202
                    if (static::validateAddress($address)) {
1203
                        $addresses[] = [
1204
                            'name' => '',
1205
                            'address' => $address,
1206
                        ];
1207
                    }
1208
                } else {
1209
                    list($name, $email) = explode('<', $address);
1210
                    $email = trim(str_replace('>', '', $email));
1211
                    if (static::validateAddress($email)) {
1212
                        $addresses[] = [
1213
                            'name' => trim(str_replace(['"', "'"], '', $name)),
1214
                            'address' => $email,
1215
                        ];
1216
                    }
1217
                }
1218
            }
1219
        }
1220
1221
        return $addresses;
1222
    }
1223
1224
    /**
1225
     * Set the From and FromName properties.
1226
     *
1227
     * @param string $address
1228
     * @param string $name
1229
     * @param bool   $auto    Whether to also set the Sender address, defaults to true
1230
     *
1231
     * @throws Exception
1232
     *
1233
     * @return bool
1234
     */
1235
    public function setFrom($address, $name = '', $auto = true)
1236
    {
1237
        $address = trim($address);
1238
        $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
1239
        // Don't validate now addresses with IDN. Will be done in send().
1240
        $pos = strrpos($address, '@');
1241
        if ((false === $pos)
1242
            || ((!$this->has8bitChars(substr($address, ++$pos)) || !static::idnSupported())
1243
            && !static::validateAddress($address))
1244
        ) {
1245
            $error_message = sprintf(
1246
                '%s (From): %s',
1247
                $this->lang('invalid_address'),
1248
                $address
1249
            );
1250
            $this->setError($error_message);
1251
            $this->edebug($error_message);
1252
            if ($this->exceptions) {
1253
                throw new Exception($error_message);
1254
            }
1255
1256
            return false;
1257
        }
1258
        $this->From = $address;
1259
        $this->FromName = $name;
1260
        if ($auto && empty($this->Sender)) {
1261
            $this->Sender = $address;
1262
        }
1263
1264
        return true;
1265
    }
1266
1267
    /**
1268
     * Return the Message-ID header of the last email.
1269
     * Technically this is the value from the last time the headers were created,
1270
     * but it's also the message ID of the last sent message except in
1271
     * pathological cases.
1272
     *
1273
     * @return string
1274
     */
1275
    public function getLastMessageID()
1276
    {
1277
        return $this->lastMessageID;
1278
    }
1279
1280
    /**
1281
     * Check that a string looks like an email address.
1282
     * Validation patterns supported:
1283
     * * `auto` Pick best pattern automatically;
1284
     * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0;
1285
     * * `pcre` Use old PCRE implementation;
1286
     * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;
1287
     * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
1288
     * * `noregex` Don't use a regex: super fast, really dumb.
1289
     * Alternatively you may pass in a callable to inject your own validator, for example:
1290
     *
1291
     * ```php
1292
     * PHPMailer::validateAddress('[email protected]', function($address) {
1293
     *     return (strpos($address, '@') !== false);
1294
     * });
1295
     * ```
1296
     *
1297
     * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator.
1298
     *
1299
     * @param string          $address       The email address to check
1300
     * @param string|callable $patternselect Which pattern to use
1301
     *
1302
     * @return bool
1303
     */
1304
    public static function validateAddress($address, $patternselect = null)
1305
    {
1306
        if (null === $patternselect) {
1307
            $patternselect = static::$validator;
1308
        }
1309
        if (is_callable($patternselect)) {
1310
            return $patternselect($address);
1311
        }
1312
        //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
1313
        if (strpos($address, "\n") !== false || strpos($address, "\r") !== false) {
1314
            return false;
1315
        }
1316
        switch ($patternselect) {
1317
            case 'pcre': //Kept for BC
1318
            case 'pcre8':
1319
                /*
1320
                 * A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL
1321
                 * is based.
1322
                 * In addition to the addresses allowed by filter_var, also permits:
1323
                 *  * dotless domains: `a@b`
1324
                 *  * comments: `1234 @ local(blah) .machine .example`
1325
                 *  * quoted elements: `'"test blah"@example.org'`
1326
                 *  * numeric TLDs: `[email protected]`
1327
                 *  * unbracketed IPv4 literals: `[email protected]`
1328
                 *  * IPv6 literals: 'first.last@[IPv6:a1::]'
1329
                 * Not all of these will necessarily work for sending!
1330
                 *
1331
                 * @see       http://squiloople.com/2009/12/20/email-address-validation/
1332
                 * @copyright 2009-2010 Michael Rushton
1333
                 * Feel free to use and redistribute this code. But please keep this copyright notice.
1334
                 */
1335
                return (bool) preg_match(
1336
                    '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
1337
                    '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
1338
                    '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
1339
                    '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
1340
                    '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
1341
                    '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
1342
                    '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
1343
                    '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
1344
                    '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
1345
                    $address
1346
                );
1347
            case 'html5':
1348
                /*
1349
                 * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
1350
                 *
1351
                 * @see http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
1352
                 */
1353
                return (bool) preg_match(
1354
                    '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
1355
                    '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
1356
                    $address
1357
                );
1358
            case 'php':
1359
            default:
1360
                return filter_var($address, FILTER_VALIDATE_EMAIL) !== false;
1361
        }
1362
    }
1363
1364
    /**
1365
     * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the
1366
     * `intl` and `mbstring` PHP extensions.
1367
     *
1368
     * @return bool `true` if required functions for IDN support are present
1369
     */
1370
    public static function idnSupported()
1371
    {
1372
        return function_exists('idn_to_ascii') && function_exists('mb_convert_encoding');
1373
    }
1374
1375
    /**
1376
     * Converts IDN in given email address to its ASCII form, also known as punycode, if possible.
1377
     * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet.
1378
     * This function silently returns unmodified address if:
1379
     * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
1380
     * - Conversion to punycode is impossible (e.g. required PHP functions are not available)
1381
     *   or fails for any reason (e.g. domain contains characters not allowed in an IDN).
1382
     *
1383
     * @see PHPMailer::$CharSet
1384
     *
1385
     * @param string $address The email address to convert
1386
     *
1387
     * @return string The encoded address in ASCII form
1388
     */
1389
    public function punyencodeAddress($address)
1390
    {
1391
        // Verify we have required functions, CharSet, and at-sign.
1392
        $pos = strrpos($address, '@');
1393
        if (!empty($this->CharSet) &&
1394
            false !== $pos &&
1395
            static::idnSupported()
1396
        ) {
1397
            $domain = substr($address, ++$pos);
1398
            // Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
1399
            if ($this->has8bitChars($domain) && @mb_check_encoding($domain, $this->CharSet)) {
1400
                $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet);
1401
                //Ignore IDE complaints about this line - method signature changed in PHP 5.4
1402
                $errorcode = 0;
1403
                if (defined('INTL_IDNA_VARIANT_UTS46')) {
1404
                    $punycode = idn_to_ascii($domain, $errorcode, INTL_IDNA_VARIANT_UTS46);
1405
                } elseif (defined('INTL_IDNA_VARIANT_2003')) {
1406
                    $punycode = idn_to_ascii($domain, $errorcode, INTL_IDNA_VARIANT_2003);
1407
                } else {
1408
                    $punycode = idn_to_ascii($domain, $errorcode);
1409
                }
1410
                if (false !== $punycode) {
1411
                    return substr($address, 0, $pos) . $punycode;
1412
                }
1413
            }
1414
        }
1415
1416
        return $address;
1417
    }
1418
1419
    /**
1420
     * Create a message and send it.
1421
     * Uses the sending method specified by $Mailer.
1422
     *
1423
     * @throws Exception
1424
     *
1425
     * @return bool false on error - See the ErrorInfo property for details of the error
1426
     */
1427
    public function send()
1428
    {
1429
        try {
1430
            if (!$this->preSend()) {
1431
                return false;
1432
            }
1433
1434
            return $this->postSend();
1435
        } catch (Exception $exc) {
1436
            $this->mailHeader = '';
1437
            $this->setError($exc->getMessage());
1438
            if ($this->exceptions) {
1439
                throw $exc;
1440
            }
1441
1442
            return false;
1443
        }
1444
    }
1445
1446
    /**
1447
     * Prepare a message for sending.
1448
     *
1449
     * @throws Exception
1450
     *
1451
     * @return bool
1452
     */
1453
    public function preSend()
1454
    {
1455
        if ('smtp' === $this->Mailer
1456
            || ('mail' === $this->Mailer && stripos(PHP_OS, 'WIN') === 0)
1457
        ) {
1458
            //SMTP mandates RFC-compliant line endings
1459
            //and it's also used with mail() on Windows
1460
            static::setLE(self::CRLF);
1461
        } else {
1462
            //Maintain backward compatibility with legacy Linux command line mailers
1463
            static::setLE(PHP_EOL);
1464
        }
1465
        //Check for buggy PHP versions that add a header with an incorrect line break
1466
        if ('mail' === $this->Mailer
1467
            && ((PHP_VERSION_ID >= 70000 && PHP_VERSION_ID < 70017)
1468
                || (PHP_VERSION_ID >= 70100 && PHP_VERSION_ID < 70103))
1469
            && ini_get('mail.add_x_header') === '1'
1470
            && stripos(PHP_OS, 'WIN') === 0
1471
        ) {
1472
            trigger_error(
1473
                'Your version of PHP is affected by a bug that may result in corrupted messages.' .
1474
                ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' .
1475
                ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.',
1476
                E_USER_WARNING
1477
            );
1478
        }
1479
1480
        try {
1481
            $this->error_count = 0; // Reset errors
1482
            $this->mailHeader = '';
1483
1484
            // Dequeue recipient and Reply-To addresses with IDN
1485
            foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
1486
                $params[1] = $this->punyencodeAddress($params[1]);
1487
                call_user_func_array([$this, 'addAnAddress'], $params);
1488
            }
1489
            if (count($this->to) + count($this->cc) + count($this->bcc) < 1) {
1490
                throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL);
1491
            }
1492
1493
            // Validate From, Sender, and ConfirmReadingTo addresses
1494
            foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) {
1495
                $this->$address_kind = trim($this->$address_kind);
1496
                if (empty($this->$address_kind)) {
1497
                    continue;
1498
                }
1499
                $this->$address_kind = $this->punyencodeAddress($this->$address_kind);
1500
                if (!static::validateAddress($this->$address_kind)) {
1501
                    $error_message = sprintf(
1502
                        '%s (%s): %s',
1503
                        $this->lang('invalid_address'),
1504
                        $address_kind,
1505
                        $this->$address_kind
1506
                    );
1507
                    $this->setError($error_message);
1508
                    $this->edebug($error_message);
1509
                    if ($this->exceptions) {
1510
                        throw new Exception($error_message);
1511
                    }
1512
1513
                    return false;
1514
                }
1515
            }
1516
1517
            // Set whether the message is multipart/alternative
1518
            if ($this->alternativeExists()) {
1519
                $this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE;
1520
            }
1521
1522
            $this->setMessageType();
1523
            // Refuse to send an empty message unless we are specifically allowing it
1524
            if (!$this->AllowEmpty && empty($this->Body)) {
1525
                throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
1526
            }
1527
1528
            //Trim subject consistently
1529
            $this->Subject = trim($this->Subject);
1530
            // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
1531
            $this->MIMEHeader = '';
1532
            $this->MIMEBody = $this->createBody();
1533
            // createBody may have added some headers, so retain them
1534
            $tempheaders = $this->MIMEHeader;
1535
            $this->MIMEHeader = $this->createHeader();
1536
            $this->MIMEHeader .= $tempheaders;
1537
1538
            // To capture the complete message when using mail(), create
1539
            // an extra header list which createHeader() doesn't fold in
1540
            if ('mail' === $this->Mailer) {
1541
                if (count($this->to) > 0) {
1542
                    $this->mailHeader .= $this->addrAppend('To', $this->to);
1543
                } else {
1544
                    $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
1545
                }
1546
                $this->mailHeader .= $this->headerLine(
1547
                    'Subject',
1548
                    $this->encodeHeader($this->secureHeader($this->Subject))
1549
                );
1550
            }
1551
1552
            // Sign with DKIM if enabled
1553
            if (!empty($this->DKIM_domain)
1554
                && !empty($this->DKIM_selector)
1555
                && (!empty($this->DKIM_private_string)
1556
                    || (!empty($this->DKIM_private)
1557
                        && static::isPermittedPath($this->DKIM_private)
1558
                        && file_exists($this->DKIM_private)
1559
                    )
1560
                )
1561
            ) {
1562
                $header_dkim = $this->DKIM_Add(
1563
                    $this->MIMEHeader . $this->mailHeader,
1564
                    $this->encodeHeader($this->secureHeader($this->Subject)),
1565
                    $this->MIMEBody
1566
                );
1567
                $this->MIMEHeader = static::stripTrailingWSP($this->MIMEHeader) . static::$LE .
1568
                    static::normalizeBreaks($header_dkim) . static::$LE;
1569
            }
1570
1571
            return true;
1572
        } catch (Exception $exc) {
1573
            $this->setError($exc->getMessage());
1574
            if ($this->exceptions) {
1575
                throw $exc;
1576
            }
1577
1578
            return false;
1579
        }
1580
    }
1581
1582
    /**
1583
     * Actually send a message via the selected mechanism.
1584
     *
1585
     * @throws Exception
1586
     *
1587
     * @return bool
1588
     */
1589
    public function postSend()
1590
    {
1591
        try {
1592
            // Choose the mailer and send through it
1593
            switch ($this->Mailer) {
1594
                case 'sendmail':
1595
                case 'qmail':
1596
                    return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
1597
                case 'smtp':
1598
                    return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
1599
                case 'mail':
1600
                    return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1601
                default:
1602
                    $sendMethod = $this->Mailer . 'Send';
1603
                    if (method_exists($this, $sendMethod)) {
1604
                        return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
1605
                    }
1606
1607
                    return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1608
            }
1609
        } catch (Exception $exc) {
1610
            $this->setError($exc->getMessage());
1611
            $this->edebug($exc->getMessage());
1612
            if ($this->exceptions) {
1613
                throw $exc;
1614
            }
1615
        }
1616
1617
        return false;
1618
    }
1619
1620
    /**
1621
     * Send mail using the $Sendmail program.
1622
     *
1623
     * @see PHPMailer::$Sendmail
1624
     *
1625
     * @param string $header The message headers
1626
     * @param string $body   The message body
1627
     *
1628
     * @throws Exception
1629
     *
1630
     * @return bool
1631
     */
1632
    protected function sendmailSend($header, $body)
1633
    {
1634
        $header = static::stripTrailingWSP($header) . static::$LE . static::$LE;
1635
1636
        // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1637
        if (!empty($this->Sender) && self::isShellSafe($this->Sender)) {
1638
            if ('qmail' === $this->Mailer) {
1639
                $sendmailFmt = '%s -f%s';
1640
            } else {
1641
                $sendmailFmt = '%s -oi -f%s -t';
1642
            }
1643
        } elseif ('qmail' === $this->Mailer) {
1644
            $sendmailFmt = '%s';
1645
        } else {
1646
            $sendmailFmt = '%s -oi -t';
1647
        }
1648
1649
        $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);
1650
1651
        if ($this->SingleTo) {
1652
            foreach ($this->SingleToArray as $toAddr) {
1653
                $mail = @popen($sendmail, 'w');
1654
                if (!$mail) {
1655
                    throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1656
                }
1657
                fwrite($mail, 'To: ' . $toAddr . "\n");
1658
                fwrite($mail, $header);
1659
                fwrite($mail, $body);
1660
                $result = pclose($mail);
1661
                $this->doCallback(
1662
                    ($result === 0),
1663
                    [$toAddr],
1664
                    $this->cc,
1665
                    $this->bcc,
1666
                    $this->Subject,
1667
                    $body,
1668
                    $this->From,
1669
                    []
1670
                );
1671
                if (0 !== $result) {
1672
                    throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1673
                }
1674
            }
1675
        } else {
1676
            $mail = @popen($sendmail, 'w');
1677
            if (!$mail) {
1678
                throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1679
            }
1680
            fwrite($mail, $header);
1681
            fwrite($mail, $body);
1682
            $result = pclose($mail);
1683
            $this->doCallback(
1684
                ($result === 0),
1685
                $this->to,
1686
                $this->cc,
1687
                $this->bcc,
1688
                $this->Subject,
1689
                $body,
1690
                $this->From,
1691
                []
1692
            );
1693
            if (0 !== $result) {
1694
                throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1695
            }
1696
        }
1697
1698
        return true;
1699
    }
1700
1701
    /**
1702
     * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters.
1703
     * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows.
1704
     *
1705
     * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report
1706
     *
1707
     * @param string $string The string to be validated
1708
     *
1709
     * @return bool
1710
     */
1711
    protected static function isShellSafe($string)
1712
    {
1713
        // Future-proof
1714
        if (escapeshellcmd($string) !== $string
1715
            || !in_array(escapeshellarg($string), ["'$string'", "\"$string\""])
1716
        ) {
1717
            return false;
1718
        }
1719
1720
        $length = strlen($string);
1721
1722
        for ($i = 0; $i < $length; ++$i) {
1723
            $c = $string[$i];
1724
1725
            // All other characters have a special meaning in at least one common shell, including = and +.
1726
            // Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
1727
            // Note that this does permit non-Latin alphanumeric characters based on the current locale.
1728
            if (!ctype_alnum($c) && strpos('@_-.', $c) === false) {
1729
                return false;
1730
            }
1731
        }
1732
1733
        return true;
1734
    }
1735
1736
    /**
1737
     * Check whether a file path is of a permitted type.
1738
     * Used to reject URLs and phar files from functions that access local file paths,
1739
     * such as addAttachment.
1740
     *
1741
     * @param string $path A relative or absolute path to a file
1742
     *
1743
     * @return bool
1744
     */
1745
    protected static function isPermittedPath($path)
1746
    {
1747
        return !preg_match('#^[a-z]+://#i', $path);
1748
    }
1749
1750
    /**
1751
     * Send mail using the PHP mail() function.
1752
     *
1753
     * @see http://www.php.net/manual/en/book.mail.php
1754
     *
1755
     * @param string $header The message headers
1756
     * @param string $body   The message body
1757
     *
1758
     * @throws Exception
1759
     *
1760
     * @return bool
1761
     */
1762
    protected function mailSend($header, $body)
1763
    {
1764
        $header = static::stripTrailingWSP($header) . static::$LE . static::$LE;
1765
1766
        $toArr = [];
1767
        foreach ($this->to as $toaddr) {
1768
            $toArr[] = $this->addrFormat($toaddr);
1769
        }
1770
        $to = implode(', ', $toArr);
1771
1772
        $params = null;
1773
        //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
1774
        //A space after `-f` is optional, but there is a long history of its presence
1775
        //causing problems, so we don't use one
1776
        //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
1777
        //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html
1778
        //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html
1779
        //Example problem: https://www.drupal.org/node/1057954
1780
        // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1781
        if (!empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) {
1782
            $params = sprintf('-f%s', $this->Sender);
1783
        }
1784
        if (!empty($this->Sender) && static::validateAddress($this->Sender)) {
1785
            $old_from = ini_get('sendmail_from');
1786
            ini_set('sendmail_from', $this->Sender);
1787
        }
1788
        $result = false;
1789
        if ($this->SingleTo && count($toArr) > 1) {
1790
            foreach ($toArr as $toAddr) {
1791
                $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
1792
                $this->doCallback($result, [$toAddr], $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);
1793
            }
1794
        } else {
1795
            $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
1796
            $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);
1797
        }
1798
        if (isset($old_from)) {
1799
            ini_set('sendmail_from', $old_from);
1800
        }
1801
        if (!$result) {
1802
            throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL);
1803
        }
1804
1805
        return true;
1806
    }
1807
1808
    /**
1809
     * Get an instance to use for SMTP operations.
1810
     * Override this function to load your own SMTP implementation,
1811
     * or set one with setSMTPInstance.
1812
     *
1813
     * @return SMTP
1814
     */
1815
    public function getSMTPInstance()
1816
    {
1817
        if (!is_object($this->smtp)) {
1818
            $this->smtp = new SMTP();
1819
        }
1820
1821
        return $this->smtp;
1822
    }
1823
1824
    /**
1825
     * Provide an instance to use for SMTP operations.
1826
     *
1827
     * @return SMTP
1828
     */
1829
    public function setSMTPInstance(SMTP $smtp)
1830
    {
1831
        $this->smtp = $smtp;
1832
1833
        return $this->smtp;
1834
    }
1835
1836
    /**
1837
     * Send mail via SMTP.
1838
     * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
1839
     *
1840
     * @see PHPMailer::setSMTPInstance() to use a different class.
1841
     *
1842
     * @uses \PHPMailer\PHPMailer\SMTP
1843
     *
1844
     * @param string $header The message headers
1845
     * @param string $body   The message body
1846
     *
1847
     * @throws Exception
1848
     *
1849
     * @return bool
1850
     */
1851
    protected function smtpSend($header, $body)
1852
    {
1853
        $header = static::stripTrailingWSP($header) . static::$LE . static::$LE;
1854
        $bad_rcpt = [];
1855
        if (!$this->smtpConnect($this->SMTPOptions)) {
1856
            throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
1857
        }
1858
        //Sender already validated in preSend()
1859
        if ('' === $this->Sender) {
1860
            $smtp_from = $this->From;
1861
        } else {
1862
            $smtp_from = $this->Sender;
1863
        }
1864
        if (!$this->smtp->mail($smtp_from)) {
1865
            $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
1866
            throw new Exception($this->ErrorInfo, self::STOP_CRITICAL);
1867
        }
1868
1869
        $callbacks = [];
1870
        // Attempt to send to all recipients
1871
        foreach ([$this->to, $this->cc, $this->bcc] as $togroup) {
1872
            foreach ($togroup as $to) {
1873
                if (!$this->smtp->recipient($to[0], $this->dsn)) {
1874
                    $error = $this->smtp->getError();
1875
                    $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']];
1876
                    $isSent = false;
1877
                } else {
1878
                    $isSent = true;
1879
                }
1880
1881
                $callbacks[] = ['issent'=>$isSent, 'to'=>$to[0]];
1882
            }
1883
        }
1884
1885
        // Only send the DATA command if we have viable recipients
1886
        if ((count($this->all_recipients) > count($bad_rcpt)) && !$this->smtp->data($header . $body)) {
1887
            throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL);
1888
        }
1889
1890
        $smtp_transaction_id = $this->smtp->getLastTransactionID();
1891
1892
        if ($this->SMTPKeepAlive) {
1893
            $this->smtp->reset();
1894
        } else {
1895
            $this->smtp->quit();
1896
            $this->smtp->close();
1897
        }
1898
1899
        foreach ($callbacks as $cb) {
1900
            $this->doCallback(
1901
                $cb['issent'],
1902
                [$cb['to']],
1903
                [],
1904
                [],
1905
                $this->Subject,
1906
                $body,
1907
                $this->From,
1908
                ['smtp_transaction_id' => $smtp_transaction_id]
1909
            );
1910
        }
1911
1912
        //Create error message for any bad addresses
1913
        if (count($bad_rcpt) > 0) {
1914
            $errstr = '';
1915
            foreach ($bad_rcpt as $bad) {
1916
                $errstr .= $bad['to'] . ': ' . $bad['error'];
1917
            }
1918
            throw new Exception($this->lang('recipients_failed') . $errstr, self::STOP_CONTINUE);
1919
        }
1920
1921
        return true;
1922
    }
1923
1924
    /**
1925
     * Initiate a connection to an SMTP server.
1926
     * Returns false if the operation failed.
1927
     *
1928
     * @param array $options An array of options compatible with stream_context_create()
1929
     *
1930
     * @throws Exception
1931
     *
1932
     * @uses \PHPMailer\PHPMailer\SMTP
1933
     *
1934
     * @return bool
1935
     */
1936
    public function smtpConnect($options = null)
1937
    {
1938
        if (null === $this->smtp) {
1939
            $this->smtp = $this->getSMTPInstance();
1940
        }
1941
1942
        //If no options are provided, use whatever is set in the instance
1943
        if (null === $options) {
1944
            $options = $this->SMTPOptions;
1945
        }
1946
1947
        // Already connected?
1948
        if ($this->smtp->connected()) {
1949
            return true;
1950
        }
1951
1952
        $this->smtp->setTimeout($this->Timeout);
1953
        $this->smtp->setDebugLevel($this->SMTPDebug);
1954
        $this->smtp->setDebugOutput($this->Debugoutput);
1955
        $this->smtp->setVerp($this->do_verp);
1956
        $hosts = explode(';', $this->Host);
1957
        $lastexception = null;
1958
1959
        foreach ($hosts as $hostentry) {
1960
            $hostinfo = [];
1961
            if (!preg_match(
1962
                '/^(?:(ssl|tls):\/\/)?(.+?)(?::(\d+))?$/',
1963
                trim($hostentry),
1964
                $hostinfo
1965
            )) {
1966
                $this->edebug($this->lang('invalid_hostentry') . ' ' . trim($hostentry));
1967
                // Not a valid host entry
1968
                continue;
1969
            }
1970
            // $hostinfo[1]: optional ssl or tls prefix
1971
            // $hostinfo[2]: the hostname
1972
            // $hostinfo[3]: optional port number
1973
            // The host string prefix can temporarily override the current setting for SMTPSecure
1974
            // If it's not specified, the default value is used
1975
1976
            //Check the host name is a valid name or IP address before trying to use it
1977
            if (!static::isValidHost($hostinfo[2])) {
1978
                $this->edebug($this->lang('invalid_host') . ' ' . $hostinfo[2]);
1979
                continue;
1980
            }
1981
            $prefix = '';
1982
            $secure = $this->SMTPSecure;
1983
            $tls = (static::ENCRYPTION_STARTTLS === $this->SMTPSecure);
1984
            if ('ssl' === $hostinfo[1] || ('' === $hostinfo[1] && static::ENCRYPTION_SMTPS === $this->SMTPSecure)) {
1985
                $prefix = 'ssl://';
1986
                $tls = false; // Can't have SSL and TLS at the same time
1987
                $secure = static::ENCRYPTION_SMTPS;
1988
            } elseif ('tls' === $hostinfo[1]) {
1989
                $tls = true;
1990
                // tls doesn't use a prefix
1991
                $secure = static::ENCRYPTION_STARTTLS;
1992
            }
1993
            //Do we need the OpenSSL extension?
1994
            $sslext = defined('OPENSSL_ALGO_SHA256');
1995
            if (static::ENCRYPTION_STARTTLS === $secure || static::ENCRYPTION_SMTPS === $secure) {
1996
                //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
1997
                if (!$sslext) {
1998
                    throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL);
1999
                }
2000
            }
2001
            $host = $hostinfo[2];
2002
            $port = $this->Port;
2003
            if (array_key_exists(3, $hostinfo) && is_numeric($hostinfo[3]) && $hostinfo[3] > 0 && $hostinfo[3] < 65536) {
2004
                $port = (int) $hostinfo[3];
2005
            }
2006
            if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
2007
                try {
2008
                    if ($this->Helo) {
2009
                        $hello = $this->Helo;
2010
                    } else {
2011
                        $hello = $this->serverHostname();
2012
                    }
2013
                    $this->smtp->hello($hello);
2014
                    //Automatically enable TLS encryption if:
2015
                    // * it's not disabled
2016
                    // * we have openssl extension
2017
                    // * we are not already using SSL
2018
                    // * the server offers STARTTLS
2019
                    if ($this->SMTPAutoTLS && $sslext && 'ssl' !== $secure && $this->smtp->getServerExt('STARTTLS')) {
2020
                        $tls = true;
2021
                    }
2022
                    if ($tls) {
2023
                        if (!$this->smtp->startTLS()) {
2024
                            throw new Exception($this->lang('connect_host'));
2025
                        }
2026
                        // We must resend EHLO after TLS negotiation
2027
                        $this->smtp->hello($hello);
2028
                    }
2029
                    if ($this->SMTPAuth && !$this->smtp->authenticate(
2030
                        $this->Username,
2031
                        $this->Password,
2032
                        $this->AuthType,
2033
                        $this->oauth
2034
                    )) {
2035
                        throw new Exception($this->lang('authenticate'));
2036
                    }
2037
2038
                    return true;
2039
                } catch (Exception $exc) {
2040
                    $lastexception = $exc;
2041
                    $this->edebug($exc->getMessage());
2042
                    // We must have connected, but then failed TLS or Auth, so close connection nicely
2043
                    $this->smtp->quit();
2044
                }
2045
            }
2046
        }
2047
        // If we get here, all connection attempts have failed, so close connection hard
2048
        $this->smtp->close();
2049
        // As we've caught all exceptions, just report whatever the last one was
2050
        if ($this->exceptions && null !== $lastexception) {
2051
            throw $lastexception;
2052
        }
2053
2054
        return false;
2055
    }
2056
2057
    /**
2058
     * Close the active SMTP session if one exists.
2059
     */
2060
    public function smtpClose()
2061
    {
2062
        if ((null !== $this->smtp) && $this->smtp->connected()) {
2063
            $this->smtp->quit();
2064
            $this->smtp->close();
2065
        }
2066
    }
2067
2068
    /**
2069
     * Set the language for error messages.
2070
     * Returns false if it cannot load the language file.
2071
     * The default language is English.
2072
     *
2073
     * @param string $langcode  ISO 639-1 2-character language code (e.g. French is "fr")
2074
     * @param string $lang_path Path to the language file directory, with trailing separator (slash)
2075
     *
2076
     * @return bool
2077
     */
2078
    public function setLanguage($langcode = 'en', $lang_path = '')
2079
    {
2080
        // Backwards compatibility for renamed language codes
2081
        $renamed_langcodes = [
2082
            'br' => 'pt_br',
2083
            'cz' => 'cs',
2084
            'dk' => 'da',
2085
            'no' => 'nb',
2086
            'se' => 'sv',
2087
            'rs' => 'sr',
2088
            'tg' => 'tl',
2089
        ];
2090
2091
        if (isset($renamed_langcodes[$langcode])) {
2092
            $langcode = $renamed_langcodes[$langcode];
2093
        }
2094
2095
        // Define full set of translatable strings in English
2096
        $PHPMAILER_LANG = [
2097
            'authenticate' => 'SMTP Error: Could not authenticate.',
2098
            'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
2099
            'data_not_accepted' => 'SMTP Error: data not accepted.',
2100
            'empty_message' => 'Message body empty',
2101
            'encoding' => 'Unknown encoding: ',
2102
            'execute' => 'Could not execute: ',
2103
            'file_access' => 'Could not access file: ',
2104
            'file_open' => 'File Error: Could not open file: ',
2105
            'from_failed' => 'The following From address failed: ',
2106
            'instantiate' => 'Could not instantiate mail function.',
2107
            'invalid_address' => 'Invalid address: ',
2108
            'invalid_hostentry' => 'Invalid hostentry: ',
2109
            'invalid_host' => 'Invalid host: ',
2110
            'mailer_not_supported' => ' mailer is not supported.',
2111
            'provide_address' => 'You must provide at least one recipient email address.',
2112
            'recipients_failed' => 'SMTP Error: The following recipients failed: ',
2113
            'signing' => 'Signing Error: ',
2114
            'smtp_connect_failed' => 'SMTP connect() failed.',
2115
            'smtp_error' => 'SMTP server error: ',
2116
            'variable_set' => 'Cannot set or reset variable: ',
2117
            'extension_missing' => 'Extension missing: ',
2118
        ];
2119
        if (empty($lang_path)) {
2120
            // Calculate an absolute path so it can work if CWD is not here
2121
            $lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR;
2122
        }
2123
        //Validate $langcode
2124
        if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) {
2125
            $langcode = 'en';
2126
        }
2127
        $foundlang = true;
2128
        $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
2129
        // There is no English translation file
2130
        if ('en' !== $langcode) {
2131
            // Make sure language file path is readable
2132
            if (!static::isPermittedPath($lang_file) || !file_exists($lang_file)) {
2133
                $foundlang = false;
2134
            } else {
2135
                // Overwrite language-specific strings.
2136
                // This way we'll never have missing translation keys.
2137
                $foundlang = include $lang_file;
2138
            }
2139
        }
2140
        $this->language = $PHPMAILER_LANG;
2141
2142
        return (bool) $foundlang; // Returns false if language not found
2143
    }
2144
2145
    /**
2146
     * Get the array of strings for the current language.
2147
     *
2148
     * @return array
2149
     */
2150
    public function getTranslations()
2151
    {
2152
        return $this->language;
2153
    }
2154
2155
    /**
2156
     * Create recipient headers.
2157
     *
2158
     * @param string $type
2159
     * @param array  $addr An array of recipients,
2160
     *                     where each recipient is a 2-element indexed array with element 0 containing an address
2161
     *                     and element 1 containing a name, like:
2162
     *                     [['[email protected]', 'Joe User'], ['[email protected]', 'Zoe User']]
2163
     *
2164
     * @return string
2165
     */
2166
    public function addrAppend($type, $addr)
2167
    {
2168
        $addresses = [];
2169
        foreach ($addr as $address) {
2170
            $addresses[] = $this->addrFormat($address);
2171
        }
2172
2173
        return $type . ': ' . implode(', ', $addresses) . static::$LE;
2174
    }
2175
2176
    /**
2177
     * Format an address for use in a message header.
2178
     *
2179
     * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name like
2180
     *                    ['[email protected]', 'Joe User']
2181
     *
2182
     * @return string
2183
     */
2184
    public function addrFormat($addr)
2185
    {
2186
        if (empty($addr[1])) { // No name provided
2187
            return $this->secureHeader($addr[0]);
2188
        }
2189
2190
        return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') .
2191
            ' <' . $this->secureHeader($addr[0]) . '>';
2192
    }
2193
2194
    /**
2195
     * Word-wrap message.
2196
     * For use with mailers that do not automatically perform wrapping
2197
     * and for quoted-printable encoded messages.
2198
     * Original written by philippe.
2199
     *
2200
     * @param string $message The message to wrap
2201
     * @param int    $length  The line length to wrap to
2202
     * @param bool   $qp_mode Whether to run in Quoted-Printable mode
2203
     *
2204
     * @return string
2205
     */
2206
    public function wrapText($message, $length, $qp_mode = false)
2207
    {
2208
        if ($qp_mode) {
2209
            $soft_break = sprintf(' =%s', static::$LE);
2210
        } else {
2211
            $soft_break = static::$LE;
2212
        }
2213
        // If utf-8 encoding is used, we will need to make sure we don't
2214
        // split multibyte characters when we wrap
2215
        $is_utf8 = static::CHARSET_UTF8 === strtolower($this->CharSet);
2216
        $lelen = strlen(static::$LE);
2217
        $crlflen = strlen(static::$LE);
2218
2219
        $message = static::normalizeBreaks($message);
2220
        //Remove a trailing line break
2221
        if (substr($message, -$lelen) === static::$LE) {
2222
            $message = substr($message, 0, -$lelen);
2223
        }
2224
2225
        //Split message into lines
2226
        $lines = explode(static::$LE, $message);
2227
        //Message will be rebuilt in here
2228
        $message = '';
2229
        foreach ($lines as $line) {
2230
            $words = explode(' ', $line);
2231
            $buf = '';
2232
            $firstword = true;
2233
            foreach ($words as $word) {
2234
                if ($qp_mode && (strlen($word) > $length)) {
2235
                    $space_left = $length - strlen($buf) - $crlflen;
2236
                    if (!$firstword) {
2237
                        if ($space_left > 20) {
2238
                            $len = $space_left;
2239
                            if ($is_utf8) {
2240
                                $len = $this->utf8CharBoundary($word, $len);
2241
                            } elseif ('=' === substr($word, $len - 1, 1)) {
2242
                                --$len;
2243
                            } elseif ('=' === substr($word, $len - 2, 1)) {
2244
                                $len -= 2;
2245
                            }
2246
                            $part = substr($word, 0, $len);
2247
                            $word = substr($word, $len);
2248
                            $buf .= ' ' . $part;
2249
                            $message .= $buf . sprintf('=%s', static::$LE);
2250
                        } else {
2251
                            $message .= $buf . $soft_break;
2252
                        }
2253
                        $buf = '';
2254
                    }
2255
                    while ($word !== '') {
2256
                        if ($length <= 0) {
2257
                            break;
2258
                        }
2259
                        $len = $length;
2260
                        if ($is_utf8) {
2261
                            $len = $this->utf8CharBoundary($word, $len);
2262
                        } elseif ('=' === substr($word, $len - 1, 1)) {
2263
                            --$len;
2264
                        } elseif ('=' === substr($word, $len - 2, 1)) {
2265
                            $len -= 2;
2266
                        }
2267
                        $part = substr($word, 0, $len);
2268
                        $word = (string) substr($word, $len);
2269
2270
                        if ($word !== '') {
2271
                            $message .= $part . sprintf('=%s', static::$LE);
2272
                        } else {
2273
                            $buf = $part;
2274
                        }
2275
                    }
2276
                } else {
2277
                    $buf_o = $buf;
2278
                    if (!$firstword) {
2279
                        $buf .= ' ';
2280
                    }
2281
                    $buf .= $word;
2282
2283
                    if ('' !== $buf_o && strlen($buf) > $length) {
2284
                        $message .= $buf_o . $soft_break;
2285
                        $buf = $word;
2286
                    }
2287
                }
2288
                $firstword = false;
2289
            }
2290
            $message .= $buf . static::$LE;
2291
        }
2292
2293
        return $message;
2294
    }
2295
2296
    /**
2297
     * Find the last character boundary prior to $maxLength in a utf-8
2298
     * quoted-printable encoded string.
2299
     * Original written by Colin Brown.
2300
     *
2301
     * @param string $encodedText utf-8 QP text
2302
     * @param int    $maxLength   Find the last character boundary prior to this length
2303
     *
2304
     * @return int
2305
     */
2306
    public function utf8CharBoundary($encodedText, $maxLength)
2307
    {
2308
        $foundSplitPos = false;
2309
        $lookBack = 3;
2310
        while (!$foundSplitPos) {
2311
            $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
2312
            $encodedCharPos = strpos($lastChunk, '=');
2313
            if (false !== $encodedCharPos) {
2314
                // Found start of encoded character byte within $lookBack block.
2315
                // Check the encoded byte value (the 2 chars after the '=')
2316
                $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
2317
                $dec = hexdec($hex);
2318
                if ($dec < 128) {
2319
                    // Single byte character.
2320
                    // If the encoded char was found at pos 0, it will fit
2321
                    // otherwise reduce maxLength to start of the encoded char
2322
                    if ($encodedCharPos > 0) {
2323
                        $maxLength -= $lookBack - $encodedCharPos;
2324
                    }
2325
                    $foundSplitPos = true;
2326
                } elseif ($dec >= 192) {
2327
                    // First byte of a multi byte character
2328
                    // Reduce maxLength to split at start of character
2329
                    $maxLength -= $lookBack - $encodedCharPos;
2330
                    $foundSplitPos = true;
2331
                } elseif ($dec < 192) {
2332
                    // Middle byte of a multi byte character, look further back
2333
                    $lookBack += 3;
2334
                }
2335
            } else {
2336
                // No encoded character found
2337
                $foundSplitPos = true;
2338
            }
2339
        }
2340
2341
        return $maxLength;
2342
    }
2343
2344
    /**
2345
     * Apply word wrapping to the message body.
2346
     * Wraps the message body to the number of chars set in the WordWrap property.
2347
     * You should only do this to plain-text bodies as wrapping HTML tags may break them.
2348
     * This is called automatically by createBody(), so you don't need to call it yourself.
2349
     */
2350
    public function setWordWrap()
2351
    {
2352
        if ($this->WordWrap < 1) {
2353
            return;
2354
        }
2355
2356
        switch ($this->message_type) {
2357
            case 'alt':
2358
            case 'alt_inline':
2359
            case 'alt_attach':
2360
            case 'alt_inline_attach':
2361
                $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
2362
                break;
2363
            default:
2364
                $this->Body = $this->wrapText($this->Body, $this->WordWrap);
2365
                break;
2366
        }
2367
    }
2368
2369
    /**
2370
     * Assemble message headers.
2371
     *
2372
     * @return string The assembled headers
2373
     */
2374
    public function createHeader()
2375
    {
2376
        $result = '';
2377
2378
        $result .= $this->headerLine('Date', '' === $this->MessageDate ? self::rfcDate() : $this->MessageDate);
2379
2380
        // To be created automatically by mail()
2381
        if ($this->SingleTo) {
2382
            if ('mail' !== $this->Mailer) {
2383
                foreach ($this->to as $toaddr) {
2384
                    $this->SingleToArray[] = $this->addrFormat($toaddr);
2385
                }
2386
            }
2387
        } elseif (count($this->to) > 0) {
2388
            if ('mail' !== $this->Mailer) {
2389
                $result .= $this->addrAppend('To', $this->to);
2390
            }
2391
        } elseif (count($this->cc) === 0) {
2392
            $result .= $this->headerLine('To', 'undisclosed-recipients:;');
2393
        }
2394
2395
        $result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]);
2396
2397
        // sendmail and mail() extract Cc from the header before sending
2398
        if (count($this->cc) > 0) {
2399
            $result .= $this->addrAppend('Cc', $this->cc);
2400
        }
2401
2402
        // sendmail and mail() extract Bcc from the header before sending
2403
        if ((
2404
                'sendmail' === $this->Mailer || 'qmail' === $this->Mailer || 'mail' === $this->Mailer
2405
            )
2406
            && count($this->bcc) > 0
2407
        ) {
2408
            $result .= $this->addrAppend('Bcc', $this->bcc);
2409
        }
2410
2411
        if (count($this->ReplyTo) > 0) {
2412
            $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
2413
        }
2414
2415
        // mail() sets the subject itself
2416
        if ('mail' !== $this->Mailer) {
2417
            $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
2418
        }
2419
2420
        // Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4
2421
        // https://tools.ietf.org/html/rfc5322#section-3.6.4
2422
        if ('' !== $this->MessageID && preg_match('/^<.*@.*>$/', $this->MessageID)) {
2423
            $this->lastMessageID = $this->MessageID;
2424
        } else {
2425
            $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());
2426
        }
2427
        $result .= $this->headerLine('Message-ID', $this->lastMessageID);
2428
        if (null !== $this->Priority) {
2429
            $result .= $this->headerLine('X-Priority', $this->Priority);
2430
        }
2431
        if ('' === $this->XMailer) {
2432
            $result .= $this->headerLine(
2433
                'X-Mailer',
2434
                'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)'
2435
            );
2436
        } else {
2437
            $myXmailer = trim($this->XMailer);
2438
            if ($myXmailer) {
2439
                $result .= $this->headerLine('X-Mailer', $myXmailer);
2440
            }
2441
        }
2442
2443
        if ('' !== $this->ConfirmReadingTo) {
2444
            $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
2445
        }
2446
2447
        // Add custom headers
2448
        foreach ($this->CustomHeader as $header) {
2449
            $result .= $this->headerLine(
2450
                trim($header[0]),
2451
                $this->encodeHeader(trim($header[1]))
2452
            );
2453
        }
2454
        if (!$this->sign_key_file) {
2455
            $result .= $this->headerLine('MIME-Version', '1.0');
2456
            $result .= $this->getMailMIME();
2457
        }
2458
2459
        return $result;
2460
    }
2461
2462
    /**
2463
     * Get the message MIME type headers.
2464
     *
2465
     * @return string
2466
     */
2467
    public function getMailMIME()
2468
    {
2469
        $result = '';
2470
        $ismultipart = true;
2471
        switch ($this->message_type) {
2472
            case 'inline':
2473
                $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2474
                $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
2475
                break;
2476
            case 'attach':
2477
            case 'inline_attach':
2478
            case 'alt_attach':
2479
            case 'alt_inline_attach':
2480
                $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_MIXED . ';');
2481
                $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
2482
                break;
2483
            case 'alt':
2484
            case 'alt_inline':
2485
                $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
2486
                $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
2487
                break;
2488
            default:
2489
                // Catches case 'plain': and case '':
2490
                $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
2491
                $ismultipart = false;
2492
                break;
2493
        }
2494
        // RFC1341 part 5 says 7bit is assumed if not specified
2495
        if (static::ENCODING_7BIT !== $this->Encoding) {
2496
            // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
2497
            if ($ismultipart) {
2498
                if (static::ENCODING_8BIT === $this->Encoding) {
2499
                    $result .= $this->headerLine('Content-Transfer-Encoding', static::ENCODING_8BIT);
2500
                }
2501
                // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
2502
            } else {
2503
                $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
2504
            }
2505
        }
2506
2507
        if ('mail' !== $this->Mailer) {
2508
//            $result .= static::$LE;
2509
        }
2510
2511
        return $result;
2512
    }
2513
2514
    /**
2515
     * Returns the whole MIME message.
2516
     * Includes complete headers and body.
2517
     * Only valid post preSend().
2518
     *
2519
     * @see PHPMailer::preSend()
2520
     *
2521
     * @return string
2522
     */
2523
    public function getSentMIMEMessage()
2524
    {
2525
        return static::stripTrailingWSP($this->MIMEHeader . $this->mailHeader) .
2526
            static::$LE . static::$LE . $this->MIMEBody;
2527
    }
2528
2529
    /**
2530
     * Create a unique ID to use for boundaries.
2531
     *
2532
     * @return string
2533
     */
2534
    protected function generateId()
2535
    {
2536
        $len = 32; //32 bytes = 256 bits
2537
        $bytes = '';
2538
        if (function_exists('random_bytes')) {
2539
            try {
2540
                $bytes = random_bytes($len);
2541
            } catch (\Exception $e) {
2542
                //Do nothing
2543
            }
2544
        } elseif (function_exists('openssl_random_pseudo_bytes')) {
2545
            /** @noinspection CryptographicallySecureRandomnessInspection */
2546
            $bytes = openssl_random_pseudo_bytes($len);
2547
        }
2548
        if ($bytes === '') {
2549
            //We failed to produce a proper random string, so make do.
2550
            //Use a hash to force the length to the same as the other methods
2551
            $bytes = hash('sha256', uniqid((string) mt_rand(), true), true);
2552
        }
2553
2554
        //We don't care about messing up base64 format here, just want a random string
2555
        return str_replace(['=', '+', '/'], '', base64_encode(hash('sha256', $bytes, true)));
2556
    }
2557
2558
    /**
2559
     * Assemble the message body.
2560
     * Returns an empty string on failure.
2561
     *
2562
     * @throws Exception
2563
     *
2564
     * @return string The assembled message body
2565
     */
2566
    public function createBody()
2567
    {
2568
        $body = '';
2569
        //Create unique IDs and preset boundaries
2570
        $this->uniqueid = $this->generateId();
2571
        $this->boundary[1] = 'b1_' . $this->uniqueid;
2572
        $this->boundary[2] = 'b2_' . $this->uniqueid;
2573
        $this->boundary[3] = 'b3_' . $this->uniqueid;
2574
2575
        if ($this->sign_key_file) {
2576
            $body .= $this->getMailMIME() . static::$LE;
2577
        }
2578
2579
        $this->setWordWrap();
2580
2581
        $bodyEncoding = $this->Encoding;
2582
        $bodyCharSet = $this->CharSet;
2583
        //Can we do a 7-bit downgrade?
2584
        if (static::ENCODING_8BIT === $bodyEncoding && !$this->has8bitChars($this->Body)) {
2585
            $bodyEncoding = static::ENCODING_7BIT;
2586
            //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
2587
            $bodyCharSet = static::CHARSET_ASCII;
2588
        }
2589
        //If lines are too long, and we're not already using an encoding that will shorten them,
2590
        //change to quoted-printable transfer encoding for the body part only
2591
        if (static::ENCODING_BASE64 !== $this->Encoding && static::hasLineLongerThanMax($this->Body)) {
2592
            $bodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
2593
        }
2594
2595
        $altBodyEncoding = $this->Encoding;
2596
        $altBodyCharSet = $this->CharSet;
2597
        //Can we do a 7-bit downgrade?
2598
        if (static::ENCODING_8BIT === $altBodyEncoding && !$this->has8bitChars($this->AltBody)) {
2599
            $altBodyEncoding = static::ENCODING_7BIT;
2600
            //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
2601
            $altBodyCharSet = static::CHARSET_ASCII;
2602
        }
2603
        //If lines are too long, and we're not already using an encoding that will shorten them,
2604
        //change to quoted-printable transfer encoding for the alt body part only
2605
        if (static::ENCODING_BASE64 !== $altBodyEncoding && static::hasLineLongerThanMax($this->AltBody)) {
2606
            $altBodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
2607
        }
2608
        //Use this as a preamble in all multipart message types
2609
        $mimepre = 'This is a multi-part message in MIME format.' . static::$LE;
2610
        switch ($this->message_type) {
2611
            case 'inline':
2612
                $body .= $mimepre;
2613
                $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
2614
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2615
                $body .= static::$LE;
2616
                $body .= $this->attachAll('inline', $this->boundary[1]);
2617
                break;
2618
            case 'attach':
2619
                $body .= $mimepre;
2620
                $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
2621
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2622
                $body .= static::$LE;
2623
                $body .= $this->attachAll('attachment', $this->boundary[1]);
2624
                break;
2625
            case 'inline_attach':
2626
                $body .= $mimepre;
2627
                $body .= $this->textLine('--' . $this->boundary[1]);
2628
                $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2629
                $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";');
2630
                $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
2631
                $body .= static::$LE;
2632
                $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
2633
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2634
                $body .= static::$LE;
2635
                $body .= $this->attachAll('inline', $this->boundary[2]);
2636
                $body .= static::$LE;
2637
                $body .= $this->attachAll('attachment', $this->boundary[1]);
2638
                break;
2639
            case 'alt':
2640
                $body .= $mimepre;
2641
                $body .= $this->getBoundary(
2642
                    $this->boundary[1],
2643
                    $altBodyCharSet,
2644
                    static::CONTENT_TYPE_PLAINTEXT,
2645
                    $altBodyEncoding
2646
                );
2647
                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2648
                $body .= static::$LE;
2649
                $body .= $this->getBoundary(
2650
                    $this->boundary[1],
2651
                    $bodyCharSet,
2652
                    static::CONTENT_TYPE_TEXT_HTML,
2653
                    $bodyEncoding
2654
                );
2655
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2656
                $body .= static::$LE;
2657
                if (!empty($this->Ical)) {
2658
                    $method = static::ICAL_METHOD_REQUEST;
2659
                    foreach (static::$IcalMethods as $imethod) {
2660
                        if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) {
2661
                            $method = $imethod;
2662
                            break;
2663
                        }
2664
                    }
2665
                    $body .= $this->getBoundary(
2666
                        $this->boundary[1],
2667
                        '',
2668
                        static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method,
2669
                        ''
2670
                    );
2671
                    $body .= $this->encodeString($this->Ical, $this->Encoding);
2672
                    $body .= static::$LE;
2673
                }
2674
                $body .= $this->endBoundary($this->boundary[1]);
2675
                break;
2676
            case 'alt_inline':
2677
                $body .= $mimepre;
2678
                $body .= $this->getBoundary(
2679
                    $this->boundary[1],
2680
                    $altBodyCharSet,
2681
                    static::CONTENT_TYPE_PLAINTEXT,
2682
                    $altBodyEncoding
2683
                );
2684
                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2685
                $body .= static::$LE;
2686
                $body .= $this->textLine('--' . $this->boundary[1]);
2687
                $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2688
                $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";');
2689
                $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
2690
                $body .= static::$LE;
2691
                $body .= $this->getBoundary(
2692
                    $this->boundary[2],
2693
                    $bodyCharSet,
2694
                    static::CONTENT_TYPE_TEXT_HTML,
2695
                    $bodyEncoding
2696
                );
2697
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2698
                $body .= static::$LE;
2699
                $body .= $this->attachAll('inline', $this->boundary[2]);
2700
                $body .= static::$LE;
2701
                $body .= $this->endBoundary($this->boundary[1]);
2702
                break;
2703
            case 'alt_attach':
2704
                $body .= $mimepre;
2705
                $body .= $this->textLine('--' . $this->boundary[1]);
2706
                $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
2707
                $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"');
2708
                $body .= static::$LE;
2709
                $body .= $this->getBoundary(
2710
                    $this->boundary[2],
2711
                    $altBodyCharSet,
2712
                    static::CONTENT_TYPE_PLAINTEXT,
2713
                    $altBodyEncoding
2714
                );
2715
                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2716
                $body .= static::$LE;
2717
                $body .= $this->getBoundary(
2718
                    $this->boundary[2],
2719
                    $bodyCharSet,
2720
                    static::CONTENT_TYPE_TEXT_HTML,
2721
                    $bodyEncoding
2722
                );
2723
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2724
                $body .= static::$LE;
2725
                if (!empty($this->Ical)) {
2726
                    $method = static::ICAL_METHOD_REQUEST;
2727
                    foreach (static::$IcalMethods as $imethod) {
2728
                        if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) {
2729
                            $method = $imethod;
2730
                            break;
2731
                        }
2732
                    }
2733
                    $body .= $this->getBoundary(
2734
                        $this->boundary[2],
2735
                        '',
2736
                        static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method,
2737
                        ''
2738
                    );
2739
                    $body .= $this->encodeString($this->Ical, $this->Encoding);
2740
                }
2741
                $body .= $this->endBoundary($this->boundary[2]);
2742
                $body .= static::$LE;
2743
                $body .= $this->attachAll('attachment', $this->boundary[1]);
2744
                break;
2745
            case 'alt_inline_attach':
2746
                $body .= $mimepre;
2747
                $body .= $this->textLine('--' . $this->boundary[1]);
2748
                $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
2749
                $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"');
2750
                $body .= static::$LE;
2751
                $body .= $this->getBoundary(
2752
                    $this->boundary[2],
2753
                    $altBodyCharSet,
2754
                    static::CONTENT_TYPE_PLAINTEXT,
2755
                    $altBodyEncoding
2756
                );
2757
                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2758
                $body .= static::$LE;
2759
                $body .= $this->textLine('--' . $this->boundary[2]);
2760
                $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2761
                $body .= $this->textLine(' boundary="' . $this->boundary[3] . '";');
2762
                $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
2763
                $body .= static::$LE;
2764
                $body .= $this->getBoundary(
2765
                    $this->boundary[3],
2766
                    $bodyCharSet,
2767
                    static::CONTENT_TYPE_TEXT_HTML,
2768
                    $bodyEncoding
2769
                );
2770
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2771
                $body .= static::$LE;
2772
                $body .= $this->attachAll('inline', $this->boundary[3]);
2773
                $body .= static::$LE;
2774
                $body .= $this->endBoundary($this->boundary[2]);
2775
                $body .= static::$LE;
2776
                $body .= $this->attachAll('attachment', $this->boundary[1]);
2777
                break;
2778
            default:
2779
                // Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types
2780
                //Reset the `Encoding` property in case we changed it for line length reasons
2781
                $this->Encoding = $bodyEncoding;
2782
                $body .= $this->encodeString($this->Body, $this->Encoding);
2783
                break;
2784
        }
2785
2786
        if ($this->isError()) {
2787
            $body = '';
2788
            if ($this->exceptions) {
2789
                throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
2790
            }
2791
        } elseif ($this->sign_key_file) {
2792
            try {
2793
                if (!defined('PKCS7_TEXT')) {
2794
                    throw new Exception($this->lang('extension_missing') . 'openssl');
2795
                }
2796
2797
                $file = tempnam(sys_get_temp_dir(), 'srcsign');
2798
                $signed = tempnam(sys_get_temp_dir(), 'mailsign');
2799
                file_put_contents($file, $body);
2800
2801
                //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
2802
                if (empty($this->sign_extracerts_file)) {
2803
                    $sign = @openssl_pkcs7_sign(
2804
                        $file,
2805
                        $signed,
2806
                        'file://' . realpath($this->sign_cert_file),
2807
                        ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
2808
                        []
2809
                    );
2810
                } else {
2811
                    $sign = @openssl_pkcs7_sign(
2812
                        $file,
2813
                        $signed,
2814
                        'file://' . realpath($this->sign_cert_file),
2815
                        ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
2816
                        [],
2817
                        PKCS7_DETACHED,
2818
                        $this->sign_extracerts_file
2819
                    );
2820
                }
2821
2822
                @unlink($file);
2823
                if ($sign) {
2824
                    $body = file_get_contents($signed);
2825
                    @unlink($signed);
2826
                    //The message returned by openssl contains both headers and body, so need to split them up
2827
                    $parts = explode("\n\n", $body, 2);
2828
                    $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE;
2829
                    $body = $parts[1];
2830
                } else {
2831
                    @unlink($signed);
2832
                    throw new Exception($this->lang('signing') . openssl_error_string());
2833
                }
2834
            } catch (Exception $exc) {
2835
                $body = '';
2836
                if ($this->exceptions) {
2837
                    throw $exc;
2838
                }
2839
            }
2840
        }
2841
2842
        return $body;
2843
    }
2844
2845
    /**
2846
     * Return the start of a message boundary.
2847
     *
2848
     * @param string $boundary
2849
     * @param string $charSet
2850
     * @param string $contentType
2851
     * @param string $encoding
2852
     *
2853
     * @return string
2854
     */
2855
    protected function getBoundary($boundary, $charSet, $contentType, $encoding)
2856
    {
2857
        $result = '';
2858
        if ('' === $charSet) {
2859
            $charSet = $this->CharSet;
2860
        }
2861
        if ('' === $contentType) {
2862
            $contentType = $this->ContentType;
2863
        }
2864
        if ('' === $encoding) {
2865
            $encoding = $this->Encoding;
2866
        }
2867
        $result .= $this->textLine('--' . $boundary);
2868
        $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
2869
        $result .= static::$LE;
2870
        // RFC1341 part 5 says 7bit is assumed if not specified
2871
        if (static::ENCODING_7BIT !== $encoding) {
2872
            $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
2873
        }
2874
        $result .= static::$LE;
2875
2876
        return $result;
2877
    }
2878
2879
    /**
2880
     * Return the end of a message boundary.
2881
     *
2882
     * @param string $boundary
2883
     *
2884
     * @return string
2885
     */
2886
    protected function endBoundary($boundary)
2887
    {
2888
        return static::$LE . '--' . $boundary . '--' . static::$LE;
2889
    }
2890
2891
    /**
2892
     * Set the message type.
2893
     * PHPMailer only supports some preset message types, not arbitrary MIME structures.
2894
     */
2895
    protected function setMessageType()
2896
    {
2897
        $type = [];
2898
        if ($this->alternativeExists()) {
2899
            $type[] = 'alt';
2900
        }
2901
        if ($this->inlineImageExists()) {
2902
            $type[] = 'inline';
2903
        }
2904
        if ($this->attachmentExists()) {
2905
            $type[] = 'attach';
2906
        }
2907
        $this->message_type = implode('_', $type);
2908
        if ('' === $this->message_type) {
2909
            //The 'plain' message_type refers to the message having a single body element, not that it is plain-text
2910
            $this->message_type = 'plain';
2911
        }
2912
    }
2913
2914
    /**
2915
     * Format a header line.
2916
     *
2917
     * @param string     $name
2918
     * @param string|int $value
2919
     *
2920
     * @return string
2921
     */
2922
    public function headerLine($name, $value)
2923
    {
2924
        return $name . ': ' . $value . static::$LE;
2925
    }
2926
2927
    /**
2928
     * Return a formatted mail line.
2929
     *
2930
     * @param string $value
2931
     *
2932
     * @return string
2933
     */
2934
    public function textLine($value)
2935
    {
2936
        return $value . static::$LE;
2937
    }
2938
2939
    /**
2940
     * Add an attachment from a path on the filesystem.
2941
     * Never use a user-supplied path to a file!
2942
     * Returns false if the file could not be found or read.
2943
     * Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client.
2944
     * If you need to do that, fetch the resource yourself and pass it in via a local file or string.
2945
     *
2946
     * @param string $path        Path to the attachment
2947
     * @param string $name        Overrides the attachment name
2948
     * @param string $encoding    File encoding (see $Encoding)
2949
     * @param string $type        File extension (MIME) type
2950
     * @param string $disposition Disposition to use
2951
     *
2952
     * @throws Exception
2953
     *
2954
     * @return bool
2955
     */
2956
    public function addAttachment(
2957
        $path,
2958
        $name = '',
2959
        $encoding = self::ENCODING_BASE64,
2960
        $type = '',
2961
        $disposition = 'attachment'
2962
    ) {
2963
        try {
2964
            if (!static::isPermittedPath($path) || !@is_file($path)) {
2965
                throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
2966
            }
2967
2968
            // If a MIME type is not specified, try to work it out from the file name
2969
            if ('' === $type) {
2970
                $type = static::filenameToType($path);
2971
            }
2972
2973
            $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME);
2974
            if ('' === $name) {
2975
                $name = $filename;
2976
            }
2977
2978
            if (!$this->validateEncoding($encoding)) {
2979
                throw new Exception($this->lang('encoding') . $encoding);
2980
            }
2981
2982
            $this->attachment[] = [
2983
                0 => $path,
2984
                1 => $filename,
2985
                2 => $name,
2986
                3 => $encoding,
2987
                4 => $type,
2988
                5 => false, // isStringAttachment
2989
                6 => $disposition,
2990
                7 => $name,
2991
            ];
2992
        } catch (Exception $exc) {
2993
            $this->setError($exc->getMessage());
2994
            $this->edebug($exc->getMessage());
2995
            if ($this->exceptions) {
2996
                throw $exc;
2997
            }
2998
2999
            return false;
3000
        }
3001
3002
        return true;
3003
    }
3004
3005
    /**
3006
     * Return the array of attachments.
3007
     *
3008
     * @return array
3009
     */
3010
    public function getAttachments()
3011
    {
3012
        return $this->attachment;
3013
    }
3014
3015
    /**
3016
     * Attach all file, string, and binary attachments to the message.
3017
     * Returns an empty string on failure.
3018
     *
3019
     * @param string $disposition_type
3020
     * @param string $boundary
3021
     *
3022
     * @throws Exception
3023
     *
3024
     * @return string
3025
     */
3026
    protected function attachAll($disposition_type, $boundary)
3027
    {
3028
        // Return text of body
3029
        $mime = [];
3030
        $cidUniq = [];
3031
        $incl = [];
3032
3033
        // Add all attachments
3034
        foreach ($this->attachment as $attachment) {
3035
            // Check if it is a valid disposition_filter
3036
            if ($attachment[6] === $disposition_type) {
3037
                // Check for string attachment
3038
                $string = '';
3039
                $path = '';
3040
                $bString = $attachment[5];
3041
                if ($bString) {
3042
                    $string = $attachment[0];
3043
                } else {
3044
                    $path = $attachment[0];
3045
                }
3046
3047
                $inclhash = hash('sha256', serialize($attachment));
3048
                if (in_array($inclhash, $incl, true)) {
3049
                    continue;
3050
                }
3051
                $incl[] = $inclhash;
3052
                $name = $attachment[2];
3053
                $encoding = $attachment[3];
3054
                $type = $attachment[4];
3055
                $disposition = $attachment[6];
3056
                $cid = $attachment[7];
3057
                if ('inline' === $disposition && array_key_exists($cid, $cidUniq)) {
3058
                    continue;
3059
                }
3060
                $cidUniq[$cid] = true;
3061
3062
                $mime[] = sprintf('--%s%s', $boundary, static::$LE);
3063
                //Only include a filename property if we have one
3064
                if (!empty($name)) {
3065
                    $mime[] = sprintf(
3066
                        'Content-Type: %s; name="%s"%s',
3067
                        $type,
3068
                        $this->encodeHeader($this->secureHeader($name)),
3069
                        static::$LE
3070
                    );
3071
                } else {
3072
                    $mime[] = sprintf(
3073
                        'Content-Type: %s%s',
3074
                        $type,
3075
                        static::$LE
3076
                    );
3077
                }
3078
                // RFC1341 part 5 says 7bit is assumed if not specified
3079
                if (static::ENCODING_7BIT !== $encoding) {
3080
                    $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE);
3081
                }
3082
3083
                //Only set Content-IDs on inline attachments
3084
                if ((string) $cid !== '' && $disposition === 'inline') {
3085
                    $mime[] = 'Content-ID: <' . $this->encodeHeader($this->secureHeader($cid)) . '>' . static::$LE;
3086
                }
3087
3088
                // If a filename contains any of these chars, it should be quoted,
3089
                // but not otherwise: RFC2183 & RFC2045 5.1
3090
                // Fixes a warning in IETF's msglint MIME checker
3091
                // Allow for bypassing the Content-Disposition header totally
3092
                if (!empty($disposition)) {
3093
                    $encoded_name = $this->encodeHeader($this->secureHeader($name));
3094
                    if (preg_match('/[ ()<>@,;:"\/\[\]?=]/', $encoded_name)) {
3095
                        $mime[] = sprintf(
3096
                            'Content-Disposition: %s; filename="%s"%s',
3097
                            $disposition,
3098
                            $encoded_name,
3099
                            static::$LE . static::$LE
3100
                        );
3101
                    } elseif (!empty($encoded_name)) {
3102
                        $mime[] = sprintf(
3103
                            'Content-Disposition: %s; filename=%s%s',
3104
                            $disposition,
3105
                            $encoded_name,
3106
                            static::$LE . static::$LE
3107
                        );
3108
                    } else {
3109
                        $mime[] = sprintf(
3110
                            'Content-Disposition: %s%s',
3111
                            $disposition,
3112
                            static::$LE . static::$LE
3113
                        );
3114
                    }
3115
                } else {
3116
                    $mime[] = static::$LE;
3117
                }
3118
3119
                // Encode as string attachment
3120
                if ($bString) {
3121
                    $mime[] = $this->encodeString($string, $encoding);
3122
                } else {
3123
                    $mime[] = $this->encodeFile($path, $encoding);
3124
                }
3125
                if ($this->isError()) {
3126
                    return '';
3127
                }
3128
                $mime[] = static::$LE;
3129
            }
3130
        }
3131
3132
        $mime[] = sprintf('--%s--%s', $boundary, static::$LE);
3133
3134
        return implode('', $mime);
3135
    }
3136
3137
    /**
3138
     * Encode a file attachment in requested format.
3139
     * Returns an empty string on failure.
3140
     *
3141
     * @param string $path     The full path to the file
3142
     * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
3143
     *
3144
     * @return string
3145
     */
3146
    protected function encodeFile($path, $encoding = self::ENCODING_BASE64)
3147
    {
3148
        try {
3149
            if (!static::isPermittedPath($path) || !file_exists($path)) {
3150
                throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
3151
            }
3152
            $file_buffer = file_get_contents($path);
3153
            if (false === $file_buffer) {
3154
                throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
3155
            }
3156
            $file_buffer = $this->encodeString($file_buffer, $encoding);
3157
3158
            return $file_buffer;
3159
        } catch (Exception $exc) {
3160
            $this->setError($exc->getMessage());
3161
3162
            return '';
3163
        }
3164
    }
3165
3166
    /**
3167
     * Encode a string in requested format.
3168
     * Returns an empty string on failure.
3169
     *
3170
     * @param string $str      The text to encode
3171
     * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
3172
     *
3173
     * @throws Exception
3174
     *
3175
     * @return string
3176
     */
3177
    public function encodeString($str, $encoding = self::ENCODING_BASE64)
3178
    {
3179
        $encoded = '';
3180
        switch (strtolower($encoding)) {
3181
            case static::ENCODING_BASE64:
3182
                $encoded = chunk_split(
3183
                    base64_encode($str),
3184
                    static::STD_LINE_LENGTH,
3185
                    static::$LE
3186
                );
3187
                break;
3188
            case static::ENCODING_7BIT:
3189
            case static::ENCODING_8BIT:
3190
                $encoded = static::normalizeBreaks($str);
3191
                // Make sure it ends with a line break
3192
                if (substr($encoded, -(strlen(static::$LE))) !== static::$LE) {
3193
                    $encoded .= static::$LE;
3194
                }
3195
                break;
3196
            case static::ENCODING_BINARY:
3197
                $encoded = $str;
3198
                break;
3199
            case static::ENCODING_QUOTED_PRINTABLE:
3200
                $encoded = $this->encodeQP($str);
3201
                break;
3202
            default:
3203
                $this->setError($this->lang('encoding') . $encoding);
3204
                if ($this->exceptions) {
3205
                    throw new Exception($this->lang('encoding') . $encoding);
3206
                }
3207
                break;
3208
        }
3209
3210
        return $encoded;
3211
    }
3212
3213
    /**
3214
     * Encode a header value (not including its label) optimally.
3215
     * Picks shortest of Q, B, or none. Result includes folding if needed.
3216
     * See RFC822 definitions for phrase, comment and text positions.
3217
     *
3218
     * @param string $str      The header value to encode
3219
     * @param string $position What context the string will be used in
3220
     *
3221
     * @return string
3222
     */
3223
    public function encodeHeader($str, $position = 'text')
3224
    {
3225
        $matchcount = 0;
3226
        switch (strtolower($position)) {
3227
            case 'phrase':
3228
                if (!preg_match('/[\200-\377]/', $str)) {
3229
                    // Can't use addslashes as we don't know the value of magic_quotes_sybase
3230
                    $encoded = addcslashes($str, "\0..\37\177\\\"");
3231
                    if (($str === $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
3232
                        return $encoded;
3233
                    }
3234
3235
                    return "\"$encoded\"";
3236
                }
3237
                $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
3238
                break;
3239
            /* @noinspection PhpMissingBreakStatementInspection */
3240
            case 'comment':
3241
                $matchcount = preg_match_all('/[()"]/', $str, $matches);
3242
            //fallthrough
3243
            case 'text':
3244
            default:
3245
                $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
3246
                break;
3247
        }
3248
3249
        if ($this->has8bitChars($str)) {
3250
            $charset = $this->CharSet;
3251
        } else {
3252
            $charset = static::CHARSET_ASCII;
3253
        }
3254
3255
        // Q/B encoding adds 8 chars and the charset ("` =?<charset>?[QB]?<content>?=`").
3256
        $overhead = 8 + strlen($charset);
3257
3258
        if ('mail' === $this->Mailer) {
3259
            $maxlen = static::MAIL_MAX_LINE_LENGTH - $overhead;
3260
        } else {
3261
            $maxlen = static::MAX_LINE_LENGTH - $overhead;
3262
        }
3263
3264
        // Select the encoding that produces the shortest output and/or prevents corruption.
3265
        if ($matchcount > strlen($str) / 3) {
3266
            // More than 1/3 of the content needs encoding, use B-encode.
3267
            $encoding = 'B';
3268
        } elseif ($matchcount > 0) {
3269
            // Less than 1/3 of the content needs encoding, use Q-encode.
3270
            $encoding = 'Q';
3271
        } elseif (strlen($str) > $maxlen) {
3272
            // No encoding needed, but value exceeds max line length, use Q-encode to prevent corruption.
3273
            $encoding = 'Q';
3274
        } else {
3275
            // No reformatting needed
3276
            $encoding = false;
3277
        }
3278
3279
        switch ($encoding) {
3280
            case 'B':
3281
                if ($this->hasMultiBytes($str)) {
3282
                    // Use a custom function which correctly encodes and wraps long
3283
                    // multibyte strings without breaking lines within a character
3284
                    $encoded = $this->base64EncodeWrapMB($str, "\n");
3285
                } else {
3286
                    $encoded = base64_encode($str);
3287
                    $maxlen -= $maxlen % 4;
3288
                    $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
3289
                }
3290
                $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded);
3291
                break;
3292
            case 'Q':
3293
                $encoded = $this->encodeQ($str, $position);
3294
                $encoded = $this->wrapText($encoded, $maxlen, true);
3295
                $encoded = str_replace('=' . static::$LE, "\n", trim($encoded));
3296
                $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded);
3297
                break;
3298
            default:
3299
                return $str;
3300
        }
3301
3302
        return trim(static::normalizeBreaks($encoded));
3303
    }
3304
3305
    /**
3306
     * Check if a string contains multi-byte characters.
3307
     *
3308
     * @param string $str multi-byte text to wrap encode
3309
     *
3310
     * @return bool
3311
     */
3312
    public function hasMultiBytes($str)
3313
    {
3314
        if (function_exists('mb_strlen')) {
3315
            return strlen($str) > mb_strlen($str, $this->CharSet);
3316
        }
3317
3318
        // Assume no multibytes (we can't handle without mbstring functions anyway)
3319
        return false;
3320
    }
3321
3322
    /**
3323
     * Does a string contain any 8-bit chars (in any charset)?
3324
     *
3325
     * @param string $text
3326
     *
3327
     * @return bool
3328
     */
3329
    public function has8bitChars($text)
3330
    {
3331
        return (bool) preg_match('/[\x80-\xFF]/', $text);
3332
    }
3333
3334
    /**
3335
     * Encode and wrap long multibyte strings for mail headers
3336
     * without breaking lines within a character.
3337
     * Adapted from a function by paravoid.
3338
     *
3339
     * @see http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
3340
     *
3341
     * @param string $str       multi-byte text to wrap encode
3342
     * @param string $linebreak string to use as linefeed/end-of-line
3343
     *
3344
     * @return string
3345
     */
3346
    public function base64EncodeWrapMB($str, $linebreak = null)
3347
    {
3348
        $start = '=?' . $this->CharSet . '?B?';
3349
        $end = '?=';
3350
        $encoded = '';
3351
        if (null === $linebreak) {
3352
            $linebreak = static::$LE;
3353
        }
3354
3355
        $mb_length = mb_strlen($str, $this->CharSet);
3356
        // Each line must have length <= 75, including $start and $end
3357
        $length = 75 - strlen($start) - strlen($end);
3358
        // Average multi-byte ratio
3359
        $ratio = $mb_length / strlen($str);
3360
        // Base64 has a 4:3 ratio
3361
        $avgLength = floor($length * $ratio * .75);
3362
3363
        $offset = 0;
0 ignored issues
show
Unused Code introduced by
$offset is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3364
        for ($i = 0; $i < $mb_length; $i += $offset) {
3365
            $lookBack = 0;
3366
            do {
3367
                $offset = $avgLength - $lookBack;
3368
                $chunk = mb_substr($str, $i, $offset, $this->CharSet);
3369
                $chunk = base64_encode($chunk);
3370
                ++$lookBack;
3371
            } while (strlen($chunk) > $length);
3372
            $encoded .= $chunk . $linebreak;
3373
        }
3374
3375
        // Chomp the last linefeed
3376
        return substr($encoded, 0, -strlen($linebreak));
3377
    }
3378
3379
    /**
3380
     * Encode a string in quoted-printable format.
3381
     * According to RFC2045 section 6.7.
3382
     *
3383
     * @param string $string The text to encode
3384
     *
3385
     * @return string
3386
     */
3387
    public function encodeQP($string)
3388
    {
3389
        return static::normalizeBreaks(quoted_printable_encode($string));
3390
    }
3391
3392
    /**
3393
     * Encode a string using Q encoding.
3394
     *
3395
     * @see http://tools.ietf.org/html/rfc2047#section-4.2
3396
     *
3397
     * @param string $str      the text to encode
3398
     * @param string $position Where the text is going to be used, see the RFC for what that means
3399
     *
3400
     * @return string
3401
     */
3402
    public function encodeQ($str, $position = 'text')
3403
    {
3404
        // There should not be any EOL in the string
3405
        $pattern = '';
3406
        $encoded = str_replace(["\r", "\n"], '', $str);
3407
        switch (strtolower($position)) {
3408
            case 'phrase':
3409
                // RFC 2047 section 5.3
3410
                $pattern = '^A-Za-z0-9!*+\/ -';
3411
                break;
3412
            /*
3413
             * RFC 2047 section 5.2.
3414
             * Build $pattern without including delimiters and []
3415
             */
3416
            /* @noinspection PhpMissingBreakStatementInspection */
3417
            case 'comment':
3418
                $pattern = '\(\)"';
3419
            /* Intentional fall through */
3420
            case 'text':
3421
            default:
3422
                // RFC 2047 section 5.1
3423
                // Replace every high ascii, control, =, ? and _ characters
3424
                $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
3425
                break;
3426
        }
3427
        $matches = [];
3428
        if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
3429
            // If the string contains an '=', make sure it's the first thing we replace
3430
            // so as to avoid double-encoding
3431
            $eqkey = array_search('=', $matches[0], true);
3432
            if (false !== $eqkey) {
3433
                unset($matches[0][$eqkey]);
3434
                array_unshift($matches[0], '=');
3435
            }
3436
            foreach (array_unique($matches[0]) as $char) {
3437
                $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
3438
            }
3439
        }
3440
        // Replace spaces with _ (more readable than =20)
3441
        // RFC 2047 section 4.2(2)
3442
        return str_replace(' ', '_', $encoded);
3443
    }
3444
3445
    /**
3446
     * Add a string or binary attachment (non-filesystem).
3447
     * This method can be used to attach ascii or binary data,
3448
     * such as a BLOB record from a database.
3449
     *
3450
     * @param string $string      String attachment data
3451
     * @param string $filename    Name of the attachment
3452
     * @param string $encoding    File encoding (see $Encoding)
3453
     * @param string $type        File extension (MIME) type
3454
     * @param string $disposition Disposition to use
3455
     *
3456
     * @throws Exception
3457
     *
3458
     * @return bool True on successfully adding an attachment
3459
     */
3460
    public function addStringAttachment(
3461
        $string,
3462
        $filename,
3463
        $encoding = self::ENCODING_BASE64,
3464
        $type = '',
3465
        $disposition = 'attachment'
3466
    ) {
3467
        try {
3468
            // If a MIME type is not specified, try to work it out from the file name
3469
            if ('' === $type) {
3470
                $type = static::filenameToType($filename);
3471
            }
3472
3473
            if (!$this->validateEncoding($encoding)) {
3474
                throw new Exception($this->lang('encoding') . $encoding);
3475
            }
3476
3477
            // Append to $attachment array
3478
            $this->attachment[] = [
3479
                0 => $string,
3480
                1 => $filename,
3481
                2 => static::mb_pathinfo($filename, PATHINFO_BASENAME),
3482
                3 => $encoding,
3483
                4 => $type,
3484
                5 => true, // isStringAttachment
3485
                6 => $disposition,
3486
                7 => 0,
3487
            ];
3488
        } catch (Exception $exc) {
3489
            $this->setError($exc->getMessage());
3490
            $this->edebug($exc->getMessage());
3491
            if ($this->exceptions) {
3492
                throw $exc;
3493
            }
3494
3495
            return false;
3496
        }
3497
3498
        return true;
3499
    }
3500
3501
    /**
3502
     * Add an embedded (inline) attachment from a file.
3503
     * This can include images, sounds, and just about any other document type.
3504
     * These differ from 'regular' attachments in that they are intended to be
3505
     * displayed inline with the message, not just attached for download.
3506
     * This is used in HTML messages that embed the images
3507
     * the HTML refers to using the $cid value.
3508
     * Never use a user-supplied path to a file!
3509
     *
3510
     * @param string $path        Path to the attachment
3511
     * @param string $cid         Content ID of the attachment; Use this to reference
3512
     *                            the content when using an embedded image in HTML
3513
     * @param string $name        Overrides the attachment name
3514
     * @param string $encoding    File encoding (see $Encoding)
3515
     * @param string $type        File MIME type
3516
     * @param string $disposition Disposition to use
3517
     *
3518
     * @throws Exception
3519
     *
3520
     * @return bool True on successfully adding an attachment
3521
     */
3522
    public function addEmbeddedImage(
3523
        $path,
3524
        $cid,
3525
        $name = '',
3526
        $encoding = self::ENCODING_BASE64,
3527
        $type = '',
3528
        $disposition = 'inline'
3529
    ) {
3530
        try {
3531
            if (!static::isPermittedPath($path) || !@is_file($path)) {
3532
                throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
3533
            }
3534
3535
            // If a MIME type is not specified, try to work it out from the file name
3536
            if ('' === $type) {
3537
                $type = static::filenameToType($path);
3538
            }
3539
3540
            if (!$this->validateEncoding($encoding)) {
3541
                throw new Exception($this->lang('encoding') . $encoding);
3542
            }
3543
3544
            $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME);
3545
            if ('' === $name) {
3546
                $name = $filename;
3547
            }
3548
3549
            // Append to $attachment array
3550
            $this->attachment[] = [
3551
                0 => $path,
3552
                1 => $filename,
3553
                2 => $name,
3554
                3 => $encoding,
3555
                4 => $type,
3556
                5 => false, // isStringAttachment
3557
                6 => $disposition,
3558
                7 => $cid,
3559
            ];
3560
        } catch (Exception $exc) {
3561
            $this->setError($exc->getMessage());
3562
            $this->edebug($exc->getMessage());
3563
            if ($this->exceptions) {
3564
                throw $exc;
3565
            }
3566
3567
            return false;
3568
        }
3569
3570
        return true;
3571
    }
3572
3573
    /**
3574
     * Add an embedded stringified attachment.
3575
     * This can include images, sounds, and just about any other document type.
3576
     * If your filename doesn't contain an extension, be sure to set the $type to an appropriate MIME type.
3577
     *
3578
     * @param string $string      The attachment binary data
3579
     * @param string $cid         Content ID of the attachment; Use this to reference
3580
     *                            the content when using an embedded image in HTML
3581
     * @param string $name        A filename for the attachment. If this contains an extension,
3582
     *                            PHPMailer will attempt to set a MIME type for the attachment.
3583
     *                            For example 'file.jpg' would get an 'image/jpeg' MIME type.
3584
     * @param string $encoding    File encoding (see $Encoding), defaults to 'base64'
3585
     * @param string $type        MIME type - will be used in preference to any automatically derived type
3586
     * @param string $disposition Disposition to use
3587
     *
3588
     * @throws Exception
3589
     *
3590
     * @return bool True on successfully adding an attachment
3591
     */
3592
    public function addStringEmbeddedImage(
3593
        $string,
3594
        $cid,
3595
        $name = '',
3596
        $encoding = self::ENCODING_BASE64,
3597
        $type = '',
3598
        $disposition = 'inline'
3599
    ) {
3600
        try {
3601
            // If a MIME type is not specified, try to work it out from the name
3602
            if ('' === $type && !empty($name)) {
3603
                $type = static::filenameToType($name);
3604
            }
3605
3606
            if (!$this->validateEncoding($encoding)) {
3607
                throw new Exception($this->lang('encoding') . $encoding);
3608
            }
3609
3610
            // Append to $attachment array
3611
            $this->attachment[] = [
3612
                0 => $string,
3613
                1 => $name,
3614
                2 => $name,
3615
                3 => $encoding,
3616
                4 => $type,
3617
                5 => true, // isStringAttachment
3618
                6 => $disposition,
3619
                7 => $cid,
3620
            ];
3621
        } catch (Exception $exc) {
3622
            $this->setError($exc->getMessage());
3623
            $this->edebug($exc->getMessage());
3624
            if ($this->exceptions) {
3625
                throw $exc;
3626
            }
3627
3628
            return false;
3629
        }
3630
3631
        return true;
3632
    }
3633
3634
    /**
3635
     * Validate encodings.
3636
     *
3637
     * @param string $encoding
3638
     *
3639
     * @return bool
3640
     */
3641
    protected function validateEncoding($encoding)
3642
    {
3643
        return in_array(
3644
            $encoding,
3645
            [
3646
                self::ENCODING_7BIT,
3647
                self::ENCODING_QUOTED_PRINTABLE,
3648
                self::ENCODING_BASE64,
3649
                self::ENCODING_8BIT,
3650
                self::ENCODING_BINARY,
3651
            ],
3652
            true
3653
        );
3654
    }
3655
3656
    /**
3657
     * Check if an embedded attachment is present with this cid.
3658
     *
3659
     * @param string $cid
3660
     *
3661
     * @return bool
3662
     */
3663
    protected function cidExists($cid)
3664
    {
3665
        foreach ($this->attachment as $attachment) {
3666
            if ('inline' === $attachment[6] && $cid === $attachment[7]) {
3667
                return true;
3668
            }
3669
        }
3670
3671
        return false;
3672
    }
3673
3674
    /**
3675
     * Check if an inline attachment is present.
3676
     *
3677
     * @return bool
3678
     */
3679
    public function inlineImageExists()
3680
    {
3681
        foreach ($this->attachment as $attachment) {
3682
            if ('inline' === $attachment[6]) {
3683
                return true;
3684
            }
3685
        }
3686
3687
        return false;
3688
    }
3689
3690
    /**
3691
     * Check if an attachment (non-inline) is present.
3692
     *
3693
     * @return bool
3694
     */
3695
    public function attachmentExists()
3696
    {
3697
        foreach ($this->attachment as $attachment) {
3698
            if ('attachment' === $attachment[6]) {
3699
                return true;
3700
            }
3701
        }
3702
3703
        return false;
3704
    }
3705
3706
    /**
3707
     * Check if this message has an alternative body set.
3708
     *
3709
     * @return bool
3710
     */
3711
    public function alternativeExists()
3712
    {
3713
        return !empty($this->AltBody);
3714
    }
3715
3716
    /**
3717
     * Clear queued addresses of given kind.
3718
     *
3719
     * @param string $kind 'to', 'cc', or 'bcc'
3720
     */
3721
    public function clearQueuedAddresses($kind)
3722
    {
3723
        $this->RecipientsQueue = array_filter(
3724
            $this->RecipientsQueue,
3725
            static function ($params) use ($kind) {
3726
                return $params[0] !== $kind;
3727
            }
3728
        );
3729
    }
3730
3731
    /**
3732
     * Clear all To recipients.
3733
     */
3734
    public function clearAddresses()
3735
    {
3736
        foreach ($this->to as $to) {
3737
            unset($this->all_recipients[strtolower($to[0])]);
3738
        }
3739
        $this->to = [];
3740
        $this->clearQueuedAddresses('to');
3741
    }
3742
3743
    /**
3744
     * Clear all CC recipients.
3745
     */
3746
    public function clearCCs()
3747
    {
3748
        foreach ($this->cc as $cc) {
3749
            unset($this->all_recipients[strtolower($cc[0])]);
3750
        }
3751
        $this->cc = [];
3752
        $this->clearQueuedAddresses('cc');
3753
    }
3754
3755
    /**
3756
     * Clear all BCC recipients.
3757
     */
3758
    public function clearBCCs()
3759
    {
3760
        foreach ($this->bcc as $bcc) {
3761
            unset($this->all_recipients[strtolower($bcc[0])]);
3762
        }
3763
        $this->bcc = [];
3764
        $this->clearQueuedAddresses('bcc');
3765
    }
3766
3767
    /**
3768
     * Clear all ReplyTo recipients.
3769
     */
3770
    public function clearReplyTos()
3771
    {
3772
        $this->ReplyTo = [];
3773
        $this->ReplyToQueue = [];
3774
    }
3775
3776
    /**
3777
     * Clear all recipient types.
3778
     */
3779
    public function clearAllRecipients()
3780
    {
3781
        $this->to = [];
3782
        $this->cc = [];
3783
        $this->bcc = [];
3784
        $this->all_recipients = [];
3785
        $this->RecipientsQueue = [];
3786
    }
3787
3788
    /**
3789
     * Clear all filesystem, string, and binary attachments.
3790
     */
3791
    public function clearAttachments()
3792
    {
3793
        $this->attachment = [];
3794
    }
3795
3796
    /**
3797
     * Clear all custom headers.
3798
     */
3799
    public function clearCustomHeaders()
3800
    {
3801
        $this->CustomHeader = [];
3802
    }
3803
3804
    /**
3805
     * Add an error message to the error container.
3806
     *
3807
     * @param string $msg
3808
     */
3809
    protected function setError($msg)
3810
    {
3811
        ++$this->error_count;
3812
        if ('smtp' === $this->Mailer && null !== $this->smtp) {
3813
            $lasterror = $this->smtp->getError();
3814
            if (!empty($lasterror['error'])) {
3815
                $msg .= $this->lang('smtp_error') . $lasterror['error'];
3816
                if (!empty($lasterror['detail'])) {
3817
                    $msg .= ' Detail: ' . $lasterror['detail'];
3818
                }
3819
                if (!empty($lasterror['smtp_code'])) {
3820
                    $msg .= ' SMTP code: ' . $lasterror['smtp_code'];
3821
                }
3822
                if (!empty($lasterror['smtp_code_ex'])) {
3823
                    $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex'];
3824
                }
3825
            }
3826
        }
3827
        $this->ErrorInfo = $msg;
3828
    }
3829
3830
    /**
3831
     * Return an RFC 822 formatted date.
3832
     *
3833
     * @return string
3834
     */
3835
    public static function rfcDate()
3836
    {
3837
        // Set the time zone to whatever the default is to avoid 500 errors
3838
        // Will default to UTC if it's not set properly in php.ini
3839
        date_default_timezone_set(@date_default_timezone_get());
3840
3841
        return date('D, j M Y H:i:s O');
3842
    }
3843
3844
    /**
3845
     * Get the server hostname.
3846
     * Returns 'localhost.localdomain' if unknown.
3847
     *
3848
     * @return string
3849
     */
3850
    protected function serverHostname()
3851
    {
3852
        $result = '';
3853
        if (!empty($this->Hostname)) {
3854
            $result = $this->Hostname;
3855
        } elseif (isset($_SERVER) && array_key_exists('SERVER_NAME', $_SERVER)) {
3856
            $result = $_SERVER['SERVER_NAME'];
3857
        } elseif (function_exists('gethostname') && gethostname() !== false) {
3858
            $result = gethostname();
3859
        } elseif (php_uname('n') !== false) {
3860
            $result = php_uname('n');
3861
        }
3862
        if (!static::isValidHost($result)) {
3863
            return 'localhost.localdomain';
3864
        }
3865
3866
        return $result;
3867
    }
3868
3869
    /**
3870
     * Validate whether a string contains a valid value to use as a hostname or IP address.
3871
     * IPv6 addresses must include [], e.g. `[::1]`, not just `::1`.
3872
     *
3873
     * @param string $host The host name or IP address to check
3874
     *
3875
     * @return bool
3876
     */
3877
    public static function isValidHost($host)
3878
    {
3879
        //Simple syntax limits
3880
        if (empty($host)
3881
            || !is_string($host)
3882
            || strlen($host) > 256
3883
            || !preg_match('/^([a-zA-Z\d.-]*|\[[a-fA-F\d:]+])$/', $host)
3884
        ) {
3885
            return false;
3886
        }
3887
        //Looks like a bracketed IPv6 address
3888
        if (strlen($host) > 2 && substr($host, 0, 1) === '[' && substr($host, -1, 1) === ']') {
3889
            return filter_var(substr($host, 1, -1), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
3890
        }
3891
        //If removing all the dots results in a numeric string, it must be an IPv4 address.
3892
        //Need to check this first because otherwise things like `999.0.0.0` are considered valid host names
3893
        if (is_numeric(str_replace('.', '', $host))) {
3894
            //Is it a valid IPv4 address?
3895
            return filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
3896
        }
3897
        if (filter_var('http://' . $host, FILTER_VALIDATE_URL) !== false) {
3898
            //Is it a syntactically valid hostname?
3899
            return true;
3900
        }
3901
3902
        return false;
3903
    }
3904
3905
    /**
3906
     * Get an error message in the current language.
3907
     *
3908
     * @param string $key
3909
     *
3910
     * @return string
3911
     */
3912
    protected function lang($key)
3913
    {
3914
        if (count($this->language) < 1) {
3915
            $this->setLanguage(); // set the default language
3916
        }
3917
3918
        if (array_key_exists($key, $this->language)) {
3919
            if ('smtp_connect_failed' === $key) {
3920
                //Include a link to troubleshooting docs on SMTP connection failure
3921
                //this is by far the biggest cause of support questions
3922
                //but it's usually not PHPMailer's fault.
3923
                return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
3924
            }
3925
3926
            return $this->language[$key];
3927
        }
3928
3929
        //Return the key as a fallback
3930
        return $key;
3931
    }
3932
3933
    /**
3934
     * Check if an error occurred.
3935
     *
3936
     * @return bool True if an error did occur
3937
     */
3938
    public function isError()
3939
    {
3940
        return $this->error_count > 0;
3941
    }
3942
3943
    /**
3944
     * Add a custom header.
3945
     * $name value can be overloaded to contain
3946
     * both header name and value (name:value).
3947
     *
3948
     * @param string      $name  Custom header name
3949
     * @param string|null $value Header value
3950
     */
3951
    public function addCustomHeader($name, $value = null)
3952
    {
3953
        if (null === $value) {
3954
            // Value passed in as name:value
3955
            $this->CustomHeader[] = explode(':', $name, 2);
3956
        } else {
3957
            $this->CustomHeader[] = [$name, $value];
3958
        }
3959
    }
3960
3961
    /**
3962
     * Returns all custom headers.
3963
     *
3964
     * @return array
3965
     */
3966
    public function getCustomHeaders()
3967
    {
3968
        return $this->CustomHeader;
3969
    }
3970
3971
    /**
3972
     * Create a message body from an HTML string.
3973
     * Automatically inlines images and creates a plain-text version by converting the HTML,
3974
     * overwriting any existing values in Body and AltBody.
3975
     * Do not source $message content from user input!
3976
     * $basedir is prepended when handling relative URLs, e.g. <img src="/images/a.png"> and must not be empty
3977
     * will look for an image file in $basedir/images/a.png and convert it to inline.
3978
     * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email)
3979
     * Converts data-uri images into embedded attachments.
3980
     * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly.
3981
     *
3982
     * @param string        $message  HTML message string
3983
     * @param string        $basedir  Absolute path to a base directory to prepend to relative paths to images
3984
     * @param bool|callable $advanced Whether to use the internal HTML to text converter
3985
     *                                or your own custom converter @return string $message The transformed message Body
3986
     *
3987
     * @throws Exception
3988
     *
3989
     * @see PHPMailer::html2text()
3990
     */
3991
    public function msgHTML($message, $basedir = '', $advanced = false)
3992
    {
3993
        preg_match_all('/(?<!-)(src|background)=["\'](.*)["\']/Ui', $message, $images);
3994
        if (array_key_exists(2, $images)) {
3995
            if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {
3996
                // Ensure $basedir has a trailing /
3997
                $basedir .= '/';
3998
            }
3999
            foreach ($images[2] as $imgindex => $url) {
4000
                // Convert data URIs into embedded images
4001
                //e.g. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
4002
                $match = [];
4003
                if (preg_match('#^data:(image/(?:jpe?g|gif|png));?(base64)?,(.+)#', $url, $match)) {
4004
                    if (count($match) === 4 && static::ENCODING_BASE64 === $match[2]) {
4005
                        $data = base64_decode($match[3]);
4006
                    } elseif ('' === $match[2]) {
4007
                        $data = rawurldecode($match[3]);
4008
                    } else {
4009
                        //Not recognised so leave it alone
4010
                        continue;
4011
                    }
4012
                    //Hash the decoded data, not the URL, so that the same data-URI image used in multiple places
4013
                    //will only be embedded once, even if it used a different encoding
4014
                    $cid = substr(hash('sha256', $data), 0, 32) . '@phpmailer.0'; // RFC2392 S 2
4015
4016
                    if (!$this->cidExists($cid)) {
4017
                        $this->addStringEmbeddedImage(
4018
                            $data,
4019
                            $cid,
4020
                            'embed' . $imgindex,
4021
                            static::ENCODING_BASE64,
4022
                            $match[1]
4023
                        );
4024
                    }
4025
                    $message = str_replace(
4026
                        $images[0][$imgindex],
4027
                        $images[1][$imgindex] . '="cid:' . $cid . '"',
4028
                        $message
4029
                    );
4030
                    continue;
4031
                }
4032
                if (// Only process relative URLs if a basedir is provided (i.e. no absolute local paths)
4033
                    !empty($basedir)
4034
                    // Ignore URLs containing parent dir traversal (..)
4035
                    && (strpos($url, '..') === false)
4036
                    // Do not change urls that are already inline images
4037
                    && 0 !== strpos($url, 'cid:')
4038
                    // Do not change absolute URLs, including anonymous protocol
4039
                    && !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url)
4040
                ) {
4041
                    $filename = static::mb_pathinfo($url, PATHINFO_BASENAME);
4042
                    $directory = dirname($url);
4043
                    if ('.' === $directory) {
4044
                        $directory = '';
4045
                    }
4046
                    // RFC2392 S 2
4047
                    $cid = substr(hash('sha256', $url), 0, 32) . '@phpmailer.0';
4048
                    if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {
4049
                        $basedir .= '/';
4050
                    }
4051
                    if (strlen($directory) > 1 && '/' !== substr($directory, -1)) {
4052
                        $directory .= '/';
4053
                    }
4054
                    if ($this->addEmbeddedImage(
4055
                        $basedir . $directory . $filename,
4056
                        $cid,
4057
                        $filename,
0 ignored issues
show
Bug introduced by
It seems like $filename defined by static::mb_pathinfo($url, PATHINFO_BASENAME) on line 4041 can also be of type array<string,string>; however, PHPMailer\PHPMailer\PHPMailer::addEmbeddedImage() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
4058
                        static::ENCODING_BASE64,
4059
                        static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION))
0 ignored issues
show
Bug introduced by
It seems like $filename defined by static::mb_pathinfo($url, PATHINFO_BASENAME) on line 4041 can also be of type array<string,string>; however, PHPMailer\PHPMailer\PHPMailer::mb_pathinfo() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
4060
                    )
4061
                    ) {
4062
                        $message = preg_replace(
4063
                            '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
4064
                            $images[1][$imgindex] . '="cid:' . $cid . '"',
4065
                            $message
4066
                        );
4067
                    }
4068
                }
4069
            }
4070
        }
4071
        $this->isHTML();
4072
        // Convert all message body line breaks to LE, makes quoted-printable encoding work much better
4073
        $this->Body = static::normalizeBreaks($message);
4074
        $this->AltBody = static::normalizeBreaks($this->html2text($message, $advanced));
4075
        if (!$this->alternativeExists()) {
4076
            $this->AltBody = 'This is an HTML-only message. To view it, activate HTML in your email application.'
4077
                . static::$LE;
4078
        }
4079
4080
        return $this->Body;
4081
    }
4082
4083
    /**
4084
     * Convert an HTML string into plain text.
4085
     * This is used by msgHTML().
4086
     * Note - older versions of this function used a bundled advanced converter
4087
     * which was removed for license reasons in #232.
4088
     * Example usage:
4089
     *
4090
     * ```php
4091
     * // Use default conversion
4092
     * $plain = $mail->html2text($html);
4093
     * // Use your own custom converter
4094
     * $plain = $mail->html2text($html, function($html) {
4095
     *     $converter = new MyHtml2text($html);
4096
     *     return $converter->get_text();
4097
     * });
4098
     * ```
4099
     *
4100
     * @param string        $html     The HTML text to convert
4101
     * @param bool|callable $advanced Any boolean value to use the internal converter,
4102
     *                                or provide your own callable for custom conversion
4103
     *
4104
     * @return string
4105
     */
4106
    public function html2text($html, $advanced = false)
4107
    {
4108
        if (is_callable($advanced)) {
4109
            return $advanced($html);
4110
        }
4111
4112
        return html_entity_decode(
4113
            trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
4114
            ENT_QUOTES,
4115
            $this->CharSet
4116
        );
4117
    }
4118
4119
    /**
4120
     * Get the MIME type for a file extension.
4121
     *
4122
     * @param string $ext File extension
4123
     *
4124
     * @return string MIME type of file
4125
     */
4126
    public static function _mime_types($ext = '')
4127
    {
4128
        $mimes = [
4129
            'xl' => 'application/excel',
4130
            'js' => 'application/javascript',
4131
            'hqx' => 'application/mac-binhex40',
4132
            'cpt' => 'application/mac-compactpro',
4133
            'bin' => 'application/macbinary',
4134
            'doc' => 'application/msword',
4135
            'word' => 'application/msword',
4136
            'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
4137
            'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
4138
            'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
4139
            'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
4140
            'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
4141
            'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
4142
            'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
4143
            'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
4144
            'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
4145
            'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
4146
            'class' => 'application/octet-stream',
4147
            'dll' => 'application/octet-stream',
4148
            'dms' => 'application/octet-stream',
4149
            'exe' => 'application/octet-stream',
4150
            'lha' => 'application/octet-stream',
4151
            'lzh' => 'application/octet-stream',
4152
            'psd' => 'application/octet-stream',
4153
            'sea' => 'application/octet-stream',
4154
            'so' => 'application/octet-stream',
4155
            'oda' => 'application/oda',
4156
            'pdf' => 'application/pdf',
4157
            'ai' => 'application/postscript',
4158
            'eps' => 'application/postscript',
4159
            'ps' => 'application/postscript',
4160
            'smi' => 'application/smil',
4161
            'smil' => 'application/smil',
4162
            'mif' => 'application/vnd.mif',
4163
            'xls' => 'application/vnd.ms-excel',
4164
            'ppt' => 'application/vnd.ms-powerpoint',
4165
            'wbxml' => 'application/vnd.wap.wbxml',
4166
            'wmlc' => 'application/vnd.wap.wmlc',
4167
            'dcr' => 'application/x-director',
4168
            'dir' => 'application/x-director',
4169
            'dxr' => 'application/x-director',
4170
            'dvi' => 'application/x-dvi',
4171
            'gtar' => 'application/x-gtar',
4172
            'php3' => 'application/x-httpd-php',
4173
            'php4' => 'application/x-httpd-php',
4174
            'php' => 'application/x-httpd-php',
4175
            'phtml' => 'application/x-httpd-php',
4176
            'phps' => 'application/x-httpd-php-source',
4177
            'swf' => 'application/x-shockwave-flash',
4178
            'sit' => 'application/x-stuffit',
4179
            'tar' => 'application/x-tar',
4180
            'tgz' => 'application/x-tar',
4181
            'xht' => 'application/xhtml+xml',
4182
            'xhtml' => 'application/xhtml+xml',
4183
            'zip' => 'application/zip',
4184
            'mid' => 'audio/midi',
4185
            'midi' => 'audio/midi',
4186
            'mp2' => 'audio/mpeg',
4187
            'mp3' => 'audio/mpeg',
4188
            'm4a' => 'audio/mp4',
4189
            'mpga' => 'audio/mpeg',
4190
            'aif' => 'audio/x-aiff',
4191
            'aifc' => 'audio/x-aiff',
4192
            'aiff' => 'audio/x-aiff',
4193
            'ram' => 'audio/x-pn-realaudio',
4194
            'rm' => 'audio/x-pn-realaudio',
4195
            'rpm' => 'audio/x-pn-realaudio-plugin',
4196
            'ra' => 'audio/x-realaudio',
4197
            'wav' => 'audio/x-wav',
4198
            'mka' => 'audio/x-matroska',
4199
            'bmp' => 'image/bmp',
4200
            'gif' => 'image/gif',
4201
            'jpeg' => 'image/jpeg',
4202
            'jpe' => 'image/jpeg',
4203
            'jpg' => 'image/jpeg',
4204
            'png' => 'image/png',
4205
            'tiff' => 'image/tiff',
4206
            'tif' => 'image/tiff',
4207
            'webp' => 'image/webp',
4208
            'heif' => 'image/heif',
4209
            'heifs' => 'image/heif-sequence',
4210
            'heic' => 'image/heic',
4211
            'heics' => 'image/heic-sequence',
4212
            'eml' => 'message/rfc822',
4213
            'css' => 'text/css',
4214
            'html' => 'text/html',
4215
            'htm' => 'text/html',
4216
            'shtml' => 'text/html',
4217
            'log' => 'text/plain',
4218
            'text' => 'text/plain',
4219
            'txt' => 'text/plain',
4220
            'rtx' => 'text/richtext',
4221
            'rtf' => 'text/rtf',
4222
            'vcf' => 'text/vcard',
4223
            'vcard' => 'text/vcard',
4224
            'ics' => 'text/calendar',
4225
            'xml' => 'text/xml',
4226
            'xsl' => 'text/xml',
4227
            'wmv' => 'video/x-ms-wmv',
4228
            'mpeg' => 'video/mpeg',
4229
            'mpe' => 'video/mpeg',
4230
            'mpg' => 'video/mpeg',
4231
            'mp4' => 'video/mp4',
4232
            'm4v' => 'video/mp4',
4233
            'mov' => 'video/quicktime',
4234
            'qt' => 'video/quicktime',
4235
            'rv' => 'video/vnd.rn-realvideo',
4236
            'avi' => 'video/x-msvideo',
4237
            'movie' => 'video/x-sgi-movie',
4238
            'webm' => 'video/webm',
4239
            'mkv' => 'video/x-matroska',
4240
        ];
4241
        $ext = strtolower($ext);
4242
        if (array_key_exists($ext, $mimes)) {
4243
            return $mimes[$ext];
4244
        }
4245
4246
        return 'application/octet-stream';
4247
    }
4248
4249
    /**
4250
     * Map a file name to a MIME type.
4251
     * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
4252
     *
4253
     * @param string $filename A file name or full path, does not need to exist as a file
4254
     *
4255
     * @return string
4256
     */
4257
    public static function filenameToType($filename)
4258
    {
4259
        // In case the path is a URL, strip any query string before getting extension
4260
        $qpos = strpos($filename, '?');
4261
        if (false !== $qpos) {
4262
            $filename = substr($filename, 0, $qpos);
4263
        }
4264
        $ext = static::mb_pathinfo($filename, PATHINFO_EXTENSION);
4265
4266
        return static::_mime_types($ext);
0 ignored issues
show
Bug introduced by
It seems like $ext defined by static::mb_pathinfo($filename, PATHINFO_EXTENSION) on line 4264 can also be of type array<string,string>; however, PHPMailer\PHPMailer\PHPMailer::_mime_types() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
4267
    }
4268
4269
    /**
4270
     * Multi-byte-safe pathinfo replacement.
4271
     * Drop-in replacement for pathinfo(), but multibyte- and cross-platform-safe.
4272
     *
4273
     * @see http://www.php.net/manual/en/function.pathinfo.php#107461
4274
     *
4275
     * @param string     $path    A filename or path, does not need to exist as a file
4276
     * @param int|string $options Either a PATHINFO_* constant,
4277
     *                            or a string name to return only the specified piece
4278
     *
4279
     * @return string|array
4280
     */
4281
    public static function mb_pathinfo($path, $options = null)
4282
    {
4283
        $ret = ['dirname' => '', 'basename' => '', 'extension' => '', 'filename' => ''];
4284
        $pathinfo = [];
4285
        if (preg_match('#^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^.\\\\/]+?)|))[\\\\/.]*$#m', $path, $pathinfo)) {
4286
            if (array_key_exists(1, $pathinfo)) {
4287
                $ret['dirname'] = $pathinfo[1];
4288
            }
4289
            if (array_key_exists(2, $pathinfo)) {
4290
                $ret['basename'] = $pathinfo[2];
4291
            }
4292
            if (array_key_exists(5, $pathinfo)) {
4293
                $ret['extension'] = $pathinfo[5];
4294
            }
4295
            if (array_key_exists(3, $pathinfo)) {
4296
                $ret['filename'] = $pathinfo[3];
4297
            }
4298
        }
4299
        switch ($options) {
4300
            case PATHINFO_DIRNAME:
4301
            case 'dirname':
4302
                return $ret['dirname'];
4303
            case PATHINFO_BASENAME:
4304
            case 'basename':
4305
                return $ret['basename'];
4306
            case PATHINFO_EXTENSION:
4307
            case 'extension':
4308
                return $ret['extension'];
4309
            case PATHINFO_FILENAME:
4310
            case 'filename':
4311
                return $ret['filename'];
4312
            default:
4313
                return $ret;
4314
        }
4315
    }
4316
4317
    /**
4318
     * Set or reset instance properties.
4319
     * You should avoid this function - it's more verbose, less efficient, more error-prone and
4320
     * harder to debug than setting properties directly.
4321
     * Usage Example:
4322
     * `$mail->set('SMTPSecure', static::ENCRYPTION_STARTTLS);`
4323
     *   is the same as:
4324
     * `$mail->SMTPSecure = static::ENCRYPTION_STARTTLS;`.
4325
     *
4326
     * @param string $name  The property name to set
4327
     * @param mixed  $value The value to set the property to
4328
     *
4329
     * @return bool
4330
     */
4331
    public function set($name, $value = '')
4332
    {
4333
        if (property_exists($this, $name)) {
4334
            $this->$name = $value;
4335
4336
            return true;
4337
        }
4338
        $this->setError($this->lang('variable_set') . $name);
4339
4340
        return false;
4341
    }
4342
4343
    /**
4344
     * Strip newlines to prevent header injection.
4345
     *
4346
     * @param string $str
4347
     *
4348
     * @return string
4349
     */
4350
    public function secureHeader($str)
4351
    {
4352
        return trim(str_replace(["\r", "\n"], '', $str));
4353
    }
4354
4355
    /**
4356
     * Normalize line breaks in a string.
4357
     * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
4358
     * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
4359
     *
4360
     * @param string $text
4361
     * @param string $breaktype What kind of line break to use; defaults to static::$LE
4362
     *
4363
     * @return string
4364
     */
4365
    public static function normalizeBreaks($text, $breaktype = null)
4366
    {
4367
        if (null === $breaktype) {
4368
            $breaktype = static::$LE;
4369
        }
4370
        // Normalise to \n
4371
        $text = str_replace([self::CRLF, "\r"], "\n", $text);
4372
        // Now convert LE as needed
4373
        if ("\n" !== $breaktype) {
4374
            $text = str_replace("\n", $breaktype, $text);
4375
        }
4376
4377
        return $text;
4378
    }
4379
4380
    /**
4381
     * Remove trailing breaks from a string.
4382
     *
4383
     * @param string $text
4384
     *
4385
     * @return string The text to remove breaks from
4386
     */
4387
    public static function stripTrailingWSP($text)
4388
    {
4389
        return rtrim($text, " \r\n\t");
4390
    }
4391
4392
    /**
4393
     * Return the current line break format string.
4394
     *
4395
     * @return string
4396
     */
4397
    public static function getLE()
4398
    {
4399
        return static::$LE;
4400
    }
4401
4402
    /**
4403
     * Set the line break format string, e.g. "\r\n".
4404
     *
4405
     * @param string $le
4406
     */
4407
    protected static function setLE($le)
4408
    {
4409
        static::$LE = $le;
4410
    }
4411
4412
    /**
4413
     * Set the public and private key files and password for S/MIME signing.
4414
     *
4415
     * @param string $cert_filename
4416
     * @param string $key_filename
4417
     * @param string $key_pass            Password for private key
4418
     * @param string $extracerts_filename Optional path to chain certificate
4419
     */
4420
    public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
4421
    {
4422
        $this->sign_cert_file = $cert_filename;
4423
        $this->sign_key_file = $key_filename;
4424
        $this->sign_key_pass = $key_pass;
4425
        $this->sign_extracerts_file = $extracerts_filename;
4426
    }
4427
4428
    /**
4429
     * Quoted-Printable-encode a DKIM header.
4430
     *
4431
     * @param string $txt
4432
     *
4433
     * @return string
4434
     */
4435
    public function DKIM_QP($txt)
4436
    {
4437
        $line = '';
4438
        $len = strlen($txt);
4439
        for ($i = 0; $i < $len; ++$i) {
4440
            $ord = ord($txt[$i]);
4441
            if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord === 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
4442
                $line .= $txt[$i];
4443
            } else {
4444
                $line .= '=' . sprintf('%02X', $ord);
4445
            }
4446
        }
4447
4448
        return $line;
4449
    }
4450
4451
    /**
4452
     * Generate a DKIM signature.
4453
     *
4454
     * @param string $signHeader
4455
     *
4456
     * @throws Exception
4457
     *
4458
     * @return string The DKIM signature value
4459
     */
4460
    public function DKIM_Sign($signHeader)
4461
    {
4462
        if (!defined('PKCS7_TEXT')) {
4463
            if ($this->exceptions) {
4464
                throw new Exception($this->lang('extension_missing') . 'openssl');
4465
            }
4466
4467
            return '';
4468
        }
4469
        $privKeyStr = !empty($this->DKIM_private_string) ?
4470
            $this->DKIM_private_string :
4471
            file_get_contents($this->DKIM_private);
4472
        if ('' !== $this->DKIM_passphrase) {
4473
            $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
4474
        } else {
4475
            $privKey = openssl_pkey_get_private($privKeyStr);
4476
        }
4477
        if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) {
4478
            openssl_pkey_free($privKey);
4479
4480
            return base64_encode($signature);
4481
        }
4482
        openssl_pkey_free($privKey);
4483
4484
        return '';
4485
    }
4486
4487
    /**
4488
     * Generate a DKIM canonicalization header.
4489
     * Uses the 'relaxed' algorithm from RFC6376 section 3.4.2.
4490
     * Canonicalized headers should *always* use CRLF, regardless of mailer setting.
4491
     *
4492
     * @see https://tools.ietf.org/html/rfc6376#section-3.4.2
4493
     *
4494
     * @param string $signHeader Header
4495
     *
4496
     * @return string
4497
     */
4498
    public function DKIM_HeaderC($signHeader)
4499
    {
4500
        //Normalize breaks to CRLF (regardless of the mailer)
4501
        $signHeader = static::normalizeBreaks($signHeader, self::CRLF);
4502
        //Unfold header lines
4503
        //Note PCRE \s is too broad a definition of whitespace; RFC5322 defines it as `[ \t]`
4504
        //@see https://tools.ietf.org/html/rfc5322#section-2.2
4505
        //That means this may break if you do something daft like put vertical tabs in your headers.
4506
        $signHeader = preg_replace('/\r\n[ \t]+/', ' ', $signHeader);
4507
        //Break headers out into an array
4508
        $lines = explode(self::CRLF, $signHeader);
4509
        foreach ($lines as $key => $line) {
4510
            //If the header is missing a :, skip it as it's invalid
4511
            //This is likely to happen because the explode() above will also split
4512
            //on the trailing LE, leaving an empty line
4513
            if (strpos($line, ':') === false) {
4514
                continue;
4515
            }
4516
            list($heading, $value) = explode(':', $line, 2);
4517
            //Lower-case header name
4518
            $heading = strtolower($heading);
4519
            //Collapse white space within the value, also convert WSP to space
4520
            $value = preg_replace('/[ \t]+/', ' ', $value);
4521
            //RFC6376 is slightly unclear here - it says to delete space at the *end* of each value
4522
            //But then says to delete space before and after the colon.
4523
            //Net result is the same as trimming both ends of the value.
4524
            //By elimination, the same applies to the field name
4525
            $lines[$key] = trim($heading, " \t") . ':' . trim($value, " \t");
4526
        }
4527
4528
        return implode(self::CRLF, $lines);
4529
    }
4530
4531
    /**
4532
     * Generate a DKIM canonicalization body.
4533
     * Uses the 'simple' algorithm from RFC6376 section 3.4.3.
4534
     * Canonicalized bodies should *always* use CRLF, regardless of mailer setting.
4535
     *
4536
     * @see https://tools.ietf.org/html/rfc6376#section-3.4.3
4537
     *
4538
     * @param string $body Message Body
4539
     *
4540
     * @return string
4541
     */
4542
    public function DKIM_BodyC($body)
4543
    {
4544
        if (empty($body)) {
4545
            return self::CRLF;
4546
        }
4547
        // Normalize line endings to CRLF
4548
        $body = static::normalizeBreaks($body, self::CRLF);
4549
4550
        //Reduce multiple trailing line breaks to a single one
4551
        return static::stripTrailingWSP($body) . self::CRLF;
4552
    }
4553
4554
    /**
4555
     * Create the DKIM header and body in a new message header.
4556
     *
4557
     * @param string $headers_line Header lines
4558
     * @param string $subject      Subject
4559
     * @param string $body         Body
4560
     *
4561
     * @throws Exception
4562
     *
4563
     * @return string
4564
     */
4565
    public function DKIM_Add($headers_line, $subject, $body)
4566
    {
4567
        $DKIMsignatureType = 'rsa-sha256'; // Signature & hash algorithms
4568
        $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization methods of header & body
4569
        $DKIMquery = 'dns/txt'; // Query method
4570
        $DKIMtime = time();
4571
        //Always sign these headers without being asked
4572
        //Recommended list from https://tools.ietf.org/html/rfc6376#section-5.4.1
4573
        $autoSignHeaders = [
4574
            'From',
4575
            'To',
4576
            'CC',
4577
            'Date',
4578
            'Subject',
4579
            'Reply-To',
4580
            'Message-ID',
4581
            'Content-Type',
4582
            'Mime-Version',
4583
            'X-Mailer',
4584
        ];
4585
        if (stripos($headers_line, 'Subject') === false) {
4586
            $headers_line .= 'Subject: ' . $subject . static::$LE;
4587
        }
4588
        $headerLines = explode(static::$LE, $headers_line);
4589
        $currentHeaderLabel = '';
4590
        $currentHeaderValue = '';
4591
        $parsedHeaders = [];
4592
        $headerLineIndex = 0;
4593
        $headerLineCount = count($headerLines);
4594
        foreach ($headerLines as $headerLine) {
4595
            $matches = [];
4596
            if (preg_match('/^([^ \t]*?)(?::[ \t]*)(.*)$/', $headerLine, $matches)) {
4597
                if ($currentHeaderLabel !== '') {
4598
                    //We were previously in another header; This is the start of a new header, so save the previous one
4599
                    $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue];
4600
                }
4601
                $currentHeaderLabel = $matches[1];
4602
                $currentHeaderValue = $matches[2];
4603
            } elseif (preg_match('/^[ \t]+(.*)$/', $headerLine, $matches)) {
4604
                //This is a folded continuation of the current header, so unfold it
4605
                $currentHeaderValue .= ' ' . $matches[1];
4606
            }
4607
            ++$headerLineIndex;
4608
            if ($headerLineIndex >= $headerLineCount) {
4609
                //This was the last line, so finish off this header
4610
                $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue];
4611
            }
4612
        }
4613
        $copiedHeaders = [];
4614
        $headersToSignKeys = [];
4615
        $headersToSign = [];
4616
        foreach ($parsedHeaders as $header) {
4617
            //Is this header one that must be included in the DKIM signature?
4618
            if (in_array($header['label'], $autoSignHeaders, true)) {
4619
                $headersToSignKeys[] = $header['label'];
4620
                $headersToSign[] = $header['label'] . ': ' . $header['value'];
4621
                if ($this->DKIM_copyHeaderFields) {
4622
                    $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC
4623
                        str_replace('|', '=7C', $this->DKIM_QP($header['value']));
4624
                }
4625
                continue;
4626
            }
4627
            //Is this an extra custom header we've been asked to sign?
4628
            if (in_array($header['label'], $this->DKIM_extraHeaders, true)) {
4629
                //Find its value in custom headers
4630
                foreach ($this->CustomHeader as $customHeader) {
4631
                    if ($customHeader[0] === $header['label']) {
4632
                        $headersToSignKeys[] = $header['label'];
4633
                        $headersToSign[] = $header['label'] . ': ' . $header['value'];
4634
                        if ($this->DKIM_copyHeaderFields) {
4635
                            $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC
4636
                                str_replace('|', '=7C', $this->DKIM_QP($header['value']));
4637
                        }
4638
                        //Skip straight to the next header
4639
                        continue 2;
4640
                    }
4641
                }
4642
            }
4643
        }
4644
        $copiedHeaderFields = '';
4645
        if ($this->DKIM_copyHeaderFields && count($copiedHeaders) > 0) {
4646
            //Assemble a DKIM 'z' tag
4647
            $copiedHeaderFields = ' z=';
4648
            $first = true;
4649
            foreach ($copiedHeaders as $copiedHeader) {
4650
                if (!$first) {
4651
                    $copiedHeaderFields .= static::$LE . ' |';
4652
                }
4653
                //Fold long values
4654
                if (strlen($copiedHeader) > self::STD_LINE_LENGTH - 3) {
4655
                    $copiedHeaderFields .= substr(
4656
                        chunk_split($copiedHeader, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS),
4657
                        0,
4658
                        -strlen(static::$LE . self::FWS)
4659
                    );
4660
                } else {
4661
                    $copiedHeaderFields .= $copiedHeader;
4662
                }
4663
                $first = false;
4664
            }
4665
            $copiedHeaderFields .= ';' . static::$LE;
4666
        }
4667
        $headerKeys = ' h=' . implode(':', $headersToSignKeys) . ';' . static::$LE;
4668
        $headerValues = implode(static::$LE, $headersToSign);
4669
        $body = $this->DKIM_BodyC($body);
4670
        $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); // Base64 of packed binary SHA-256 hash of body
4671
        $ident = '';
4672
        if ('' !== $this->DKIM_identity) {
4673
            $ident = ' i=' . $this->DKIM_identity . ';' . static::$LE;
4674
        }
4675
        //The DKIM-Signature header is included in the signature *except for* the value of the `b` tag
4676
        //which is appended after calculating the signature
4677
        //https://tools.ietf.org/html/rfc6376#section-3.5
4678
        $dkimSignatureHeader = 'DKIM-Signature: v=1;' .
4679
            ' d=' . $this->DKIM_domain . ';' .
4680
            ' s=' . $this->DKIM_selector . ';' . static::$LE .
4681
            ' a=' . $DKIMsignatureType . ';' .
4682
            ' q=' . $DKIMquery . ';' .
4683
            ' t=' . $DKIMtime . ';' .
4684
            ' c=' . $DKIMcanonicalization . ';' . static::$LE .
4685
            $headerKeys .
4686
            $ident .
4687
            $copiedHeaderFields .
4688
            ' bh=' . $DKIMb64 . ';' . static::$LE .
4689
            ' b=';
4690
        //Canonicalize the set of headers
4691
        $canonicalizedHeaders = $this->DKIM_HeaderC(
4692
            $headerValues . static::$LE . $dkimSignatureHeader
4693
        );
4694
        $signature = $this->DKIM_Sign($canonicalizedHeaders);
4695
        $signature = trim(chunk_split($signature, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS));
4696
4697
        return static::normalizeBreaks($dkimSignatureHeader . $signature);
4698
    }
4699
4700
    /**
4701
     * Detect if a string contains a line longer than the maximum line length
4702
     * allowed by RFC 2822 section 2.1.1.
4703
     *
4704
     * @param string $str
4705
     *
4706
     * @return bool
4707
     */
4708
    public static function hasLineLongerThanMax($str)
4709
    {
4710
        return (bool) preg_match('/^(.{' . (self::MAX_LINE_LENGTH + strlen(static::$LE)) . ',})/m', $str);
4711
    }
4712
4713
    /**
4714
     * Allows for public read access to 'to' property.
4715
     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4716
     *
4717
     * @return array
4718
     */
4719
    public function getToAddresses()
4720
    {
4721
        return $this->to;
4722
    }
4723
4724
    /**
4725
     * Allows for public read access to 'cc' property.
4726
     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4727
     *
4728
     * @return array
4729
     */
4730
    public function getCcAddresses()
4731
    {
4732
        return $this->cc;
4733
    }
4734
4735
    /**
4736
     * Allows for public read access to 'bcc' property.
4737
     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4738
     *
4739
     * @return array
4740
     */
4741
    public function getBccAddresses()
4742
    {
4743
        return $this->bcc;
4744
    }
4745
4746
    /**
4747
     * Allows for public read access to 'ReplyTo' property.
4748
     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4749
     *
4750
     * @return array
4751
     */
4752
    public function getReplyToAddresses()
4753
    {
4754
        return $this->ReplyTo;
4755
    }
4756
4757
    /**
4758
     * Allows for public read access to 'all_recipients' property.
4759
     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4760
     *
4761
     * @return array
4762
     */
4763
    public function getAllRecipientAddresses()
4764
    {
4765
        return $this->all_recipients;
4766
    }
4767
4768
    /**
4769
     * Perform a callback.
4770
     *
4771
     * @param bool   $isSent
4772
     * @param array  $to
4773
     * @param array  $cc
4774
     * @param array  $bcc
4775
     * @param string $subject
4776
     * @param string $body
4777
     * @param string $from
4778
     * @param array  $extra
4779
     */
4780
    protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from, $extra)
4781
    {
4782
        if (!empty($this->action_function) && is_callable($this->action_function)) {
4783
            call_user_func($this->action_function, $isSent, $to, $cc, $bcc, $subject, $body, $from, $extra);
4784
        }
4785
    }
4786
4787
    /**
4788
     * Get the OAuth instance.
4789
     *
4790
     * @return OAuth
4791
     */
4792
    public function getOAuth()
4793
    {
4794
        return $this->oauth;
4795
    }
4796
4797
    /**
4798
     * Set an OAuth instance.
4799
     */
4800
    public function setOAuth(OAuth $oauth)
4801
    {
4802
        $this->oauth = $oauth;
4803
    }
4804
}
4805