Subversion Repositories web_pages

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 rodolico 1
<?php
2
 
3
/**
4
 * PHPMailer - PHP email creation and transport class.
5
 * PHP Version 5.5.
6
 *
7
 * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
8
 *
9
 * @author    Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
10
 * @author    Jim Jagielski (jimjag) <jimjag@gmail.com>
11
 * @author    Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
12
 * @author    Brent R. Matzelle (original founder)
13
 * @copyright 2012 - 2020 Marcus Bointon
14
 * @copyright 2010 - 2012 Jim Jagielski
15
 * @copyright 2004 - 2009 Andy Prevost
16
 * @license   http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
17
 * @note      This program is distributed in the hope that it will be useful - WITHOUT
18
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19
 * FITNESS FOR A PARTICULAR PURPOSE.
20
 */
21
 
22
namespace PHPMailer\PHPMailer;
23
 
24
/**
25
 * PHPMailer - PHP email creation and transport class.
26
 *
27
 * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
28
 * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
29
 * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
30
 * @author Brent R. Matzelle (original founder)
31
 */
32
class PHPMailer
33
{
34
    const CHARSET_ASCII = 'us-ascii';
35
    const CHARSET_ISO88591 = 'iso-8859-1';
36
    const CHARSET_UTF8 = 'utf-8';
37
 
38
    const CONTENT_TYPE_PLAINTEXT = 'text/plain';
39
    const CONTENT_TYPE_TEXT_CALENDAR = 'text/calendar';
40
    const CONTENT_TYPE_TEXT_HTML = 'text/html';
41
    const CONTENT_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative';
42
    const CONTENT_TYPE_MULTIPART_MIXED = 'multipart/mixed';
43
    const CONTENT_TYPE_MULTIPART_RELATED = 'multipart/related';
44
 
45
    const ENCODING_7BIT = '7bit';
46
    const ENCODING_8BIT = '8bit';
47
    const ENCODING_BASE64 = 'base64';
48
    const ENCODING_BINARY = 'binary';
49
    const ENCODING_QUOTED_PRINTABLE = 'quoted-printable';
50
 
51
    const ENCRYPTION_STARTTLS = 'tls';
52
    const ENCRYPTION_SMTPS = 'ssl';
53
 
54
    const ICAL_METHOD_REQUEST = 'REQUEST';
55
    const ICAL_METHOD_PUBLISH = 'PUBLISH';
56
    const ICAL_METHOD_REPLY = 'REPLY';
57
    const ICAL_METHOD_ADD = 'ADD';
58
    const ICAL_METHOD_CANCEL = 'CANCEL';
59
    const ICAL_METHOD_REFRESH = 'REFRESH';
60
    const ICAL_METHOD_COUNTER = 'COUNTER';
61
    const ICAL_METHOD_DECLINECOUNTER = 'DECLINECOUNTER';
62
 
63
    /**
64
     * Email priority.
65
     * Options: null (default), 1 = High, 3 = Normal, 5 = low.
66
     * When null, the header is not set at all.
67
     *
68
     * @var int|null
69
     */
70
    public $Priority;
71
 
72
    /**
73
     * The character set of the message.
74
     *
75
     * @var string
76
     */
77
    public $CharSet = self::CHARSET_ISO88591;
78
 
79
    /**
80
     * The MIME Content-type of the message.
81
     *
82
     * @var string
83
     */
84
    public $ContentType = self::CONTENT_TYPE_PLAINTEXT;
85
 
86
    /**
87
     * The message encoding.
88
     * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
89
     *
90
     * @var string
91
     */
92
    public $Encoding = self::ENCODING_8BIT;
93
 
94
    /**
95
     * Holds the most recent mailer error message.
96
     *
97
     * @var string
98
     */
99
    public $ErrorInfo = '';
100
 
101
    /**
102
     * The From email address for the message.
103
     *
104
     * @var string
105
     */
106
    public $From = '';
107
 
108
    /**
109
     * The From name of the message.
110
     *
111
     * @var string
112
     */
113
    public $FromName = '';
114
 
115
    /**
116
     * The envelope sender of the message.
117
     * This will usually be turned into a Return-Path header by the receiver,
118
     * and is the address that bounces will be sent to.
119
     * If not empty, will be passed via `-f` to sendmail or as the 'MAIL FROM' value over SMTP.
120
     *
121
     * @var string
122
     */
123
    public $Sender = '';
124
 
125
    /**
126
     * The Subject of the message.
127
     *
128
     * @var string
129
     */
130
    public $Subject = '';
131
 
132
    /**
133
     * An HTML or plain text message body.
134
     * If HTML then call isHTML(true).
135
     *
136
     * @var string
137
     */
138
    public $Body = '';
139
 
140
    /**
141
     * The plain-text message body.
142
     * This body can be read by mail clients that do not have HTML email
143
     * capability such as mutt & Eudora.
144
     * Clients that can read HTML will view the normal Body.
145
     *
146
     * @var string
147
     */
148
    public $AltBody = '';
149
 
150
    /**
151
     * An iCal message part body.
152
     * Only supported in simple alt or alt_inline message types
153
     * To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator.
154
     *
155
     * @see http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
156
     * @see http://kigkonsult.se/iCalcreator/
157
     *
158
     * @var string
159
     */
160
    public $Ical = '';
161
 
162
    /**
163
     * Value-array of "method" in Contenttype header "text/calendar"
164
     *
165
     * @var string[]
166
     */
167
    protected static $IcalMethods = [
168
        self::ICAL_METHOD_REQUEST,
169
        self::ICAL_METHOD_PUBLISH,
170
        self::ICAL_METHOD_REPLY,
171
        self::ICAL_METHOD_ADD,
172
        self::ICAL_METHOD_CANCEL,
173
        self::ICAL_METHOD_REFRESH,
174
        self::ICAL_METHOD_COUNTER,
175
        self::ICAL_METHOD_DECLINECOUNTER,
176
    ];
177
 
178
    /**
179
     * The complete compiled MIME message body.
180
     *
181
     * @var string
182
     */
183
    protected $MIMEBody = '';
184
 
185
    /**
186
     * The complete compiled MIME message headers.
187
     *
188
     * @var string
189
     */
190
    protected $MIMEHeader = '';
191
 
192
    /**
193
     * Extra headers that createHeader() doesn't fold in.
194
     *
195
     * @var string
196
     */
197
    protected $mailHeader = '';
198
 
199
    /**
200
     * Word-wrap the message body to this number of chars.
201
     * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
202
     *
203
     * @see static::STD_LINE_LENGTH
204
     *
205
     * @var int
206
     */
207
    public $WordWrap = 0;
208
 
209
    /**
210
     * Which method to use to send mail.
211
     * Options: "mail", "sendmail", or "smtp".
212
     *
213
     * @var string
214
     */
215
    public $Mailer = 'mail';
216
 
217
    /**
218
     * The path to the sendmail program.
219
     *
220
     * @var string
221
     */
222
    public $Sendmail = '/usr/sbin/sendmail';
223
 
224
    /**
225
     * Whether mail() uses a fully sendmail-compatible MTA.
226
     * One which supports sendmail's "-oi -f" options.
227
     *
228
     * @var bool
229
     */
230
    public $UseSendmailOptions = true;
231
 
232
    /**
233
     * The email address that a reading confirmation should be sent to, also known as read receipt.
234
     *
235
     * @var string
236
     */
237
    public $ConfirmReadingTo = '';
238
 
239
    /**
240
     * The hostname to use in the Message-ID header and as default HELO string.
241
     * If empty, PHPMailer attempts to find one with, in order,
242
     * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value
243
     * 'localhost.localdomain'.
244
     *
245
     * @see PHPMailer::$Helo
246
     *
247
     * @var string
248
     */
249
    public $Hostname = '';
250
 
251
    /**
252
     * An ID to be used in the Message-ID header.
253
     * If empty, a unique id will be generated.
254
     * You can set your own, but it must be in the format "<id@domain>",
255
     * as defined in RFC5322 section 3.6.4 or it will be ignored.
256
     *
257
     * @see https://tools.ietf.org/html/rfc5322#section-3.6.4
258
     *
259
     * @var string
260
     */
261
    public $MessageID = '';
262
 
263
    /**
264
     * The message Date to be used in the Date header.
265
     * If empty, the current date will be added.
266
     *
267
     * @var string
268
     */
269
    public $MessageDate = '';
270
 
271
    /**
272
     * SMTP hosts.
273
     * Either a single hostname or multiple semicolon-delimited hostnames.
274
     * You can also specify a different port
275
     * for each host by using this format: [hostname:port]
276
     * (e.g. "smtp1.example.com:25;smtp2.example.com").
277
     * You can also specify encryption type, for example:
278
     * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
279
     * Hosts will be tried in order.
280
     *
281
     * @var string
282
     */
283
    public $Host = 'localhost';
284
 
285
    /**
286
     * The default SMTP server port.
287
     *
288
     * @var int
289
     */
290
    public $Port = 25;
291
 
292
    /**
293
     * The SMTP HELO/EHLO name used for the SMTP connection.
294
     * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find
295
     * one with the same method described above for $Hostname.
296
     *
297
     * @see PHPMailer::$Hostname
298
     *
299
     * @var string
300
     */
301
    public $Helo = '';
302
 
303
    /**
304
     * What kind of encryption to use on the SMTP connection.
305
     * Options: '', static::ENCRYPTION_STARTTLS, or static::ENCRYPTION_SMTPS.
306
     *
307
     * @var string
308
     */
309
    public $SMTPSecure = '';
310
 
311
    /**
312
     * Whether to enable TLS encryption automatically if a server supports it,
313
     * even if `SMTPSecure` is not set to 'tls'.
314
     * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
315
     *
316
     * @var bool
317
     */
318
    public $SMTPAutoTLS = true;
319
 
320
    /**
321
     * Whether to use SMTP authentication.
322
     * Uses the Username and Password properties.
323
     *
324
     * @see PHPMailer::$Username
325
     * @see PHPMailer::$Password
326
     *
327
     * @var bool
328
     */
329
    public $SMTPAuth = false;
330
 
331
    /**
332
     * Options array passed to stream_context_create when connecting via SMTP.
333
     *
334
     * @var array
335
     */
336
    public $SMTPOptions = [];
337
 
338
    /**
339
     * SMTP username.
340
     *
341
     * @var string
342
     */
343
    public $Username = '';
344
 
345
    /**
346
     * SMTP password.
347
     *
348
     * @var string
349
     */
350
    public $Password = '';
351
 
352
    /**
353
     * SMTP authentication type. Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2.
354
     * If not specified, the first one from that list that the server supports will be selected.
355
     *
356
     * @var string
357
     */
358
    public $AuthType = '';
359
 
360
    /**
361
     * SMTP SMTPXClient command attibutes
362
     *
363
     * @var array
364
     */
365
    protected $SMTPXClient = [];
366
 
367
    /**
368
     * An implementation of the PHPMailer OAuthTokenProvider interface.
369
     *
370
     * @var OAuthTokenProvider
371
     */
372
    protected $oauth;
373
 
374
    /**
375
     * The SMTP server timeout in seconds.
376
     * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.
377
     *
378
     * @var int
379
     */
380
    public $Timeout = 300;
381
 
382
    /**
383
     * Comma separated list of DSN notifications
384
     * 'NEVER' under no circumstances a DSN must be returned to the sender.
385
     *         If you use NEVER all other notifications will be ignored.
386
     * 'SUCCESS' will notify you when your mail has arrived at its destination.
387
     * 'FAILURE' will arrive if an error occurred during delivery.
388
     * 'DELAY'   will notify you if there is an unusual delay in delivery, but the actual
389
     *           delivery's outcome (success or failure) is not yet decided.
390
     *
391
     * @see https://tools.ietf.org/html/rfc3461 See section 4.1 for more information about NOTIFY
392
     */
393
    public $dsn = '';
394
 
395
    /**
396
     * SMTP class debug output mode.
397
     * Debug output level.
398
     * Options:
399
     * @see SMTP::DEBUG_OFF: No output
400
     * @see SMTP::DEBUG_CLIENT: Client messages
401
     * @see SMTP::DEBUG_SERVER: Client and server messages
402
     * @see SMTP::DEBUG_CONNECTION: As SERVER plus connection status
403
     * @see SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, rarely needed
404
     *
405
     * @see SMTP::$do_debug
406
     *
407
     * @var int
408
     */
409
    public $SMTPDebug = 0;
410
 
411
    /**
412
     * How to handle debug output.
413
     * Options:
414
     * * `echo` Output plain-text as-is, appropriate for CLI
415
     * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
416
     * * `error_log` Output to error log as configured in php.ini
417
     * By default PHPMailer will use `echo` if run from a `cli` or `cli-server` SAPI, `html` otherwise.
418
     * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
419
     *
420
     * ```php
421
     * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
422
     * ```
423
     *
424
     * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug`
425
     * level output is used:
426
     *
427
     * ```php
428
     * $mail->Debugoutput = new myPsr3Logger;
429
     * ```
430
     *
431
     * @see SMTP::$Debugoutput
432
     *
433
     * @var string|callable|\Psr\Log\LoggerInterface
434
     */
435
    public $Debugoutput = 'echo';
436
 
437
    /**
438
     * Whether to keep the SMTP connection open after each message.
439
     * If this is set to true then the connection will remain open after a send,
440
     * and closing the connection will require an explicit call to smtpClose().
441
     * It's a good idea to use this if you are sending multiple messages as it reduces overhead.
442
     * See the mailing list example for how to use it.
443
     *
444
     * @var bool
445
     */
446
    public $SMTPKeepAlive = false;
447
 
448
    /**
449
     * Whether to split multiple to addresses into multiple messages
450
     * or send them all in one message.
451
     * Only supported in `mail` and `sendmail` transports, not in SMTP.
452
     *
453
     * @var bool
454
     *
455
     * @deprecated 6.0.0 PHPMailer isn't a mailing list manager!
456
     */
457
    public $SingleTo = false;
458
 
459
    /**
460
     * Storage for addresses when SingleTo is enabled.
461
     *
462
     * @var array
463
     */
464
    protected $SingleToArray = [];
465
 
466
    /**
467
     * Whether to generate VERP addresses on send.
468
     * Only applicable when sending via SMTP.
469
     *
470
     * @see https://en.wikipedia.org/wiki/Variable_envelope_return_path
471
     * @see http://www.postfix.org/VERP_README.html Postfix VERP info
472
     *
473
     * @var bool
474
     */
475
    public $do_verp = false;
476
 
477
    /**
478
     * Whether to allow sending messages with an empty body.
479
     *
480
     * @var bool
481
     */
482
    public $AllowEmpty = false;
483
 
484
    /**
485
     * DKIM selector.
486
     *
487
     * @var string
488
     */
489
    public $DKIM_selector = '';
490
 
491
    /**
492
     * DKIM Identity.
493
     * Usually the email address used as the source of the email.
494
     *
495
     * @var string
496
     */
497
    public $DKIM_identity = '';
498
 
499
    /**
500
     * DKIM passphrase.
501
     * Used if your key is encrypted.
502
     *
503
     * @var string
504
     */
505
    public $DKIM_passphrase = '';
506
 
507
    /**
508
     * DKIM signing domain name.
509
     *
510
     * @example 'example.com'
511
     *
512
     * @var string
513
     */
514
    public $DKIM_domain = '';
515
 
516
    /**
517
     * DKIM Copy header field values for diagnostic use.
518
     *
519
     * @var bool
520
     */
521
    public $DKIM_copyHeaderFields = true;
522
 
523
    /**
524
     * DKIM Extra signing headers.
525
     *
526
     * @example ['List-Unsubscribe', 'List-Help']
527
     *
528
     * @var array
529
     */
530
    public $DKIM_extraHeaders = [];
531
 
532
    /**
533
     * DKIM private key file path.
534
     *
535
     * @var string
536
     */
537
    public $DKIM_private = '';
538
 
539
    /**
540
     * DKIM private key string.
541
     *
542
     * If set, takes precedence over `$DKIM_private`.
543
     *
544
     * @var string
545
     */
546
    public $DKIM_private_string = '';
547
 
548
    /**
549
     * Callback Action function name.
550
     *
551
     * The function that handles the result of the send email action.
552
     * It is called out by send() for each email sent.
553
     *
554
     * Value can be any php callable: http://www.php.net/is_callable
555
     *
556
     * Parameters:
557
     *   bool $result        result of the send action
558
     *   array   $to            email addresses of the recipients
559
     *   array   $cc            cc email addresses
560
     *   array   $bcc           bcc email addresses
561
     *   string  $subject       the subject
562
     *   string  $body          the email body
563
     *   string  $from          email address of sender
564
     *   string  $extra         extra information of possible use
565
     *                          "smtp_transaction_id' => last smtp transaction id
566
     *
567
     * @var string
568
     */
569
    public $action_function = '';
570
 
571
    /**
572
     * What to put in the X-Mailer header.
573
     * Options: An empty string for PHPMailer default, whitespace/null for none, or a string to use.
574
     *
575
     * @var string|null
576
     */
577
    public $XMailer = '';
578
 
579
    /**
580
     * Which validator to use by default when validating email addresses.
581
     * May be a callable to inject your own validator, but there are several built-in validators.
582
     * The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option.
583
     *
584
     * @see PHPMailer::validateAddress()
585
     *
586
     * @var string|callable
587
     */
588
    public static $validator = 'php';
589
 
590
    /**
591
     * An instance of the SMTP sender class.
592
     *
593
     * @var SMTP
594
     */
595
    protected $smtp;
596
 
597
    /**
598
     * The array of 'to' names and addresses.
599
     *
600
     * @var array
601
     */
602
    protected $to = [];
603
 
604
    /**
605
     * The array of 'cc' names and addresses.
606
     *
607
     * @var array
608
     */
609
    protected $cc = [];
610
 
611
    /**
612
     * The array of 'bcc' names and addresses.
613
     *
614
     * @var array
615
     */
616
    protected $bcc = [];
617
 
618
    /**
619
     * The array of reply-to names and addresses.
620
     *
621
     * @var array
622
     */
623
    protected $ReplyTo = [];
624
 
625
    /**
626
     * An array of all kinds of addresses.
627
     * Includes all of $to, $cc, $bcc.
628
     *
629
     * @see PHPMailer::$to
630
     * @see PHPMailer::$cc
631
     * @see PHPMailer::$bcc
632
     *
633
     * @var array
634
     */
635
    protected $all_recipients = [];
636
 
637
    /**
638
     * An array of names and addresses queued for validation.
639
     * In send(), valid and non duplicate entries are moved to $all_recipients
640
     * and one of $to, $cc, or $bcc.
641
     * This array is used only for addresses with IDN.
642
     *
643
     * @see PHPMailer::$to
644
     * @see PHPMailer::$cc
645
     * @see PHPMailer::$bcc
646
     * @see PHPMailer::$all_recipients
647
     *
648
     * @var array
649
     */
650
    protected $RecipientsQueue = [];
651
 
652
    /**
653
     * An array of reply-to names and addresses queued for validation.
654
     * In send(), valid and non duplicate entries are moved to $ReplyTo.
655
     * This array is used only for addresses with IDN.
656
     *
657
     * @see PHPMailer::$ReplyTo
658
     *
659
     * @var array
660
     */
661
    protected $ReplyToQueue = [];
662
 
663
    /**
664
     * The array of attachments.
665
     *
666
     * @var array
667
     */
668
    protected $attachment = [];
669
 
670
    /**
671
     * The array of custom headers.
672
     *
673
     * @var array
674
     */
675
    protected $CustomHeader = [];
676
 
677
    /**
678
     * The most recent Message-ID (including angular brackets).
679
     *
680
     * @var string
681
     */
682
    protected $lastMessageID = '';
683
 
684
    /**
685
     * The message's MIME type.
686
     *
687
     * @var string
688
     */
689
    protected $message_type = '';
690
 
691
    /**
692
     * The array of MIME boundary strings.
693
     *
694
     * @var array
695
     */
696
    protected $boundary = [];
697
 
698
    /**
699
     * The array of available text strings for the current language.
700
     *
701
     * @var array
702
     */
703
    protected $language = [];
704
 
705
    /**
706
     * The number of errors encountered.
707
     *
708
     * @var int
709
     */
710
    protected $error_count = 0;
711
 
712
    /**
713
     * The S/MIME certificate file path.
714
     *
715
     * @var string
716
     */
717
    protected $sign_cert_file = '';
718
 
719
    /**
720
     * The S/MIME key file path.
721
     *
722
     * @var string
723
     */
724
    protected $sign_key_file = '';
725
 
726
    /**
727
     * The optional S/MIME extra certificates ("CA Chain") file path.
728
     *
729
     * @var string
730
     */
731
    protected $sign_extracerts_file = '';
732
 
733
    /**
734
     * The S/MIME password for the key.
735
     * Used only if the key is encrypted.
736
     *
737
     * @var string
738
     */
739
    protected $sign_key_pass = '';
740
 
741
    /**
742
     * Whether to throw exceptions for errors.
743
     *
744
     * @var bool
745
     */
746
    protected $exceptions = false;
747
 
748
    /**
749
     * Unique ID used for message ID and boundaries.
750
     *
751
     * @var string
752
     */
753
    protected $uniqueid = '';
754
 
755
    /**
756
     * The PHPMailer Version number.
757
     *
758
     * @var string
759
     */
760
    const VERSION = '6.9.1';
761
 
762
    /**
763
     * Error severity: message only, continue processing.
764
     *
765
     * @var int
766
     */
767
    const STOP_MESSAGE = 0;
768
 
769
    /**
770
     * Error severity: message, likely ok to continue processing.
771
     *
772
     * @var int
773
     */
774
    const STOP_CONTINUE = 1;
775
 
776
    /**
777
     * Error severity: message, plus full stop, critical error reached.
778
     *
779
     * @var int
780
     */
781
    const STOP_CRITICAL = 2;
782
 
783
    /**
784
     * The SMTP standard CRLF line break.
785
     * If you want to change line break format, change static::$LE, not this.
786
     */
787
    const CRLF = "\r\n";
788
 
789
    /**
790
     * "Folding White Space" a white space string used for line folding.
791
     */
792
    const FWS = ' ';
793
 
794
    /**
795
     * SMTP RFC standard line ending; Carriage Return, Line Feed.
796
     *
797
     * @var string
798
     */
799
    protected static $LE = self::CRLF;
800
 
801
    /**
802
     * The maximum line length supported by mail().
803
     *
804
     * Background: mail() will sometimes corrupt messages
805
     * with headers longer than 65 chars, see #818.
806
     *
807
     * @var int
808
     */
809
    const MAIL_MAX_LINE_LENGTH = 63;
810
 
811
    /**
812
     * The maximum line length allowed by RFC 2822 section 2.1.1.
813
     *
814
     * @var int
815
     */
816
    const MAX_LINE_LENGTH = 998;
817
 
818
    /**
819
     * The lower maximum line length allowed by RFC 2822 section 2.1.1.
820
     * This length does NOT include the line break
821
     * 76 means that lines will be 77 or 78 chars depending on whether
822
     * the line break format is LF or CRLF; both are valid.
823
     *
824
     * @var int
825
     */
826
    const STD_LINE_LENGTH = 76;
827
 
828
    /**
829
     * Constructor.
830
     *
831
     * @param bool $exceptions Should we throw external exceptions?
832
     */
833
    public function __construct($exceptions = null)
834
    {
835
        if (null !== $exceptions) {
836
            $this->exceptions = (bool) $exceptions;
837
        }
838
        //Pick an appropriate debug output format automatically
839
        $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html');
840
    }
841
 
842
    /**
843
     * Destructor.
844
     */
845
    public function __destruct()
846
    {
847
        //Close any open SMTP connection nicely
848
        $this->smtpClose();
849
    }
850
 
851
    /**
852
     * Call mail() in a safe_mode-aware fashion.
853
     * Also, unless sendmail_path points to sendmail (or something that
854
     * claims to be sendmail), don't pass params (not a perfect fix,
855
     * but it will do).
856
     *
857
     * @param string      $to      To
858
     * @param string      $subject Subject
859
     * @param string      $body    Message Body
860
     * @param string      $header  Additional Header(s)
861
     * @param string|null $params  Params
862
     *
863
     * @return bool
864
     */
865
    private function mailPassthru($to, $subject, $body, $header, $params)
866
    {
867
        //Check overloading of mail function to avoid double-encoding
868
        if ((int)ini_get('mbstring.func_overload') & 1) {
869
            $subject = $this->secureHeader($subject);
870
        } else {
871
            $subject = $this->encodeHeader($this->secureHeader($subject));
872
        }
873
        //Calling mail() with null params breaks
874
        $this->edebug('Sending with mail()');
875
        $this->edebug('Sendmail path: ' . ini_get('sendmail_path'));
876
        $this->edebug("Envelope sender: {$this->Sender}");
877
        $this->edebug("To: {$to}");
878
        $this->edebug("Subject: {$subject}");
879
        $this->edebug("Headers: {$header}");
880
        if (!$this->UseSendmailOptions || null === $params) {
881
            $result = @mail($to, $subject, $body, $header);
882
        } else {
883
            $this->edebug("Additional params: {$params}");
884
            $result = @mail($to, $subject, $body, $header, $params);
885
        }
886
        $this->edebug('Result: ' . ($result ? 'true' : 'false'));
887
        return $result;
888
    }
889
 
890
    /**
891
     * Output debugging info via a user-defined method.
892
     * Only generates output if debug output is enabled.
893
     *
894
     * @see PHPMailer::$Debugoutput
895
     * @see PHPMailer::$SMTPDebug
896
     *
897
     * @param string $str
898
     */
899
    protected function edebug($str)
900
    {
901
        if ($this->SMTPDebug <= 0) {
902
            return;
903
        }
904
        //Is this a PSR-3 logger?
905
        if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) {
906
            $this->Debugoutput->debug($str);
907
 
908
            return;
909
        }
910
        //Avoid clash with built-in function names
911
        if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) {
912
            call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
913
 
914
            return;
915
        }
916
        switch ($this->Debugoutput) {
917
            case 'error_log':
918
                //Don't output, just log
919
                /** @noinspection ForgottenDebugOutputInspection */
920
                error_log($str);
921
                break;
922
            case 'html':
923
                //Cleans up output a bit for a better looking, HTML-safe output
924
                echo htmlentities(
925
                    preg_replace('/[\r\n]+/', '', $str),
926
                    ENT_QUOTES,
927
                    'UTF-8'
928
                ), "<br>\n";
929
                break;
930
            case 'echo':
931
            default:
932
                //Normalize line breaks
933
                $str = preg_replace('/\r\n|\r/m', "\n", $str);
934
                echo gmdate('Y-m-d H:i:s'),
935
                "\t",
936
                    //Trim trailing space
937
                trim(
938
                    //Indent for readability, except for trailing break
939
                    str_replace(
940
                        "\n",
941
                        "\n                   \t                  ",
942
                        trim($str)
943
                    )
944
                ),
945
                "\n";
946
        }
947
    }
948
 
949
    /**
950
     * Sets message type to HTML or plain.
951
     *
952
     * @param bool $isHtml True for HTML mode
953
     */
954
    public function isHTML($isHtml = true)
955
    {
956
        if ($isHtml) {
957
            $this->ContentType = static::CONTENT_TYPE_TEXT_HTML;
958
        } else {
959
            $this->ContentType = static::CONTENT_TYPE_PLAINTEXT;
960
        }
961
    }
962
 
963
    /**
964
     * Send messages using SMTP.
965
     */
966
    public function isSMTP()
967
    {
968
        $this->Mailer = 'smtp';
969
    }
970
 
971
    /**
972
     * Send messages using PHP's mail() function.
973
     */
974
    public function isMail()
975
    {
976
        $this->Mailer = 'mail';
977
    }
978
 
979
    /**
980
     * Send messages using $Sendmail.
981
     */
982
    public function isSendmail()
983
    {
984
        $ini_sendmail_path = ini_get('sendmail_path');
985
 
986
        if (false === stripos($ini_sendmail_path, 'sendmail')) {
987
            $this->Sendmail = '/usr/sbin/sendmail';
988
        } else {
989
            $this->Sendmail = $ini_sendmail_path;
990
        }
991
        $this->Mailer = 'sendmail';
992
    }
993
 
994
    /**
995
     * Send messages using qmail.
996
     */
997
    public function isQmail()
998
    {
999
        $ini_sendmail_path = ini_get('sendmail_path');
1000
 
1001
        if (false === stripos($ini_sendmail_path, 'qmail')) {
1002
            $this->Sendmail = '/var/qmail/bin/qmail-inject';
1003
        } else {
1004
            $this->Sendmail = $ini_sendmail_path;
1005
        }
1006
        $this->Mailer = 'qmail';
1007
    }
1008
 
1009
    /**
1010
     * Add a "To" address.
1011
     *
1012
     * @param string $address The email address to send to
1013
     * @param string $name
1014
     *
1015
     * @throws Exception
1016
     *
1017
     * @return bool true on success, false if address already used or invalid in some way
1018
     */
1019
    public function addAddress($address, $name = '')
1020
    {
1021
        return $this->addOrEnqueueAnAddress('to', $address, $name);
1022
    }
1023
 
1024
    /**
1025
     * Add a "CC" address.
1026
     *
1027
     * @param string $address The email address to send to
1028
     * @param string $name
1029
     *
1030
     * @throws Exception
1031
     *
1032
     * @return bool true on success, false if address already used or invalid in some way
1033
     */
1034
    public function addCC($address, $name = '')
1035
    {
1036
        return $this->addOrEnqueueAnAddress('cc', $address, $name);
1037
    }
1038
 
1039
    /**
1040
     * Add a "BCC" address.
1041
     *
1042
     * @param string $address The email address to send to
1043
     * @param string $name
1044
     *
1045
     * @throws Exception
1046
     *
1047
     * @return bool true on success, false if address already used or invalid in some way
1048
     */
1049
    public function addBCC($address, $name = '')
1050
    {
1051
        return $this->addOrEnqueueAnAddress('bcc', $address, $name);
1052
    }
1053
 
1054
    /**
1055
     * Add a "Reply-To" address.
1056
     *
1057
     * @param string $address The email address to reply to
1058
     * @param string $name
1059
     *
1060
     * @throws Exception
1061
     *
1062
     * @return bool true on success, false if address already used or invalid in some way
1063
     */
1064
    public function addReplyTo($address, $name = '')
1065
    {
1066
        return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);
1067
    }
1068
 
1069
    /**
1070
     * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer
1071
     * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still
1072
     * be modified after calling this function), addition of such addresses is delayed until send().
1073
     * Addresses that have been added already return false, but do not throw exceptions.
1074
     *
1075
     * @param string $kind    One of 'to', 'cc', 'bcc', or 'ReplyTo'
1076
     * @param string $address The email address
1077
     * @param string $name    An optional username associated with the address
1078
     *
1079
     * @throws Exception
1080
     *
1081
     * @return bool true on success, false if address already used or invalid in some way
1082
     */
1083
    protected function addOrEnqueueAnAddress($kind, $address, $name)
1084
    {
1085
        $pos = false;
1086
        if ($address !== null) {
1087
            $address = trim($address);
1088
            $pos = strrpos($address, '@');
1089
        }
1090
        if (false === $pos) {
1091
            //At-sign is missing.
1092
            $error_message = sprintf(
1093
                '%s (%s): %s',
1094
                $this->lang('invalid_address'),
1095
                $kind,
1096
                $address
1097
            );
1098
            $this->setError($error_message);
1099
            $this->edebug($error_message);
1100
            if ($this->exceptions) {
1101
                throw new Exception($error_message);
1102
            }
1103
 
1104
            return false;
1105
        }
1106
        if ($name !== null && is_string($name)) {
1107
            $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
1108
        } else {
1109
            $name = '';
1110
        }
1111
        $params = [$kind, $address, $name];
1112
        //Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
1113
        //Domain is assumed to be whatever is after the last @ symbol in the address
1114
        if (static::idnSupported() && $this->has8bitChars(substr($address, ++$pos))) {
1115
            if ('Reply-To' !== $kind) {
1116
                if (!array_key_exists($address, $this->RecipientsQueue)) {
1117
                    $this->RecipientsQueue[$address] = $params;
1118
 
1119
                    return true;
1120
                }
1121
            } elseif (!array_key_exists($address, $this->ReplyToQueue)) {
1122
                $this->ReplyToQueue[$address] = $params;
1123
 
1124
                return true;
1125
            }
1126
 
1127
            return false;
1128
        }
1129
 
1130
        //Immediately add standard addresses without IDN.
1131
        return call_user_func_array([$this, 'addAnAddress'], $params);
1132
    }
1133
 
1134
    /**
1135
     * Set the boundaries to use for delimiting MIME parts.
1136
     * If you override this, ensure you set all 3 boundaries to unique values.
1137
     * The default boundaries include a "=_" sequence which cannot occur in quoted-printable bodies,
1138
     * as suggested by https://www.rfc-editor.org/rfc/rfc2045#section-6.7
1139
     *
1140
     * @return void
1141
     */
1142
    public function setBoundaries()
1143
    {
1144
        $this->uniqueid = $this->generateId();
1145
        $this->boundary[1] = 'b1=_' . $this->uniqueid;
1146
        $this->boundary[2] = 'b2=_' . $this->uniqueid;
1147
        $this->boundary[3] = 'b3=_' . $this->uniqueid;
1148
    }
1149
 
1150
    /**
1151
     * Add an address to one of the recipient arrays or to the ReplyTo array.
1152
     * Addresses that have been added already return false, but do not throw exceptions.
1153
     *
1154
     * @param string $kind    One of 'to', 'cc', 'bcc', or 'ReplyTo'
1155
     * @param string $address The email address to send, resp. to reply to
1156
     * @param string $name
1157
     *
1158
     * @throws Exception
1159
     *
1160
     * @return bool true on success, false if address already used or invalid in some way
1161
     */
1162
    protected function addAnAddress($kind, $address, $name = '')
1163
    {
1164
        if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) {
1165
            $error_message = sprintf(
1166
                '%s: %s',
1167
                $this->lang('Invalid recipient kind'),
1168
                $kind
1169
            );
1170
            $this->setError($error_message);
1171
            $this->edebug($error_message);
1172
            if ($this->exceptions) {
1173
                throw new Exception($error_message);
1174
            }
1175
 
1176
            return false;
1177
        }
1178
        if (!static::validateAddress($address)) {
1179
            $error_message = sprintf(
1180
                '%s (%s): %s',
1181
                $this->lang('invalid_address'),
1182
                $kind,
1183
                $address
1184
            );
1185
            $this->setError($error_message);
1186
            $this->edebug($error_message);
1187
            if ($this->exceptions) {
1188
                throw new Exception($error_message);
1189
            }
1190
 
1191
            return false;
1192
        }
1193
        if ('Reply-To' !== $kind) {
1194
            if (!array_key_exists(strtolower($address), $this->all_recipients)) {
1195
                $this->{$kind}[] = [$address, $name];
1196
                $this->all_recipients[strtolower($address)] = true;
1197
 
1198
                return true;
1199
            }
1200
        } elseif (!array_key_exists(strtolower($address), $this->ReplyTo)) {
1201
            $this->ReplyTo[strtolower($address)] = [$address, $name];
1202
 
1203
            return true;
1204
        }
1205
 
1206
        return false;
1207
    }
1208
 
1209
    /**
1210
     * Parse and validate a string containing one or more RFC822-style comma-separated email addresses
1211
     * of the form "display name <address>" into an array of name/address pairs.
1212
     * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
1213
     * Note that quotes in the name part are removed.
1214
     *
1215
     * @see http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
1216
     *
1217
     * @param string $addrstr The address list string
1218
     * @param bool   $useimap Whether to use the IMAP extension to parse the list
1219
     * @param string $charset The charset to use when decoding the address list string.
1220
     *
1221
     * @return array
1222
     */
1223
    public static function parseAddresses($addrstr, $useimap = true, $charset = self::CHARSET_ISO88591)
1224
    {
1225
        $addresses = [];
1226
        if ($useimap && function_exists('imap_rfc822_parse_adrlist')) {
1227
            //Use this built-in parser if it's available
1228
            $list = imap_rfc822_parse_adrlist($addrstr, '');
1229
            // Clear any potential IMAP errors to get rid of notices being thrown at end of script.
1230
            imap_errors();
1231
            foreach ($list as $address) {
1232
                if (
1233
                    '.SYNTAX-ERROR.' !== $address->host &&
1234
                    static::validateAddress($address->mailbox . '@' . $address->host)
1235
                ) {
1236
                    //Decode the name part if it's present and encoded
1237
                    if (
1238
                        property_exists($address, 'personal') &&
1239
                        //Check for a Mbstring constant rather than using extension_loaded, which is sometimes disabled
1240
                        defined('MB_CASE_UPPER') &&
1241
                        preg_match('/^=\?.*\?=$/s', $address->personal)
1242
                    ) {
1243
                        $origCharset = mb_internal_encoding();
1244
                        mb_internal_encoding($charset);
1245
                        //Undo any RFC2047-encoded spaces-as-underscores
1246
                        $address->personal = str_replace('_', '=20', $address->personal);
1247
                        //Decode the name
1248
                        $address->personal = mb_decode_mimeheader($address->personal);
1249
                        mb_internal_encoding($origCharset);
1250
                    }
1251
 
1252
                    $addresses[] = [
1253
                        'name' => (property_exists($address, 'personal') ? $address->personal : ''),
1254
                        'address' => $address->mailbox . '@' . $address->host,
1255
                    ];
1256
                }
1257
            }
1258
        } else {
1259
            //Use this simpler parser
1260
            $list = explode(',', $addrstr);
1261
            foreach ($list as $address) {
1262
                $address = trim($address);
1263
                //Is there a separate name part?
1264
                if (strpos($address, '<') === false) {
1265
                    //No separate name, just use the whole thing
1266
                    if (static::validateAddress($address)) {
1267
                        $addresses[] = [
1268
                            'name' => '',
1269
                            'address' => $address,
1270
                        ];
1271
                    }
1272
                } else {
1273
                    list($name, $email) = explode('<', $address);
1274
                    $email = trim(str_replace('>', '', $email));
1275
                    $name = trim($name);
1276
                    if (static::validateAddress($email)) {
1277
                        //Check for a Mbstring constant rather than using extension_loaded, which is sometimes disabled
1278
                        //If this name is encoded, decode it
1279
                        if (defined('MB_CASE_UPPER') && preg_match('/^=\?.*\?=$/s', $name)) {
1280
                            $origCharset = mb_internal_encoding();
1281
                            mb_internal_encoding($charset);
1282
                            //Undo any RFC2047-encoded spaces-as-underscores
1283
                            $name = str_replace('_', '=20', $name);
1284
                            //Decode the name
1285
                            $name = mb_decode_mimeheader($name);
1286
                            mb_internal_encoding($origCharset);
1287
                        }
1288
                        $addresses[] = [
1289
                            //Remove any surrounding quotes and spaces from the name
1290
                            'name' => trim($name, '\'" '),
1291
                            'address' => $email,
1292
                        ];
1293
                    }
1294
                }
1295
            }
1296
        }
1297
 
1298
        return $addresses;
1299
    }
1300
 
1301
    /**
1302
     * Set the From and FromName properties.
1303
     *
1304
     * @param string $address
1305
     * @param string $name
1306
     * @param bool   $auto    Whether to also set the Sender address, defaults to true
1307
     *
1308
     * @throws Exception
1309
     *
1310
     * @return bool
1311
     */
1312
    public function setFrom($address, $name = '', $auto = true)
1313
    {
1314
        $address = trim((string)$address);
1315
        $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
1316
        //Don't validate now addresses with IDN. Will be done in send().
1317
        $pos = strrpos($address, '@');
1318
        if (
1319
            (false === $pos)
1320
            || ((!$this->has8bitChars(substr($address, ++$pos)) || !static::idnSupported())
1321
            && !static::validateAddress($address))
1322
        ) {
1323
            $error_message = sprintf(
1324
                '%s (From): %s',
1325
                $this->lang('invalid_address'),
1326
                $address
1327
            );
1328
            $this->setError($error_message);
1329
            $this->edebug($error_message);
1330
            if ($this->exceptions) {
1331
                throw new Exception($error_message);
1332
            }
1333
 
1334
            return false;
1335
        }
1336
        $this->From = $address;
1337
        $this->FromName = $name;
1338
        if ($auto && empty($this->Sender)) {
1339
            $this->Sender = $address;
1340
        }
1341
 
1342
        return true;
1343
    }
1344
 
1345
    /**
1346
     * Return the Message-ID header of the last email.
1347
     * Technically this is the value from the last time the headers were created,
1348
     * but it's also the message ID of the last sent message except in
1349
     * pathological cases.
1350
     *
1351
     * @return string
1352
     */
1353
    public function getLastMessageID()
1354
    {
1355
        return $this->lastMessageID;
1356
    }
1357
 
1358
    /**
1359
     * Check that a string looks like an email address.
1360
     * Validation patterns supported:
1361
     * * `auto` Pick best pattern automatically;
1362
     * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0;
1363
     * * `pcre` Use old PCRE implementation;
1364
     * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;
1365
     * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
1366
     * * `noregex` Don't use a regex: super fast, really dumb.
1367
     * Alternatively you may pass in a callable to inject your own validator, for example:
1368
     *
1369
     * ```php
1370
     * PHPMailer::validateAddress('user@example.com', function($address) {
1371
     *     return (strpos($address, '@') !== false);
1372
     * });
1373
     * ```
1374
     *
1375
     * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator.
1376
     *
1377
     * @param string          $address       The email address to check
1378
     * @param string|callable $patternselect Which pattern to use
1379
     *
1380
     * @return bool
1381
     */
1382
    public static function validateAddress($address, $patternselect = null)
1383
    {
1384
        if (null === $patternselect) {
1385
            $patternselect = static::$validator;
1386
        }
1387
        //Don't allow strings as callables, see SECURITY.md and CVE-2021-3603
1388
        if (is_callable($patternselect) && !is_string($patternselect)) {
1389
            return call_user_func($patternselect, $address);
1390
        }
1391
        //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
1392
        if (strpos($address, "\n") !== false || strpos($address, "\r") !== false) {
1393
            return false;
1394
        }
1395
        switch ($patternselect) {
1396
            case 'pcre': //Kept for BC
1397
            case 'pcre8':
1398
                /*
1399
                 * A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL
1400
                 * is based.
1401
                 * In addition to the addresses allowed by filter_var, also permits:
1402
                 *  * dotless domains: `a@b`
1403
                 *  * comments: `1234 @ local(blah) .machine .example`
1404
                 *  * quoted elements: `'"test blah"@example.org'`
1405
                 *  * numeric TLDs: `a@b.123`
1406
                 *  * unbracketed IPv4 literals: `a@192.168.0.1`
1407
                 *  * IPv6 literals: 'first.last@[IPv6:a1::]'
1408
                 * Not all of these will necessarily work for sending!
1409
                 *
1410
                 * @see       http://squiloople.com/2009/12/20/email-address-validation/
1411
                 * @copyright 2009-2010 Michael Rushton
1412
                 * Feel free to use and redistribute this code. But please keep this copyright notice.
1413
                 */
1414
                return (bool) preg_match(
1415
                    '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
1416
                    '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
1417
                    '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
1418
                    '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
1419
                    '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
1420
                    '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
1421
                    '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
1422
                    '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
1423
                    '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
1424
                    $address
1425
                );
1426
            case 'html5':
1427
                /*
1428
                 * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
1429
                 *
1430
                 * @see https://html.spec.whatwg.org/#e-mail-state-(type=email)
1431
                 */
1432
                return (bool) preg_match(
1433
                    '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
1434
                    '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
1435
                    $address
1436
                );
1437
            case 'php':
1438
            default:
1439
                return filter_var($address, FILTER_VALIDATE_EMAIL) !== false;
1440
        }
1441
    }
1442
 
1443
    /**
1444
     * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the
1445
     * `intl` and `mbstring` PHP extensions.
1446
     *
1447
     * @return bool `true` if required functions for IDN support are present
1448
     */
1449
    public static function idnSupported()
1450
    {
1451
        return function_exists('idn_to_ascii') && function_exists('mb_convert_encoding');
1452
    }
1453
 
1454
    /**
1455
     * Converts IDN in given email address to its ASCII form, also known as punycode, if possible.
1456
     * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet.
1457
     * This function silently returns unmodified address if:
1458
     * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
1459
     * - Conversion to punycode is impossible (e.g. required PHP functions are not available)
1460
     *   or fails for any reason (e.g. domain contains characters not allowed in an IDN).
1461
     *
1462
     * @see PHPMailer::$CharSet
1463
     *
1464
     * @param string $address The email address to convert
1465
     *
1466
     * @return string The encoded address in ASCII form
1467
     */
1468
    public function punyencodeAddress($address)
1469
    {
1470
        //Verify we have required functions, CharSet, and at-sign.
1471
        $pos = strrpos($address, '@');
1472
        if (
1473
            !empty($this->CharSet) &&
1474
            false !== $pos &&
1475
            static::idnSupported()
1476
        ) {
1477
            $domain = substr($address, ++$pos);
1478
            //Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
1479
            if ($this->has8bitChars($domain) && @mb_check_encoding($domain, $this->CharSet)) {
1480
                //Convert the domain from whatever charset it's in to UTF-8
1481
                $domain = mb_convert_encoding($domain, self::CHARSET_UTF8, $this->CharSet);
1482
                //Ignore IDE complaints about this line - method signature changed in PHP 5.4
1483
                $errorcode = 0;
1484
                if (defined('INTL_IDNA_VARIANT_UTS46')) {
1485
                    //Use the current punycode standard (appeared in PHP 7.2)
1486
                    $punycode = idn_to_ascii(
1487
                        $domain,
1488
                        \IDNA_DEFAULT | \IDNA_USE_STD3_RULES | \IDNA_CHECK_BIDI |
1489
                            \IDNA_CHECK_CONTEXTJ | \IDNA_NONTRANSITIONAL_TO_ASCII,
1490
                        \INTL_IDNA_VARIANT_UTS46
1491
                    );
1492
                } elseif (defined('INTL_IDNA_VARIANT_2003')) {
1493
                    //Fall back to this old, deprecated/removed encoding
1494
                    $punycode = idn_to_ascii($domain, $errorcode, \INTL_IDNA_VARIANT_2003);
1495
                } else {
1496
                    //Fall back to a default we don't know about
1497
                    $punycode = idn_to_ascii($domain, $errorcode);
1498
                }
1499
                if (false !== $punycode) {
1500
                    return substr($address, 0, $pos) . $punycode;
1501
                }
1502
            }
1503
        }
1504
 
1505
        return $address;
1506
    }
1507
 
1508
    /**
1509
     * Create a message and send it.
1510
     * Uses the sending method specified by $Mailer.
1511
     *
1512
     * @throws Exception
1513
     *
1514
     * @return bool false on error - See the ErrorInfo property for details of the error
1515
     */
1516
    public function send()
1517
    {
1518
        try {
1519
            if (!$this->preSend()) {
1520
                return false;
1521
            }
1522
 
1523
            return $this->postSend();
1524
        } catch (Exception $exc) {
1525
            $this->mailHeader = '';
1526
            $this->setError($exc->getMessage());
1527
            if ($this->exceptions) {
1528
                throw $exc;
1529
            }
1530
 
1531
            return false;
1532
        }
1533
    }
1534
 
1535
    /**
1536
     * Prepare a message for sending.
1537
     *
1538
     * @throws Exception
1539
     *
1540
     * @return bool
1541
     */
1542
    public function preSend()
1543
    {
1544
        if (
1545
            'smtp' === $this->Mailer
1546
            || ('mail' === $this->Mailer && (\PHP_VERSION_ID >= 80000 || stripos(PHP_OS, 'WIN') === 0))
1547
        ) {
1548
            //SMTP mandates RFC-compliant line endings
1549
            //and it's also used with mail() on Windows
1550
            static::setLE(self::CRLF);
1551
        } else {
1552
            //Maintain backward compatibility with legacy Linux command line mailers
1553
            static::setLE(PHP_EOL);
1554
        }
1555
        //Check for buggy PHP versions that add a header with an incorrect line break
1556
        if (
1557
            'mail' === $this->Mailer
1558
            && ((\PHP_VERSION_ID >= 70000 && \PHP_VERSION_ID < 70017)
1559
                || (\PHP_VERSION_ID >= 70100 && \PHP_VERSION_ID < 70103))
1560
            && ini_get('mail.add_x_header') === '1'
1561
            && stripos(PHP_OS, 'WIN') === 0
1562
        ) {
1563
            trigger_error($this->lang('buggy_php'), E_USER_WARNING);
1564
        }
1565
 
1566
        try {
1567
            $this->error_count = 0; //Reset errors
1568
            $this->mailHeader = '';
1569
 
1570
            //Dequeue recipient and Reply-To addresses with IDN
1571
            foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
1572
                $params[1] = $this->punyencodeAddress($params[1]);
1573
                call_user_func_array([$this, 'addAnAddress'], $params);
1574
            }
1575
            if (count($this->to) + count($this->cc) + count($this->bcc) < 1) {
1576
                throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL);
1577
            }
1578
 
1579
            //Validate From, Sender, and ConfirmReadingTo addresses
1580
            foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) {
1581
                if ($this->{$address_kind} === null) {
1582
                    $this->{$address_kind} = '';
1583
                    continue;
1584
                }
1585
                $this->{$address_kind} = trim($this->{$address_kind});
1586
                if (empty($this->{$address_kind})) {
1587
                    continue;
1588
                }
1589
                $this->{$address_kind} = $this->punyencodeAddress($this->{$address_kind});
1590
                if (!static::validateAddress($this->{$address_kind})) {
1591
                    $error_message = sprintf(
1592
                        '%s (%s): %s',
1593
                        $this->lang('invalid_address'),
1594
                        $address_kind,
1595
                        $this->{$address_kind}
1596
                    );
1597
                    $this->setError($error_message);
1598
                    $this->edebug($error_message);
1599
                    if ($this->exceptions) {
1600
                        throw new Exception($error_message);
1601
                    }
1602
 
1603
                    return false;
1604
                }
1605
            }
1606
 
1607
            //Set whether the message is multipart/alternative
1608
            if ($this->alternativeExists()) {
1609
                $this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE;
1610
            }
1611
 
1612
            $this->setMessageType();
1613
            //Refuse to send an empty message unless we are specifically allowing it
1614
            if (!$this->AllowEmpty && empty($this->Body)) {
1615
                throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
1616
            }
1617
 
1618
            //Trim subject consistently
1619
            $this->Subject = trim($this->Subject);
1620
            //Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
1621
            $this->MIMEHeader = '';
1622
            $this->MIMEBody = $this->createBody();
1623
            //createBody may have added some headers, so retain them
1624
            $tempheaders = $this->MIMEHeader;
1625
            $this->MIMEHeader = $this->createHeader();
1626
            $this->MIMEHeader .= $tempheaders;
1627
 
1628
            //To capture the complete message when using mail(), create
1629
            //an extra header list which createHeader() doesn't fold in
1630
            if ('mail' === $this->Mailer) {
1631
                if (count($this->to) > 0) {
1632
                    $this->mailHeader .= $this->addrAppend('To', $this->to);
1633
                } else {
1634
                    $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
1635
                }
1636
                $this->mailHeader .= $this->headerLine(
1637
                    'Subject',
1638
                    $this->encodeHeader($this->secureHeader($this->Subject))
1639
                );
1640
            }
1641
 
1642
            //Sign with DKIM if enabled
1643
            if (
1644
                !empty($this->DKIM_domain)
1645
                && !empty($this->DKIM_selector)
1646
                && (!empty($this->DKIM_private_string)
1647
                    || (!empty($this->DKIM_private)
1648
                        && static::isPermittedPath($this->DKIM_private)
1649
                        && file_exists($this->DKIM_private)
1650
                    )
1651
                )
1652
            ) {
1653
                $header_dkim = $this->DKIM_Add(
1654
                    $this->MIMEHeader . $this->mailHeader,
1655
                    $this->encodeHeader($this->secureHeader($this->Subject)),
1656
                    $this->MIMEBody
1657
                );
1658
                $this->MIMEHeader = static::stripTrailingWSP($this->MIMEHeader) . static::$LE .
1659
                    static::normalizeBreaks($header_dkim) . static::$LE;
1660
            }
1661
 
1662
            return true;
1663
        } catch (Exception $exc) {
1664
            $this->setError($exc->getMessage());
1665
            if ($this->exceptions) {
1666
                throw $exc;
1667
            }
1668
 
1669
            return false;
1670
        }
1671
    }
1672
 
1673
    /**
1674
     * Actually send a message via the selected mechanism.
1675
     *
1676
     * @throws Exception
1677
     *
1678
     * @return bool
1679
     */
1680
    public function postSend()
1681
    {
1682
        try {
1683
            //Choose the mailer and send through it
1684
            switch ($this->Mailer) {
1685
                case 'sendmail':
1686
                case 'qmail':
1687
                    return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
1688
                case 'smtp':
1689
                    return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
1690
                case 'mail':
1691
                    return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1692
                default:
1693
                    $sendMethod = $this->Mailer . 'Send';
1694
                    if (method_exists($this, $sendMethod)) {
1695
                        return $this->{$sendMethod}($this->MIMEHeader, $this->MIMEBody);
1696
                    }
1697
 
1698
                    return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1699
            }
1700
        } catch (Exception $exc) {
1701
            $this->setError($exc->getMessage());
1702
            $this->edebug($exc->getMessage());
1703
            if ($this->Mailer === 'smtp' && $this->SMTPKeepAlive == true && $this->smtp->connected()) {
1704
                $this->smtp->reset();
1705
            }
1706
            if ($this->exceptions) {
1707
                throw $exc;
1708
            }
1709
        }
1710
 
1711
        return false;
1712
    }
1713
 
1714
    /**
1715
     * Send mail using the $Sendmail program.
1716
     *
1717
     * @see PHPMailer::$Sendmail
1718
     *
1719
     * @param string $header The message headers
1720
     * @param string $body   The message body
1721
     *
1722
     * @throws Exception
1723
     *
1724
     * @return bool
1725
     */
1726
    protected function sendmailSend($header, $body)
1727
    {
1728
        if ($this->Mailer === 'qmail') {
1729
            $this->edebug('Sending with qmail');
1730
        } else {
1731
            $this->edebug('Sending with sendmail');
1732
        }
1733
        $header = static::stripTrailingWSP($header) . static::$LE . static::$LE;
1734
        //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
1735
        //A space after `-f` is optional, but there is a long history of its presence
1736
        //causing problems, so we don't use one
1737
        //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
1738
        //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html
1739
        //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html
1740
        //Example problem: https://www.drupal.org/node/1057954
1741
 
1742
        //PHP 5.6 workaround
1743
        $sendmail_from_value = ini_get('sendmail_from');
1744
        if (empty($this->Sender) && !empty($sendmail_from_value)) {
1745
            //PHP config has a sender address we can use
1746
            $this->Sender = ini_get('sendmail_from');
1747
        }
1748
        //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1749
        if (!empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) {
1750
            if ($this->Mailer === 'qmail') {
1751
                $sendmailFmt = '%s -f%s';
1752
            } else {
1753
                $sendmailFmt = '%s -oi -f%s -t';
1754
            }
1755
        } else {
1756
            //allow sendmail to choose a default envelope sender. It may
1757
            //seem preferable to force it to use the From header as with
1758
            //SMTP, but that introduces new problems (see
1759
            //<https://github.com/PHPMailer/PHPMailer/issues/2298>), and
1760
            //it has historically worked this way.
1761
            $sendmailFmt = '%s -oi -t';
1762
        }
1763
 
1764
        $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);
1765
        $this->edebug('Sendmail path: ' . $this->Sendmail);
1766
        $this->edebug('Sendmail command: ' . $sendmail);
1767
        $this->edebug('Envelope sender: ' . $this->Sender);
1768
        $this->edebug("Headers: {$header}");
1769
 
1770
        if ($this->SingleTo) {
1771
            foreach ($this->SingleToArray as $toAddr) {
1772
                $mail = @popen($sendmail, 'w');
1773
                if (!$mail) {
1774
                    throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1775
                }
1776
                $this->edebug("To: {$toAddr}");
1777
                fwrite($mail, 'To: ' . $toAddr . "\n");
1778
                fwrite($mail, $header);
1779
                fwrite($mail, $body);
1780
                $result = pclose($mail);
1781
                $addrinfo = static::parseAddresses($toAddr, true, $this->CharSet);
1782
                $this->doCallback(
1783
                    ($result === 0),
1784
                    [[$addrinfo['address'], $addrinfo['name']]],
1785
                    $this->cc,
1786
                    $this->bcc,
1787
                    $this->Subject,
1788
                    $body,
1789
                    $this->From,
1790
                    []
1791
                );
1792
                $this->edebug("Result: " . ($result === 0 ? 'true' : 'false'));
1793
                if (0 !== $result) {
1794
                    throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1795
                }
1796
            }
1797
        } else {
1798
            $mail = @popen($sendmail, 'w');
1799
            if (!$mail) {
1800
                throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1801
            }
1802
            fwrite($mail, $header);
1803
            fwrite($mail, $body);
1804
            $result = pclose($mail);
1805
            $this->doCallback(
1806
                ($result === 0),
1807
                $this->to,
1808
                $this->cc,
1809
                $this->bcc,
1810
                $this->Subject,
1811
                $body,
1812
                $this->From,
1813
                []
1814
            );
1815
            $this->edebug("Result: " . ($result === 0 ? 'true' : 'false'));
1816
            if (0 !== $result) {
1817
                throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1818
            }
1819
        }
1820
 
1821
        return true;
1822
    }
1823
 
1824
    /**
1825
     * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters.
1826
     * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows.
1827
     *
1828
     * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report
1829
     *
1830
     * @param string $string The string to be validated
1831
     *
1832
     * @return bool
1833
     */
1834
    protected static function isShellSafe($string)
1835
    {
1836
        //It's not possible to use shell commands safely (which includes the mail() function) without escapeshellarg,
1837
        //but some hosting providers disable it, creating a security problem that we don't want to have to deal with,
1838
        //so we don't.
1839
        if (!function_exists('escapeshellarg') || !function_exists('escapeshellcmd')) {
1840
            return false;
1841
        }
1842
 
1843
        if (
1844
            escapeshellcmd($string) !== $string
1845
            || !in_array(escapeshellarg($string), ["'$string'", "\"$string\""])
1846
        ) {
1847
            return false;
1848
        }
1849
 
1850
        $length = strlen($string);
1851
 
1852
        for ($i = 0; $i < $length; ++$i) {
1853
            $c = $string[$i];
1854
 
1855
            //All other characters have a special meaning in at least one common shell, including = and +.
1856
            //Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
1857
            //Note that this does permit non-Latin alphanumeric characters based on the current locale.
1858
            if (!ctype_alnum($c) && strpos('@_-.', $c) === false) {
1859
                return false;
1860
            }
1861
        }
1862
 
1863
        return true;
1864
    }
1865
 
1866
    /**
1867
     * Check whether a file path is of a permitted type.
1868
     * Used to reject URLs and phar files from functions that access local file paths,
1869
     * such as addAttachment.
1870
     *
1871
     * @param string $path A relative or absolute path to a file
1872
     *
1873
     * @return bool
1874
     */
1875
    protected static function isPermittedPath($path)
1876
    {
1877
        //Matches scheme definition from https://tools.ietf.org/html/rfc3986#section-3.1
1878
        return !preg_match('#^[a-z][a-z\d+.-]*://#i', $path);
1879
    }
1880
 
1881
    /**
1882
     * Check whether a file path is safe, accessible, and readable.
1883
     *
1884
     * @param string $path A relative or absolute path to a file
1885
     *
1886
     * @return bool
1887
     */
1888
    protected static function fileIsAccessible($path)
1889
    {
1890
        if (!static::isPermittedPath($path)) {
1891
            return false;
1892
        }
1893
        $readable = is_file($path);
1894
        //If not a UNC path (expected to start with \\), check read permission, see #2069
1895
        if (strpos($path, '\\\\') !== 0) {
1896
            $readable = $readable && is_readable($path);
1897
        }
1898
        return  $readable;
1899
    }
1900
 
1901
    /**
1902
     * Send mail using the PHP mail() function.
1903
     *
1904
     * @see http://www.php.net/manual/en/book.mail.php
1905
     *
1906
     * @param string $header The message headers
1907
     * @param string $body   The message body
1908
     *
1909
     * @throws Exception
1910
     *
1911
     * @return bool
1912
     */
1913
    protected function mailSend($header, $body)
1914
    {
1915
        $header = static::stripTrailingWSP($header) . static::$LE . static::$LE;
1916
 
1917
        $toArr = [];
1918
        foreach ($this->to as $toaddr) {
1919
            $toArr[] = $this->addrFormat($toaddr);
1920
        }
1921
        $to = trim(implode(', ', $toArr));
1922
 
1923
        //If there are no To-addresses (e.g. when sending only to BCC-addresses)
1924
        //the following should be added to get a correct DKIM-signature.
1925
        //Compare with $this->preSend()
1926
        if ($to === '') {
1927
            $to = 'undisclosed-recipients:;';
1928
        }
1929
 
1930
        $params = null;
1931
        //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
1932
        //A space after `-f` is optional, but there is a long history of its presence
1933
        //causing problems, so we don't use one
1934
        //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
1935
        //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html
1936
        //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html
1937
        //Example problem: https://www.drupal.org/node/1057954
1938
        //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1939
 
1940
        //PHP 5.6 workaround
1941
        $sendmail_from_value = ini_get('sendmail_from');
1942
        if (empty($this->Sender) && !empty($sendmail_from_value)) {
1943
            //PHP config has a sender address we can use
1944
            $this->Sender = ini_get('sendmail_from');
1945
        }
1946
        if (!empty($this->Sender) && static::validateAddress($this->Sender)) {
1947
            if (self::isShellSafe($this->Sender)) {
1948
                $params = sprintf('-f%s', $this->Sender);
1949
            }
1950
            $old_from = ini_get('sendmail_from');
1951
            ini_set('sendmail_from', $this->Sender);
1952
        }
1953
        $result = false;
1954
        if ($this->SingleTo && count($toArr) > 1) {
1955
            foreach ($toArr as $toAddr) {
1956
                $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
1957
                $addrinfo = static::parseAddresses($toAddr, true, $this->CharSet);
1958
                $this->doCallback(
1959
                    $result,
1960
                    [[$addrinfo['address'], $addrinfo['name']]],
1961
                    $this->cc,
1962
                    $this->bcc,
1963
                    $this->Subject,
1964
                    $body,
1965
                    $this->From,
1966
                    []
1967
                );
1968
            }
1969
        } else {
1970
            $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
1971
            $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);
1972
        }
1973
        if (isset($old_from)) {
1974
            ini_set('sendmail_from', $old_from);
1975
        }
1976
        if (!$result) {
1977
            throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL);
1978
        }
1979
 
1980
        return true;
1981
    }
1982
 
1983
    /**
1984
     * Get an instance to use for SMTP operations.
1985
     * Override this function to load your own SMTP implementation,
1986
     * or set one with setSMTPInstance.
1987
     *
1988
     * @return SMTP
1989
     */
1990
    public function getSMTPInstance()
1991
    {
1992
        if (!is_object($this->smtp)) {
1993
            $this->smtp = new SMTP();
1994
        }
1995
 
1996
        return $this->smtp;
1997
    }
1998
 
1999
    /**
2000
     * Provide an instance to use for SMTP operations.
2001
     *
2002
     * @return SMTP
2003
     */
2004
    public function setSMTPInstance(SMTP $smtp)
2005
    {
2006
        $this->smtp = $smtp;
2007
 
2008
        return $this->smtp;
2009
    }
2010
 
2011
    /**
2012
     * Provide SMTP XCLIENT attributes
2013
     *
2014
     * @param string $name  Attribute name
2015
     * @param ?string $value Attribute value
2016
     *
2017
     * @return bool
2018
     */
2019
    public function setSMTPXclientAttribute($name, $value)
2020
    {
2021
        if (!in_array($name, SMTP::$xclient_allowed_attributes)) {
2022
            return false;
2023
        }
2024
        if (isset($this->SMTPXClient[$name]) && $value === null) {
2025
            unset($this->SMTPXClient[$name]);
2026
        } elseif ($value !== null) {
2027
            $this->SMTPXClient[$name] = $value;
2028
        }
2029
 
2030
        return true;
2031
    }
2032
 
2033
    /**
2034
     * Get SMTP XCLIENT attributes
2035
     *
2036
     * @return array
2037
     */
2038
    public function getSMTPXclientAttributes()
2039
    {
2040
        return $this->SMTPXClient;
2041
    }
2042
 
2043
    /**
2044
     * Send mail via SMTP.
2045
     * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
2046
     *
2047
     * @see PHPMailer::setSMTPInstance() to use a different class.
2048
     *
2049
     * @uses \PHPMailer\PHPMailer\SMTP
2050
     *
2051
     * @param string $header The message headers
2052
     * @param string $body   The message body
2053
     *
2054
     * @throws Exception
2055
     *
2056
     * @return bool
2057
     */
2058
    protected function smtpSend($header, $body)
2059
    {
2060
        $header = static::stripTrailingWSP($header) . static::$LE . static::$LE;
2061
        $bad_rcpt = [];
2062
        if (!$this->smtpConnect($this->SMTPOptions)) {
2063
            throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
2064
        }
2065
        //Sender already validated in preSend()
2066
        if ('' === $this->Sender) {
2067
            $smtp_from = $this->From;
2068
        } else {
2069
            $smtp_from = $this->Sender;
2070
        }
2071
        if (count($this->SMTPXClient)) {
2072
            $this->smtp->xclient($this->SMTPXClient);
2073
        }
2074
        if (!$this->smtp->mail($smtp_from)) {
2075
            $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
2076
            throw new Exception($this->ErrorInfo, self::STOP_CRITICAL);
2077
        }
2078
 
2079
        $callbacks = [];
2080
        //Attempt to send to all recipients
2081
        foreach ([$this->to, $this->cc, $this->bcc] as $togroup) {
2082
            foreach ($togroup as $to) {
2083
                if (!$this->smtp->recipient($to[0], $this->dsn)) {
2084
                    $error = $this->smtp->getError();
2085
                    $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']];
2086
                    $isSent = false;
2087
                } else {
2088
                    $isSent = true;
2089
                }
2090
 
2091
                $callbacks[] = ['issent' => $isSent, 'to' => $to[0], 'name' => $to[1]];
2092
            }
2093
        }
2094
 
2095
        //Only send the DATA command if we have viable recipients
2096
        if ((count($this->all_recipients) > count($bad_rcpt)) && !$this->smtp->data($header . $body)) {
2097
            throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL);
2098
        }
2099
 
2100
        $smtp_transaction_id = $this->smtp->getLastTransactionID();
2101
 
2102
        if ($this->SMTPKeepAlive) {
2103
            $this->smtp->reset();
2104
        } else {
2105
            $this->smtp->quit();
2106
            $this->smtp->close();
2107
        }
2108
 
2109
        foreach ($callbacks as $cb) {
2110
            $this->doCallback(
2111
                $cb['issent'],
2112
                [[$cb['to'], $cb['name']]],
2113
                [],
2114
                [],
2115
                $this->Subject,
2116
                $body,
2117
                $this->From,
2118
                ['smtp_transaction_id' => $smtp_transaction_id]
2119
            );
2120
        }
2121
 
2122
        //Create error message for any bad addresses
2123
        if (count($bad_rcpt) > 0) {
2124
            $errstr = '';
2125
            foreach ($bad_rcpt as $bad) {
2126
                $errstr .= $bad['to'] . ': ' . $bad['error'];
2127
            }
2128
            throw new Exception($this->lang('recipients_failed') . $errstr, self::STOP_CONTINUE);
2129
        }
2130
 
2131
        return true;
2132
    }
2133
 
2134
    /**
2135
     * Initiate a connection to an SMTP server.
2136
     * Returns false if the operation failed.
2137
     *
2138
     * @param array $options An array of options compatible with stream_context_create()
2139
     *
2140
     * @throws Exception
2141
     *
2142
     * @uses \PHPMailer\PHPMailer\SMTP
2143
     *
2144
     * @return bool
2145
     */
2146
    public function smtpConnect($options = null)
2147
    {
2148
        if (null === $this->smtp) {
2149
            $this->smtp = $this->getSMTPInstance();
2150
        }
2151
 
2152
        //If no options are provided, use whatever is set in the instance
2153
        if (null === $options) {
2154
            $options = $this->SMTPOptions;
2155
        }
2156
 
2157
        //Already connected?
2158
        if ($this->smtp->connected()) {
2159
            return true;
2160
        }
2161
 
2162
        $this->smtp->setTimeout($this->Timeout);
2163
        $this->smtp->setDebugLevel($this->SMTPDebug);
2164
        $this->smtp->setDebugOutput($this->Debugoutput);
2165
        $this->smtp->setVerp($this->do_verp);
2166
        if ($this->Host === null) {
2167
            $this->Host = 'localhost';
2168
        }
2169
        $hosts = explode(';', $this->Host);
2170
        $lastexception = null;
2171
 
2172
        foreach ($hosts as $hostentry) {
2173
            $hostinfo = [];
2174
            if (
2175
                !preg_match(
2176
                    '/^(?:(ssl|tls):\/\/)?(.+?)(?::(\d+))?$/',
2177
                    trim($hostentry),
2178
                    $hostinfo
2179
                )
2180
            ) {
2181
                $this->edebug($this->lang('invalid_hostentry') . ' ' . trim($hostentry));
2182
                //Not a valid host entry
2183
                continue;
2184
            }
2185
            //$hostinfo[1]: optional ssl or tls prefix
2186
            //$hostinfo[2]: the hostname
2187
            //$hostinfo[3]: optional port number
2188
            //The host string prefix can temporarily override the current setting for SMTPSecure
2189
            //If it's not specified, the default value is used
2190
 
2191
            //Check the host name is a valid name or IP address before trying to use it
2192
            if (!static::isValidHost($hostinfo[2])) {
2193
                $this->edebug($this->lang('invalid_host') . ' ' . $hostinfo[2]);
2194
                continue;
2195
            }
2196
            $prefix = '';
2197
            $secure = $this->SMTPSecure;
2198
            $tls = (static::ENCRYPTION_STARTTLS === $this->SMTPSecure);
2199
            if ('ssl' === $hostinfo[1] || ('' === $hostinfo[1] && static::ENCRYPTION_SMTPS === $this->SMTPSecure)) {
2200
                $prefix = 'ssl://';
2201
                $tls = false; //Can't have SSL and TLS at the same time
2202
                $secure = static::ENCRYPTION_SMTPS;
2203
            } elseif ('tls' === $hostinfo[1]) {
2204
                $tls = true;
2205
                //TLS doesn't use a prefix
2206
                $secure = static::ENCRYPTION_STARTTLS;
2207
            }
2208
            //Do we need the OpenSSL extension?
2209
            $sslext = defined('OPENSSL_ALGO_SHA256');
2210
            if (static::ENCRYPTION_STARTTLS === $secure || static::ENCRYPTION_SMTPS === $secure) {
2211
                //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
2212
                if (!$sslext) {
2213
                    throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL);
2214
                }
2215
            }
2216
            $host = $hostinfo[2];
2217
            $port = $this->Port;
2218
            if (
2219
                array_key_exists(3, $hostinfo) &&
2220
                is_numeric($hostinfo[3]) &&
2221
                $hostinfo[3] > 0 &&
2222
                $hostinfo[3] < 65536
2223
            ) {
2224
                $port = (int) $hostinfo[3];
2225
            }
2226
            if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
2227
                try {
2228
                    if ($this->Helo) {
2229
                        $hello = $this->Helo;
2230
                    } else {
2231
                        $hello = $this->serverHostname();
2232
                    }
2233
                    $this->smtp->hello($hello);
2234
                    //Automatically enable TLS encryption if:
2235
                    //* it's not disabled
2236
                    //* we are not connecting to localhost
2237
                    //* we have openssl extension
2238
                    //* we are not already using SSL
2239
                    //* the server offers STARTTLS
2240
                    if (
2241
                        $this->SMTPAutoTLS &&
2242
                        $this->Host !== 'localhost' &&
2243
                        $sslext &&
2244
                        $secure !== 'ssl' &&
2245
                        $this->smtp->getServerExt('STARTTLS')
2246
                    ) {
2247
                        $tls = true;
2248
                    }
2249
                    if ($tls) {
2250
                        if (!$this->smtp->startTLS()) {
2251
                            $message = $this->getSmtpErrorMessage('connect_host');
2252
                            throw new Exception($message);
2253
                        }
2254
                        //We must resend EHLO after TLS negotiation
2255
                        $this->smtp->hello($hello);
2256
                    }
2257
                    if (
2258
                        $this->SMTPAuth && !$this->smtp->authenticate(
2259
                            $this->Username,
2260
                            $this->Password,
2261
                            $this->AuthType,
2262
                            $this->oauth
2263
                        )
2264
                    ) {
2265
                        throw new Exception($this->lang('authenticate'));
2266
                    }
2267
 
2268
                    return true;
2269
                } catch (Exception $exc) {
2270
                    $lastexception = $exc;
2271
                    $this->edebug($exc->getMessage());
2272
                    //We must have connected, but then failed TLS or Auth, so close connection nicely
2273
                    $this->smtp->quit();
2274
                }
2275
            }
2276
        }
2277
        //If we get here, all connection attempts have failed, so close connection hard
2278
        $this->smtp->close();
2279
        //As we've caught all exceptions, just report whatever the last one was
2280
        if ($this->exceptions && null !== $lastexception) {
2281
            throw $lastexception;
2282
        }
2283
        if ($this->exceptions) {
2284
            // no exception was thrown, likely $this->smtp->connect() failed
2285
            $message = $this->getSmtpErrorMessage('connect_host');
2286
            throw new Exception($message);
2287
        }
2288
 
2289
        return false;
2290
    }
2291
 
2292
    /**
2293
     * Close the active SMTP session if one exists.
2294
     */
2295
    public function smtpClose()
2296
    {
2297
        if ((null !== $this->smtp) && $this->smtp->connected()) {
2298
            $this->smtp->quit();
2299
            $this->smtp->close();
2300
        }
2301
    }
2302
 
2303
    /**
2304
     * Set the language for error messages.
2305
     * The default language is English.
2306
     *
2307
     * @param string $langcode  ISO 639-1 2-character language code (e.g. French is "fr")
2308
     *                          Optionally, the language code can be enhanced with a 4-character
2309
     *                          script annotation and/or a 2-character country annotation.
2310
     * @param string $lang_path Path to the language file directory, with trailing separator (slash)
2311
     *                          Do not set this from user input!
2312
     *
2313
     * @return bool Returns true if the requested language was loaded, false otherwise.
2314
     */
2315
    public function setLanguage($langcode = 'en', $lang_path = '')
2316
    {
2317
        //Backwards compatibility for renamed language codes
2318
        $renamed_langcodes = [
2319
            'br' => 'pt_br',
2320
            'cz' => 'cs',
2321
            'dk' => 'da',
2322
            'no' => 'nb',
2323
            'se' => 'sv',
2324
            'rs' => 'sr',
2325
            'tg' => 'tl',
2326
            'am' => 'hy',
2327
        ];
2328
 
2329
        if (array_key_exists($langcode, $renamed_langcodes)) {
2330
            $langcode = $renamed_langcodes[$langcode];
2331
        }
2332
 
2333
        //Define full set of translatable strings in English
2334
        $PHPMAILER_LANG = [
2335
            'authenticate' => 'SMTP Error: Could not authenticate.',
2336
            'buggy_php' => 'Your version of PHP is affected by a bug that may result in corrupted messages.' .
2337
                ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' .
2338
                ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.',
2339
            'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
2340
            'data_not_accepted' => 'SMTP Error: data not accepted.',
2341
            'empty_message' => 'Message body empty',
2342
            'encoding' => 'Unknown encoding: ',
2343
            'execute' => 'Could not execute: ',
2344
            'extension_missing' => 'Extension missing: ',
2345
            'file_access' => 'Could not access file: ',
2346
            'file_open' => 'File Error: Could not open file: ',
2347
            'from_failed' => 'The following From address failed: ',
2348
            'instantiate' => 'Could not instantiate mail function.',
2349
            'invalid_address' => 'Invalid address: ',
2350
            'invalid_header' => 'Invalid header name or value',
2351
            'invalid_hostentry' => 'Invalid hostentry: ',
2352
            'invalid_host' => 'Invalid host: ',
2353
            'mailer_not_supported' => ' mailer is not supported.',
2354
            'provide_address' => 'You must provide at least one recipient email address.',
2355
            'recipients_failed' => 'SMTP Error: The following recipients failed: ',
2356
            'signing' => 'Signing Error: ',
2357
            'smtp_code' => 'SMTP code: ',
2358
            'smtp_code_ex' => 'Additional SMTP info: ',
2359
            'smtp_connect_failed' => 'SMTP connect() failed.',
2360
            'smtp_detail' => 'Detail: ',
2361
            'smtp_error' => 'SMTP server error: ',
2362
            'variable_set' => 'Cannot set or reset variable: ',
2363
        ];
2364
        if (empty($lang_path)) {
2365
            //Calculate an absolute path so it can work if CWD is not here
2366
            $lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR;
2367
        }
2368
 
2369
        //Validate $langcode
2370
        $foundlang = true;
2371
        $langcode  = strtolower($langcode);
2372
        if (
2373
            !preg_match('/^(?P<lang>[a-z]{2})(?P<script>_[a-z]{4})?(?P<country>_[a-z]{2})?$/', $langcode, $matches)
2374
            && $langcode !== 'en'
2375
        ) {
2376
            $foundlang = false;
2377
            $langcode = 'en';
2378
        }
2379
 
2380
        //There is no English translation file
2381
        if ('en' !== $langcode) {
2382
            $langcodes = [];
2383
            if (!empty($matches['script']) && !empty($matches['country'])) {
2384
                $langcodes[] = $matches['lang'] . $matches['script'] . $matches['country'];
2385
            }
2386
            if (!empty($matches['country'])) {
2387
                $langcodes[] = $matches['lang'] . $matches['country'];
2388
            }
2389
            if (!empty($matches['script'])) {
2390
                $langcodes[] = $matches['lang'] . $matches['script'];
2391
            }
2392
            $langcodes[] = $matches['lang'];
2393
 
2394
            //Try and find a readable language file for the requested language.
2395
            $foundFile = false;
2396
            foreach ($langcodes as $code) {
2397
                $lang_file = $lang_path . 'phpmailer.lang-' . $code . '.php';
2398
                if (static::fileIsAccessible($lang_file)) {
2399
                    $foundFile = true;
2400
                    break;
2401
                }
2402
            }
2403
 
2404
            if ($foundFile === false) {
2405
                $foundlang = false;
2406
            } else {
2407
                $lines = file($lang_file);
2408
                foreach ($lines as $line) {
2409
                    //Translation file lines look like this:
2410
                    //$PHPMAILER_LANG['authenticate'] = 'SMTP-Fehler: Authentifizierung fehlgeschlagen.';
2411
                    //These files are parsed as text and not PHP so as to avoid the possibility of code injection
2412
                    //See https://blog.stevenlevithan.com/archives/match-quoted-string
2413
                    $matches = [];
2414
                    if (
2415
                        preg_match(
2416
                            '/^\$PHPMAILER_LANG\[\'([a-z\d_]+)\'\]\s*=\s*(["\'])(.+)*?\2;/',
2417
                            $line,
2418
                            $matches
2419
                        ) &&
2420
                        //Ignore unknown translation keys
2421
                        array_key_exists($matches[1], $PHPMAILER_LANG)
2422
                    ) {
2423
                        //Overwrite language-specific strings so we'll never have missing translation keys.
2424
                        $PHPMAILER_LANG[$matches[1]] = (string)$matches[3];
2425
                    }
2426
                }
2427
            }
2428
        }
2429
        $this->language = $PHPMAILER_LANG;
2430
 
2431
        return $foundlang; //Returns false if language not found
2432
    }
2433
 
2434
    /**
2435
     * Get the array of strings for the current language.
2436
     *
2437
     * @return array
2438
     */
2439
    public function getTranslations()
2440
    {
2441
        if (empty($this->language)) {
2442
            $this->setLanguage(); // Set the default language.
2443
        }
2444
 
2445
        return $this->language;
2446
    }
2447
 
2448
    /**
2449
     * Create recipient headers.
2450
     *
2451
     * @param string $type
2452
     * @param array  $addr An array of recipients,
2453
     *                     where each recipient is a 2-element indexed array with element 0 containing an address
2454
     *                     and element 1 containing a name, like:
2455
     *                     [['joe@example.com', 'Joe User'], ['zoe@example.com', 'Zoe User']]
2456
     *
2457
     * @return string
2458
     */
2459
    public function addrAppend($type, $addr)
2460
    {
2461
        $addresses = [];
2462
        foreach ($addr as $address) {
2463
            $addresses[] = $this->addrFormat($address);
2464
        }
2465
 
2466
        return $type . ': ' . implode(', ', $addresses) . static::$LE;
2467
    }
2468
 
2469
    /**
2470
     * Format an address for use in a message header.
2471
     *
2472
     * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name like
2473
     *                    ['joe@example.com', 'Joe User']
2474
     *
2475
     * @return string
2476
     */
2477
    public function addrFormat($addr)
2478
    {
2479
        if (!isset($addr[1]) || ($addr[1] === '')) { //No name provided
2480
            return $this->secureHeader($addr[0]);
2481
        }
2482
 
2483
        return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') .
2484
            ' <' . $this->secureHeader($addr[0]) . '>';
2485
    }
2486
 
2487
    /**
2488
     * Word-wrap message.
2489
     * For use with mailers that do not automatically perform wrapping
2490
     * and for quoted-printable encoded messages.
2491
     * Original written by philippe.
2492
     *
2493
     * @param string $message The message to wrap
2494
     * @param int    $length  The line length to wrap to
2495
     * @param bool   $qp_mode Whether to run in Quoted-Printable mode
2496
     *
2497
     * @return string
2498
     */
2499
    public function wrapText($message, $length, $qp_mode = false)
2500
    {
2501
        if ($qp_mode) {
2502
            $soft_break = sprintf(' =%s', static::$LE);
2503
        } else {
2504
            $soft_break = static::$LE;
2505
        }
2506
        //If utf-8 encoding is used, we will need to make sure we don't
2507
        //split multibyte characters when we wrap
2508
        $is_utf8 = static::CHARSET_UTF8 === strtolower($this->CharSet);
2509
        $lelen = strlen(static::$LE);
2510
        $crlflen = strlen(static::$LE);
2511
 
2512
        $message = static::normalizeBreaks($message);
2513
        //Remove a trailing line break
2514
        if (substr($message, -$lelen) === static::$LE) {
2515
            $message = substr($message, 0, -$lelen);
2516
        }
2517
 
2518
        //Split message into lines
2519
        $lines = explode(static::$LE, $message);
2520
        //Message will be rebuilt in here
2521
        $message = '';
2522
        foreach ($lines as $line) {
2523
            $words = explode(' ', $line);
2524
            $buf = '';
2525
            $firstword = true;
2526
            foreach ($words as $word) {
2527
                if ($qp_mode && (strlen($word) > $length)) {
2528
                    $space_left = $length - strlen($buf) - $crlflen;
2529
                    if (!$firstword) {
2530
                        if ($space_left > 20) {
2531
                            $len = $space_left;
2532
                            if ($is_utf8) {
2533
                                $len = $this->utf8CharBoundary($word, $len);
2534
                            } elseif ('=' === substr($word, $len - 1, 1)) {
2535
                                --$len;
2536
                            } elseif ('=' === substr($word, $len - 2, 1)) {
2537
                                $len -= 2;
2538
                            }
2539
                            $part = substr($word, 0, $len);
2540
                            $word = substr($word, $len);
2541
                            $buf .= ' ' . $part;
2542
                            $message .= $buf . sprintf('=%s', static::$LE);
2543
                        } else {
2544
                            $message .= $buf . $soft_break;
2545
                        }
2546
                        $buf = '';
2547
                    }
2548
                    while ($word !== '') {
2549
                        if ($length <= 0) {
2550
                            break;
2551
                        }
2552
                        $len = $length;
2553
                        if ($is_utf8) {
2554
                            $len = $this->utf8CharBoundary($word, $len);
2555
                        } elseif ('=' === substr($word, $len - 1, 1)) {
2556
                            --$len;
2557
                        } elseif ('=' === substr($word, $len - 2, 1)) {
2558
                            $len -= 2;
2559
                        }
2560
                        $part = substr($word, 0, $len);
2561
                        $word = (string) substr($word, $len);
2562
 
2563
                        if ($word !== '') {
2564
                            $message .= $part . sprintf('=%s', static::$LE);
2565
                        } else {
2566
                            $buf = $part;
2567
                        }
2568
                    }
2569
                } else {
2570
                    $buf_o = $buf;
2571
                    if (!$firstword) {
2572
                        $buf .= ' ';
2573
                    }
2574
                    $buf .= $word;
2575
 
2576
                    if ('' !== $buf_o && strlen($buf) > $length) {
2577
                        $message .= $buf_o . $soft_break;
2578
                        $buf = $word;
2579
                    }
2580
                }
2581
                $firstword = false;
2582
            }
2583
            $message .= $buf . static::$LE;
2584
        }
2585
 
2586
        return $message;
2587
    }
2588
 
2589
    /**
2590
     * Find the last character boundary prior to $maxLength in a utf-8
2591
     * quoted-printable encoded string.
2592
     * Original written by Colin Brown.
2593
     *
2594
     * @param string $encodedText utf-8 QP text
2595
     * @param int    $maxLength   Find the last character boundary prior to this length
2596
     *
2597
     * @return int
2598
     */
2599
    public function utf8CharBoundary($encodedText, $maxLength)
2600
    {
2601
        $foundSplitPos = false;
2602
        $lookBack = 3;
2603
        while (!$foundSplitPos) {
2604
            $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
2605
            $encodedCharPos = strpos($lastChunk, '=');
2606
            if (false !== $encodedCharPos) {
2607
                //Found start of encoded character byte within $lookBack block.
2608
                //Check the encoded byte value (the 2 chars after the '=')
2609
                $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
2610
                $dec = hexdec($hex);
2611
                if ($dec < 128) {
2612
                    //Single byte character.
2613
                    //If the encoded char was found at pos 0, it will fit
2614
                    //otherwise reduce maxLength to start of the encoded char
2615
                    if ($encodedCharPos > 0) {
2616
                        $maxLength -= $lookBack - $encodedCharPos;
2617
                    }
2618
                    $foundSplitPos = true;
2619
                } elseif ($dec >= 192) {
2620
                    //First byte of a multi byte character
2621
                    //Reduce maxLength to split at start of character
2622
                    $maxLength -= $lookBack - $encodedCharPos;
2623
                    $foundSplitPos = true;
2624
                } elseif ($dec < 192) {
2625
                    //Middle byte of a multi byte character, look further back
2626
                    $lookBack += 3;
2627
                }
2628
            } else {
2629
                //No encoded character found
2630
                $foundSplitPos = true;
2631
            }
2632
        }
2633
 
2634
        return $maxLength;
2635
    }
2636
 
2637
    /**
2638
     * Apply word wrapping to the message body.
2639
     * Wraps the message body to the number of chars set in the WordWrap property.
2640
     * You should only do this to plain-text bodies as wrapping HTML tags may break them.
2641
     * This is called automatically by createBody(), so you don't need to call it yourself.
2642
     */
2643
    public function setWordWrap()
2644
    {
2645
        if ($this->WordWrap < 1) {
2646
            return;
2647
        }
2648
 
2649
        switch ($this->message_type) {
2650
            case 'alt':
2651
            case 'alt_inline':
2652
            case 'alt_attach':
2653
            case 'alt_inline_attach':
2654
                $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
2655
                break;
2656
            default:
2657
                $this->Body = $this->wrapText($this->Body, $this->WordWrap);
2658
                break;
2659
        }
2660
    }
2661
 
2662
    /**
2663
     * Assemble message headers.
2664
     *
2665
     * @return string The assembled headers
2666
     */
2667
    public function createHeader()
2668
    {
2669
        $result = '';
2670
 
2671
        $result .= $this->headerLine('Date', '' === $this->MessageDate ? self::rfcDate() : $this->MessageDate);
2672
 
2673
        //The To header is created automatically by mail(), so needs to be omitted here
2674
        if ('mail' !== $this->Mailer) {
2675
            if ($this->SingleTo) {
2676
                foreach ($this->to as $toaddr) {
2677
                    $this->SingleToArray[] = $this->addrFormat($toaddr);
2678
                }
2679
            } elseif (count($this->to) > 0) {
2680
                $result .= $this->addrAppend('To', $this->to);
2681
            } elseif (count($this->cc) === 0) {
2682
                $result .= $this->headerLine('To', 'undisclosed-recipients:;');
2683
            }
2684
        }
2685
        $result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]);
2686
 
2687
        //sendmail and mail() extract Cc from the header before sending
2688
        if (count($this->cc) > 0) {
2689
            $result .= $this->addrAppend('Cc', $this->cc);
2690
        }
2691
 
2692
        //sendmail and mail() extract Bcc from the header before sending
2693
        if (
2694
            (
2695
                'sendmail' === $this->Mailer || 'qmail' === $this->Mailer || 'mail' === $this->Mailer
2696
            )
2697
            && count($this->bcc) > 0
2698
        ) {
2699
            $result .= $this->addrAppend('Bcc', $this->bcc);
2700
        }
2701
 
2702
        if (count($this->ReplyTo) > 0) {
2703
            $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
2704
        }
2705
 
2706
        //mail() sets the subject itself
2707
        if ('mail' !== $this->Mailer) {
2708
            $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
2709
        }
2710
 
2711
        //Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4
2712
        //https://tools.ietf.org/html/rfc5322#section-3.6.4
2713
        if (
2714
            '' !== $this->MessageID &&
2715
            preg_match(
2716
                '/^<((([a-z\d!#$%&\'*+\/=?^_`{|}~-]+(\.[a-z\d!#$%&\'*+\/=?^_`{|}~-]+)*)' .
2717
                '|("(([\x01-\x08\x0B\x0C\x0E-\x1F\x7F]|[\x21\x23-\x5B\x5D-\x7E])' .
2718
                '|(\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*"))@(([a-z\d!#$%&\'*+\/=?^_`{|}~-]+' .
2719
                '(\.[a-z\d!#$%&\'*+\/=?^_`{|}~-]+)*)|(\[(([\x01-\x08\x0B\x0C\x0E-\x1F\x7F]' .
2720
                '|[\x21-\x5A\x5E-\x7E])|(\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*\])))>$/Di',
2721
                $this->MessageID
2722
            )
2723
        ) {
2724
            $this->lastMessageID = $this->MessageID;
2725
        } else {
2726
            $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());
2727
        }
2728
        $result .= $this->headerLine('Message-ID', $this->lastMessageID);
2729
        if (null !== $this->Priority) {
2730
            $result .= $this->headerLine('X-Priority', $this->Priority);
2731
        }
2732
        if ('' === $this->XMailer) {
2733
            //Empty string for default X-Mailer header
2734
            $result .= $this->headerLine(
2735
                'X-Mailer',
2736
                'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)'
2737
            );
2738
        } elseif (is_string($this->XMailer) && trim($this->XMailer) !== '') {
2739
            //Some string
2740
            $result .= $this->headerLine('X-Mailer', trim($this->XMailer));
2741
        } //Other values result in no X-Mailer header
2742
 
2743
        if ('' !== $this->ConfirmReadingTo) {
2744
            $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
2745
        }
2746
 
2747
        //Add custom headers
2748
        foreach ($this->CustomHeader as $header) {
2749
            $result .= $this->headerLine(
2750
                trim($header[0]),
2751
                $this->encodeHeader(trim($header[1]))
2752
            );
2753
        }
2754
        if (!$this->sign_key_file) {
2755
            $result .= $this->headerLine('MIME-Version', '1.0');
2756
            $result .= $this->getMailMIME();
2757
        }
2758
 
2759
        return $result;
2760
    }
2761
 
2762
    /**
2763
     * Get the message MIME type headers.
2764
     *
2765
     * @return string
2766
     */
2767
    public function getMailMIME()
2768
    {
2769
        $result = '';
2770
        $ismultipart = true;
2771
        switch ($this->message_type) {
2772
            case 'inline':
2773
                $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2774
                $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
2775
                break;
2776
            case 'attach':
2777
            case 'inline_attach':
2778
            case 'alt_attach':
2779
            case 'alt_inline_attach':
2780
                $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_MIXED . ';');
2781
                $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
2782
                break;
2783
            case 'alt':
2784
            case 'alt_inline':
2785
                $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
2786
                $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
2787
                break;
2788
            default:
2789
                //Catches case 'plain': and case '':
2790
                $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
2791
                $ismultipart = false;
2792
                break;
2793
        }
2794
        //RFC1341 part 5 says 7bit is assumed if not specified
2795
        if (static::ENCODING_7BIT !== $this->Encoding) {
2796
            //RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
2797
            if ($ismultipart) {
2798
                if (static::ENCODING_8BIT === $this->Encoding) {
2799
                    $result .= $this->headerLine('Content-Transfer-Encoding', static::ENCODING_8BIT);
2800
                }
2801
                //The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
2802
            } else {
2803
                $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
2804
            }
2805
        }
2806
 
2807
        return $result;
2808
    }
2809
 
2810
    /**
2811
     * Returns the whole MIME message.
2812
     * Includes complete headers and body.
2813
     * Only valid post preSend().
2814
     *
2815
     * @see PHPMailer::preSend()
2816
     *
2817
     * @return string
2818
     */
2819
    public function getSentMIMEMessage()
2820
    {
2821
        return static::stripTrailingWSP($this->MIMEHeader . $this->mailHeader) .
2822
            static::$LE . static::$LE . $this->MIMEBody;
2823
    }
2824
 
2825
    /**
2826
     * Create a unique ID to use for boundaries.
2827
     *
2828
     * @return string
2829
     */
2830
    protected function generateId()
2831
    {
2832
        $len = 32; //32 bytes = 256 bits
2833
        $bytes = '';
2834
        if (function_exists('random_bytes')) {
2835
            try {
2836
                $bytes = random_bytes($len);
2837
            } catch (\Exception $e) {
2838
                //Do nothing
2839
            }
2840
        } elseif (function_exists('openssl_random_pseudo_bytes')) {
2841
            /** @noinspection CryptographicallySecureRandomnessInspection */
2842
            $bytes = openssl_random_pseudo_bytes($len);
2843
        }
2844
        if ($bytes === '') {
2845
            //We failed to produce a proper random string, so make do.
2846
            //Use a hash to force the length to the same as the other methods
2847
            $bytes = hash('sha256', uniqid((string) mt_rand(), true), true);
2848
        }
2849
 
2850
        //We don't care about messing up base64 format here, just want a random string
2851
        return str_replace(['=', '+', '/'], '', base64_encode(hash('sha256', $bytes, true)));
2852
    }
2853
 
2854
    /**
2855
     * Assemble the message body.
2856
     * Returns an empty string on failure.
2857
     *
2858
     * @throws Exception
2859
     *
2860
     * @return string The assembled message body
2861
     */
2862
    public function createBody()
2863
    {
2864
        $body = '';
2865
        //Create unique IDs and preset boundaries
2866
        $this->setBoundaries();
2867
 
2868
        if ($this->sign_key_file) {
2869
            $body .= $this->getMailMIME() . static::$LE;
2870
        }
2871
 
2872
        $this->setWordWrap();
2873
 
2874
        $bodyEncoding = $this->Encoding;
2875
        $bodyCharSet = $this->CharSet;
2876
        //Can we do a 7-bit downgrade?
2877
        if (static::ENCODING_8BIT === $bodyEncoding && !$this->has8bitChars($this->Body)) {
2878
            $bodyEncoding = static::ENCODING_7BIT;
2879
            //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
2880
            $bodyCharSet = static::CHARSET_ASCII;
2881
        }
2882
        //If lines are too long, and we're not already using an encoding that will shorten them,
2883
        //change to quoted-printable transfer encoding for the body part only
2884
        if (static::ENCODING_BASE64 !== $this->Encoding && static::hasLineLongerThanMax($this->Body)) {
2885
            $bodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
2886
        }
2887
 
2888
        $altBodyEncoding = $this->Encoding;
2889
        $altBodyCharSet = $this->CharSet;
2890
        //Can we do a 7-bit downgrade?
2891
        if (static::ENCODING_8BIT === $altBodyEncoding && !$this->has8bitChars($this->AltBody)) {
2892
            $altBodyEncoding = static::ENCODING_7BIT;
2893
            //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
2894
            $altBodyCharSet = static::CHARSET_ASCII;
2895
        }
2896
        //If lines are too long, and we're not already using an encoding that will shorten them,
2897
        //change to quoted-printable transfer encoding for the alt body part only
2898
        if (static::ENCODING_BASE64 !== $altBodyEncoding && static::hasLineLongerThanMax($this->AltBody)) {
2899
            $altBodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
2900
        }
2901
        //Use this as a preamble in all multipart message types
2902
        $mimepre = '';
2903
        switch ($this->message_type) {
2904
            case 'inline':
2905
                $body .= $mimepre;
2906
                $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
2907
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2908
                $body .= static::$LE;
2909
                $body .= $this->attachAll('inline', $this->boundary[1]);
2910
                break;
2911
            case 'attach':
2912
                $body .= $mimepre;
2913
                $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
2914
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2915
                $body .= static::$LE;
2916
                $body .= $this->attachAll('attachment', $this->boundary[1]);
2917
                break;
2918
            case 'inline_attach':
2919
                $body .= $mimepre;
2920
                $body .= $this->textLine('--' . $this->boundary[1]);
2921
                $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2922
                $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";');
2923
                $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
2924
                $body .= static::$LE;
2925
                $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
2926
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2927
                $body .= static::$LE;
2928
                $body .= $this->attachAll('inline', $this->boundary[2]);
2929
                $body .= static::$LE;
2930
                $body .= $this->attachAll('attachment', $this->boundary[1]);
2931
                break;
2932
            case 'alt':
2933
                $body .= $mimepre;
2934
                $body .= $this->getBoundary(
2935
                    $this->boundary[1],
2936
                    $altBodyCharSet,
2937
                    static::CONTENT_TYPE_PLAINTEXT,
2938
                    $altBodyEncoding
2939
                );
2940
                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2941
                $body .= static::$LE;
2942
                $body .= $this->getBoundary(
2943
                    $this->boundary[1],
2944
                    $bodyCharSet,
2945
                    static::CONTENT_TYPE_TEXT_HTML,
2946
                    $bodyEncoding
2947
                );
2948
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2949
                $body .= static::$LE;
2950
                if (!empty($this->Ical)) {
2951
                    $method = static::ICAL_METHOD_REQUEST;
2952
                    foreach (static::$IcalMethods as $imethod) {
2953
                        if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) {
2954
                            $method = $imethod;
2955
                            break;
2956
                        }
2957
                    }
2958
                    $body .= $this->getBoundary(
2959
                        $this->boundary[1],
2960
                        '',
2961
                        static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method,
2962
                        ''
2963
                    );
2964
                    $body .= $this->encodeString($this->Ical, $this->Encoding);
2965
                    $body .= static::$LE;
2966
                }
2967
                $body .= $this->endBoundary($this->boundary[1]);
2968
                break;
2969
            case 'alt_inline':
2970
                $body .= $mimepre;
2971
                $body .= $this->getBoundary(
2972
                    $this->boundary[1],
2973
                    $altBodyCharSet,
2974
                    static::CONTENT_TYPE_PLAINTEXT,
2975
                    $altBodyEncoding
2976
                );
2977
                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2978
                $body .= static::$LE;
2979
                $body .= $this->textLine('--' . $this->boundary[1]);
2980
                $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2981
                $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";');
2982
                $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
2983
                $body .= static::$LE;
2984
                $body .= $this->getBoundary(
2985
                    $this->boundary[2],
2986
                    $bodyCharSet,
2987
                    static::CONTENT_TYPE_TEXT_HTML,
2988
                    $bodyEncoding
2989
                );
2990
                $body .= $this->encodeString($this->Body, $bodyEncoding);
2991
                $body .= static::$LE;
2992
                $body .= $this->attachAll('inline', $this->boundary[2]);
2993
                $body .= static::$LE;
2994
                $body .= $this->endBoundary($this->boundary[1]);
2995
                break;
2996
            case 'alt_attach':
2997
                $body .= $mimepre;
2998
                $body .= $this->textLine('--' . $this->boundary[1]);
2999
                $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
3000
                $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"');
3001
                $body .= static::$LE;
3002
                $body .= $this->getBoundary(
3003
                    $this->boundary[2],
3004
                    $altBodyCharSet,
3005
                    static::CONTENT_TYPE_PLAINTEXT,
3006
                    $altBodyEncoding
3007
                );
3008
                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
3009
                $body .= static::$LE;
3010
                $body .= $this->getBoundary(
3011
                    $this->boundary[2],
3012
                    $bodyCharSet,
3013
                    static::CONTENT_TYPE_TEXT_HTML,
3014
                    $bodyEncoding
3015
                );
3016
                $body .= $this->encodeString($this->Body, $bodyEncoding);
3017
                $body .= static::$LE;
3018
                if (!empty($this->Ical)) {
3019
                    $method = static::ICAL_METHOD_REQUEST;
3020
                    foreach (static::$IcalMethods as $imethod) {
3021
                        if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) {
3022
                            $method = $imethod;
3023
                            break;
3024
                        }
3025
                    }
3026
                    $body .= $this->getBoundary(
3027
                        $this->boundary[2],
3028
                        '',
3029
                        static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method,
3030
                        ''
3031
                    );
3032
                    $body .= $this->encodeString($this->Ical, $this->Encoding);
3033
                }
3034
                $body .= $this->endBoundary($this->boundary[2]);
3035
                $body .= static::$LE;
3036
                $body .= $this->attachAll('attachment', $this->boundary[1]);
3037
                break;
3038
            case 'alt_inline_attach':
3039
                $body .= $mimepre;
3040
                $body .= $this->textLine('--' . $this->boundary[1]);
3041
                $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
3042
                $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"');
3043
                $body .= static::$LE;
3044
                $body .= $this->getBoundary(
3045
                    $this->boundary[2],
3046
                    $altBodyCharSet,
3047
                    static::CONTENT_TYPE_PLAINTEXT,
3048
                    $altBodyEncoding
3049
                );
3050
                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
3051
                $body .= static::$LE;
3052
                $body .= $this->textLine('--' . $this->boundary[2]);
3053
                $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
3054
                $body .= $this->textLine(' boundary="' . $this->boundary[3] . '";');
3055
                $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
3056
                $body .= static::$LE;
3057
                $body .= $this->getBoundary(
3058
                    $this->boundary[3],
3059
                    $bodyCharSet,
3060
                    static::CONTENT_TYPE_TEXT_HTML,
3061
                    $bodyEncoding
3062
                );
3063
                $body .= $this->encodeString($this->Body, $bodyEncoding);
3064
                $body .= static::$LE;
3065
                $body .= $this->attachAll('inline', $this->boundary[3]);
3066
                $body .= static::$LE;
3067
                $body .= $this->endBoundary($this->boundary[2]);
3068
                $body .= static::$LE;
3069
                $body .= $this->attachAll('attachment', $this->boundary[1]);
3070
                break;
3071
            default:
3072
                //Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types
3073
                //Reset the `Encoding` property in case we changed it for line length reasons
3074
                $this->Encoding = $bodyEncoding;
3075
                $body .= $this->encodeString($this->Body, $this->Encoding);
3076
                break;
3077
        }
3078
 
3079
        if ($this->isError()) {
3080
            $body = '';
3081
            if ($this->exceptions) {
3082
                throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
3083
            }
3084
        } elseif ($this->sign_key_file) {
3085
            try {
3086
                if (!defined('PKCS7_TEXT')) {
3087
                    throw new Exception($this->lang('extension_missing') . 'openssl');
3088
                }
3089
 
3090
                $file = tempnam(sys_get_temp_dir(), 'srcsign');
3091
                $signed = tempnam(sys_get_temp_dir(), 'mailsign');
3092
                file_put_contents($file, $body);
3093
 
3094
                //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
3095
                if (empty($this->sign_extracerts_file)) {
3096
                    $sign = @openssl_pkcs7_sign(
3097
                        $file,
3098
                        $signed,
3099
                        'file://' . realpath($this->sign_cert_file),
3100
                        ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
3101
                        []
3102
                    );
3103
                } else {
3104
                    $sign = @openssl_pkcs7_sign(
3105
                        $file,
3106
                        $signed,
3107
                        'file://' . realpath($this->sign_cert_file),
3108
                        ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
3109
                        [],
3110
                        PKCS7_DETACHED,
3111
                        $this->sign_extracerts_file
3112
                    );
3113
                }
3114
 
3115
                @unlink($file);
3116
                if ($sign) {
3117
                    $body = file_get_contents($signed);
3118
                    @unlink($signed);
3119
                    //The message returned by openssl contains both headers and body, so need to split them up
3120
                    $parts = explode("\n\n", $body, 2);
3121
                    $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE;
3122
                    $body = $parts[1];
3123
                } else {
3124
                    @unlink($signed);
3125
                    throw new Exception($this->lang('signing') . openssl_error_string());
3126
                }
3127
            } catch (Exception $exc) {
3128
                $body = '';
3129
                if ($this->exceptions) {
3130
                    throw $exc;
3131
                }
3132
            }
3133
        }
3134
 
3135
        return $body;
3136
    }
3137
 
3138
    /**
3139
     * Get the boundaries that this message will use
3140
     * @return array
3141
     */
3142
    public function getBoundaries()
3143
    {
3144
        if (empty($this->boundary)) {
3145
            $this->setBoundaries();
3146
        }
3147
        return $this->boundary;
3148
    }
3149
 
3150
    /**
3151
     * Return the start of a message boundary.
3152
     *
3153
     * @param string $boundary
3154
     * @param string $charSet
3155
     * @param string $contentType
3156
     * @param string $encoding
3157
     *
3158
     * @return string
3159
     */
3160
    protected function getBoundary($boundary, $charSet, $contentType, $encoding)
3161
    {
3162
        $result = '';
3163
        if ('' === $charSet) {
3164
            $charSet = $this->CharSet;
3165
        }
3166
        if ('' === $contentType) {
3167
            $contentType = $this->ContentType;
3168
        }
3169
        if ('' === $encoding) {
3170
            $encoding = $this->Encoding;
3171
        }
3172
        $result .= $this->textLine('--' . $boundary);
3173
        $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
3174
        $result .= static::$LE;
3175
        //RFC1341 part 5 says 7bit is assumed if not specified
3176
        if (static::ENCODING_7BIT !== $encoding) {
3177
            $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
3178
        }
3179
        $result .= static::$LE;
3180
 
3181
        return $result;
3182
    }
3183
 
3184
    /**
3185
     * Return the end of a message boundary.
3186
     *
3187
     * @param string $boundary
3188
     *
3189
     * @return string
3190
     */
3191
    protected function endBoundary($boundary)
3192
    {
3193
        return static::$LE . '--' . $boundary . '--' . static::$LE;
3194
    }
3195
 
3196
    /**
3197
     * Set the message type.
3198
     * PHPMailer only supports some preset message types, not arbitrary MIME structures.
3199
     */
3200
    protected function setMessageType()
3201
    {
3202
        $type = [];
3203
        if ($this->alternativeExists()) {
3204
            $type[] = 'alt';
3205
        }
3206
        if ($this->inlineImageExists()) {
3207
            $type[] = 'inline';
3208
        }
3209
        if ($this->attachmentExists()) {
3210
            $type[] = 'attach';
3211
        }
3212
        $this->message_type = implode('_', $type);
3213
        if ('' === $this->message_type) {
3214
            //The 'plain' message_type refers to the message having a single body element, not that it is plain-text
3215
            $this->message_type = 'plain';
3216
        }
3217
    }
3218
 
3219
    /**
3220
     * Format a header line.
3221
     *
3222
     * @param string     $name
3223
     * @param string|int $value
3224
     *
3225
     * @return string
3226
     */
3227
    public function headerLine($name, $value)
3228
    {
3229
        return $name . ': ' . $value . static::$LE;
3230
    }
3231
 
3232
    /**
3233
     * Return a formatted mail line.
3234
     *
3235
     * @param string $value
3236
     *
3237
     * @return string
3238
     */
3239
    public function textLine($value)
3240
    {
3241
        return $value . static::$LE;
3242
    }
3243
 
3244
    /**
3245
     * Add an attachment from a path on the filesystem.
3246
     * Never use a user-supplied path to a file!
3247
     * Returns false if the file could not be found or read.
3248
     * Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client.
3249
     * If you need to do that, fetch the resource yourself and pass it in via a local file or string.
3250
     *
3251
     * @param string $path        Path to the attachment
3252
     * @param string $name        Overrides the attachment name
3253
     * @param string $encoding    File encoding (see $Encoding)
3254
     * @param string $type        MIME type, e.g. `image/jpeg`; determined automatically from $path if not specified
3255
     * @param string $disposition Disposition to use
3256
     *
3257
     * @throws Exception
3258
     *
3259
     * @return bool
3260
     */
3261
    public function addAttachment(
3262
        $path,
3263
        $name = '',
3264
        $encoding = self::ENCODING_BASE64,
3265
        $type = '',
3266
        $disposition = 'attachment'
3267
    ) {
3268
        try {
3269
            if (!static::fileIsAccessible($path)) {
3270
                throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
3271
            }
3272
 
3273
            //If a MIME type is not specified, try to work it out from the file name
3274
            if ('' === $type) {
3275
                $type = static::filenameToType($path);
3276
            }
3277
 
3278
            $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME);
3279
            if ('' === $name) {
3280
                $name = $filename;
3281
            }
3282
            if (!$this->validateEncoding($encoding)) {
3283
                throw new Exception($this->lang('encoding') . $encoding);
3284
            }
3285
 
3286
            $this->attachment[] = [
3287
 
3288
                1 => $filename,
3289
                2 => $name,
3290
                3 => $encoding,
3291
                4 => $type,
3292
                5 => false, //isStringAttachment
3293
                6 => $disposition,
3294
                7 => $name,
3295
            ];
3296
        } catch (Exception $exc) {
3297
            $this->setError($exc->getMessage());
3298
            $this->edebug($exc->getMessage());
3299
            if ($this->exceptions) {
3300
                throw $exc;
3301
            }
3302
 
3303
            return false;
3304
        }
3305
 
3306
        return true;
3307
    }
3308
 
3309
    /**
3310
     * Return the array of attachments.
3311
     *
3312
     * @return array
3313
     */
3314
    public function getAttachments()
3315
    {
3316
        return $this->attachment;
3317
    }
3318
 
3319
    /**
3320
     * Attach all file, string, and binary attachments to the message.
3321
     * Returns an empty string on failure.
3322
     *
3323
     * @param string $disposition_type
3324
     * @param string $boundary
3325
     *
3326
     * @throws Exception
3327
     *
3328
     * @return string
3329
     */
3330
    protected function attachAll($disposition_type, $boundary)
3331
    {
3332
        //Return text of body
3333
        $mime = [];
3334
        $cidUniq = [];
3335
        $incl = [];
3336
 
3337
        //Add all attachments
3338
        foreach ($this->attachment as $attachment) {
3339
            //Check if it is a valid disposition_filter
3340
            if ($attachment[6] === $disposition_type) {
3341
                //Check for string attachment
3342
                $string = '';
3343
                $path = '';
3344
                $bString = $attachment[5];
3345
                if ($bString) {
3346
                    $string = $attachment[0];
3347
                } else {
3348
                    $path = $attachment[0];
3349
                }
3350
 
3351
                $inclhash = hash('sha256', serialize($attachment));
3352
                if (in_array($inclhash, $incl, true)) {
3353
                    continue;
3354
                }
3355
                $incl[] = $inclhash;
3356
                $name = $attachment[2];
3357
                $encoding = $attachment[3];
3358
                $type = $attachment[4];
3359
                $disposition = $attachment[6];
3360
                $cid = $attachment[7];
3361
                if ('inline' === $disposition && array_key_exists($cid, $cidUniq)) {
3362
                    continue;
3363
                }
3364
                $cidUniq[$cid] = true;
3365
 
3366
                $mime[] = sprintf('--%s%s', $boundary, static::$LE);
3367
                //Only include a filename property if we have one
3368
                if (!empty($name)) {
3369
                    $mime[] = sprintf(
3370
                        'Content-Type: %s; name=%s%s',
3371
                        $type,
3372
                        static::quotedString($this->encodeHeader($this->secureHeader($name))),
3373
                        static::$LE
3374
                    );
3375
                } else {
3376
                    $mime[] = sprintf(
3377
                        'Content-Type: %s%s',
3378
                        $type,
3379
                        static::$LE
3380
                    );
3381
                }
3382
                //RFC1341 part 5 says 7bit is assumed if not specified
3383
                if (static::ENCODING_7BIT !== $encoding) {
3384
                    $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE);
3385
                }
3386
 
3387
                //Only set Content-IDs on inline attachments
3388
                if ((string) $cid !== '' && $disposition === 'inline') {
3389
                    $mime[] = 'Content-ID: <' . $this->encodeHeader($this->secureHeader($cid)) . '>' . static::$LE;
3390
                }
3391
 
3392
                //Allow for bypassing the Content-Disposition header
3393
                if (!empty($disposition)) {
3394
                    $encoded_name = $this->encodeHeader($this->secureHeader($name));
3395
                    if (!empty($encoded_name)) {
3396
                        $mime[] = sprintf(
3397
                            'Content-Disposition: %s; filename=%s%s',
3398
                            $disposition,
3399
                            static::quotedString($encoded_name),
3400
                            static::$LE . static::$LE
3401
                        );
3402
                    } else {
3403
                        $mime[] = sprintf(
3404
                            'Content-Disposition: %s%s',
3405
                            $disposition,
3406
                            static::$LE . static::$LE
3407
                        );
3408
                    }
3409
                } else {
3410
                    $mime[] = static::$LE;
3411
                }
3412
 
3413
                //Encode as string attachment
3414
                if ($bString) {
3415
                    $mime[] = $this->encodeString($string, $encoding);
3416
                } else {
3417
                    $mime[] = $this->encodeFile($path, $encoding);
3418
                }
3419
                if ($this->isError()) {
3420
                    return '';
3421
                }
3422
                $mime[] = static::$LE;
3423
            }
3424
        }
3425
 
3426
        $mime[] = sprintf('--%s--%s', $boundary, static::$LE);
3427
 
3428
        return implode('', $mime);
3429
    }
3430
 
3431
    /**
3432
     * Encode a file attachment in requested format.
3433
     * Returns an empty string on failure.
3434
     *
3435
     * @param string $path     The full path to the file
3436
     * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
3437
     *
3438
     * @return string
3439
     */
3440
    protected function encodeFile($path, $encoding = self::ENCODING_BASE64)
3441
    {
3442
        try {
3443
            if (!static::fileIsAccessible($path)) {
3444
                throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
3445
            }
3446
            $file_buffer = file_get_contents($path);
3447
            if (false === $file_buffer) {
3448
                throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
3449
            }
3450
            $file_buffer = $this->encodeString($file_buffer, $encoding);
3451
 
3452
            return $file_buffer;
3453
        } catch (Exception $exc) {
3454
            $this->setError($exc->getMessage());
3455
            $this->edebug($exc->getMessage());
3456
            if ($this->exceptions) {
3457
                throw $exc;
3458
            }
3459
 
3460
            return '';
3461
        }
3462
    }
3463
 
3464
    /**
3465
     * Encode a string in requested format.
3466
     * Returns an empty string on failure.
3467
     *
3468
     * @param string $str      The text to encode
3469
     * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
3470
     *
3471
     * @throws Exception
3472
     *
3473
     * @return string
3474
     */
3475
    public function encodeString($str, $encoding = self::ENCODING_BASE64)
3476
    {
3477
        $encoded = '';
3478
        switch (strtolower($encoding)) {
3479
            case static::ENCODING_BASE64:
3480
                $encoded = chunk_split(
3481
                    base64_encode($str),
3482
                    static::STD_LINE_LENGTH,
3483
                    static::$LE
3484
                );
3485
                break;
3486
            case static::ENCODING_7BIT:
3487
            case static::ENCODING_8BIT:
3488
                $encoded = static::normalizeBreaks($str);
3489
                //Make sure it ends with a line break
3490
                if (substr($encoded, -(strlen(static::$LE))) !== static::$LE) {
3491
                    $encoded .= static::$LE;
3492
                }
3493
                break;
3494
            case static::ENCODING_BINARY:
3495
                $encoded = $str;
3496
                break;
3497
            case static::ENCODING_QUOTED_PRINTABLE:
3498
                $encoded = $this->encodeQP($str);
3499
                break;
3500
            default:
3501
                $this->setError($this->lang('encoding') . $encoding);
3502
                if ($this->exceptions) {
3503
                    throw new Exception($this->lang('encoding') . $encoding);
3504
                }
3505
                break;
3506
        }
3507
 
3508
        return $encoded;
3509
    }
3510
 
3511
    /**
3512
     * Encode a header value (not including its label) optimally.
3513
     * Picks shortest of Q, B, or none. Result includes folding if needed.
3514
     * See RFC822 definitions for phrase, comment and text positions.
3515
     *
3516
     * @param string $str      The header value to encode
3517
     * @param string $position What context the string will be used in
3518
     *
3519
     * @return string
3520
     */
3521
    public function encodeHeader($str, $position = 'text')
3522
    {
3523
        $matchcount = 0;
3524
        switch (strtolower($position)) {
3525
            case 'phrase':
3526
                if (!preg_match('/[\200-\377]/', $str)) {
3527
                    //Can't use addslashes as we don't know the value of magic_quotes_sybase
3528
                    $encoded = addcslashes($str, "\0..\37\177\\\"");
3529
                    if (($str === $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
3530
                        return $encoded;
3531
                    }
3532
 
3533
                    return "\"$encoded\"";
3534
                }
3535
                $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
3536
                break;
3537
            /* @noinspection PhpMissingBreakStatementInspection */
3538
            case 'comment':
3539
                $matchcount = preg_match_all('/[()"]/', $str, $matches);
3540
            //fallthrough
3541
            case 'text':
3542
            default:
3543
                $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
3544
                break;
3545
        }
3546
 
3547
        if ($this->has8bitChars($str)) {
3548
            $charset = $this->CharSet;
3549
        } else {
3550
            $charset = static::CHARSET_ASCII;
3551
        }
3552
 
3553
        //Q/B encoding adds 8 chars and the charset ("` =?<charset>?[QB]?<content>?=`").
3554
        $overhead = 8 + strlen($charset);
3555
 
3556
        if ('mail' === $this->Mailer) {
3557
            $maxlen = static::MAIL_MAX_LINE_LENGTH - $overhead;
3558
        } else {
3559
            $maxlen = static::MAX_LINE_LENGTH - $overhead;
3560
        }
3561
 
3562
        //Select the encoding that produces the shortest output and/or prevents corruption.
3563
        if ($matchcount > strlen($str) / 3) {
3564
            //More than 1/3 of the content needs encoding, use B-encode.
3565
            $encoding = 'B';
3566
        } elseif ($matchcount > 0) {
3567
            //Less than 1/3 of the content needs encoding, use Q-encode.
3568
            $encoding = 'Q';
3569
        } elseif (strlen($str) > $maxlen) {
3570
            //No encoding needed, but value exceeds max line length, use Q-encode to prevent corruption.
3571
            $encoding = 'Q';
3572
        } else {
3573
            //No reformatting needed
3574
            $encoding = false;
3575
        }
3576
 
3577
        switch ($encoding) {
3578
            case 'B':
3579
                if ($this->hasMultiBytes($str)) {
3580
                    //Use a custom function which correctly encodes and wraps long
3581
                    //multibyte strings without breaking lines within a character
3582
                    $encoded = $this->base64EncodeWrapMB($str, "\n");
3583
                } else {
3584
                    $encoded = base64_encode($str);
3585
                    $maxlen -= $maxlen % 4;
3586
                    $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
3587
                }
3588
                $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded);
3589
                break;
3590
            case 'Q':
3591
                $encoded = $this->encodeQ($str, $position);
3592
                $encoded = $this->wrapText($encoded, $maxlen, true);
3593
                $encoded = str_replace('=' . static::$LE, "\n", trim($encoded));
3594
                $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded);
3595
                break;
3596
            default:
3597
                return $str;
3598
        }
3599
 
3600
        return trim(static::normalizeBreaks($encoded));
3601
    }
3602
 
3603
    /**
3604
     * Check if a string contains multi-byte characters.
3605
     *
3606
     * @param string $str multi-byte text to wrap encode
3607
     *
3608
     * @return bool
3609
     */
3610
    public function hasMultiBytes($str)
3611
    {
3612
        if (function_exists('mb_strlen')) {
3613
            return strlen($str) > mb_strlen($str, $this->CharSet);
3614
        }
3615
 
3616
        //Assume no multibytes (we can't handle without mbstring functions anyway)
3617
        return false;
3618
    }
3619
 
3620
    /**
3621
     * Does a string contain any 8-bit chars (in any charset)?
3622
     *
3623
     * @param string $text
3624
     *
3625
     * @return bool
3626
     */
3627
    public function has8bitChars($text)
3628
    {
3629
        return (bool) preg_match('/[\x80-\xFF]/', $text);
3630
    }
3631
 
3632
    /**
3633
     * Encode and wrap long multibyte strings for mail headers
3634
     * without breaking lines within a character.
3635
     * Adapted from a function by paravoid.
3636
     *
3637
     * @see http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
3638
     *
3639
     * @param string $str       multi-byte text to wrap encode
3640
     * @param string $linebreak string to use as linefeed/end-of-line
3641
     *
3642
     * @return string
3643
     */
3644
    public function base64EncodeWrapMB($str, $linebreak = null)
3645
    {
3646
        $start = '=?' . $this->CharSet . '?B?';
3647
        $end = '?=';
3648
        $encoded = '';
3649
        if (null === $linebreak) {
3650
            $linebreak = static::$LE;
3651
        }
3652
 
3653
        $mb_length = mb_strlen($str, $this->CharSet);
3654
        //Each line must have length <= 75, including $start and $end
3655
        $length = 75 - strlen($start) - strlen($end);
3656
        //Average multi-byte ratio
3657
        $ratio = $mb_length / strlen($str);
3658
        //Base64 has a 4:3 ratio
3659
        $avgLength = floor($length * $ratio * .75);
3660
 
3661
        $offset = 0;
3662
        for ($i = 0; $i < $mb_length; $i += $offset) {
3663
            $lookBack = 0;
3664
            do {
3665
                $offset = $avgLength - $lookBack;
3666
                $chunk = mb_substr($str, $i, $offset, $this->CharSet);
3667
                $chunk = base64_encode($chunk);
3668
                ++$lookBack;
3669
            } while (strlen($chunk) > $length);
3670
            $encoded .= $chunk . $linebreak;
3671
        }
3672
 
3673
        //Chomp the last linefeed
3674
        return substr($encoded, 0, -strlen($linebreak));
3675
    }
3676
 
3677
    /**
3678
     * Encode a string in quoted-printable format.
3679
     * According to RFC2045 section 6.7.
3680
     *
3681
     * @param string $string The text to encode
3682
     *
3683
     * @return string
3684
     */
3685
    public function encodeQP($string)
3686
    {
3687
        return static::normalizeBreaks(quoted_printable_encode($string));
3688
    }
3689
 
3690
    /**
3691
     * Encode a string using Q encoding.
3692
     *
3693
     * @see http://tools.ietf.org/html/rfc2047#section-4.2
3694
     *
3695
     * @param string $str      the text to encode
3696
     * @param string $position Where the text is going to be used, see the RFC for what that means
3697
     *
3698
     * @return string
3699
     */
3700
    public function encodeQ($str, $position = 'text')
3701
    {
3702
        //There should not be any EOL in the string
3703
        $pattern = '';
3704
        $encoded = str_replace(["\r", "\n"], '', $str);
3705
        switch (strtolower($position)) {
3706
            case 'phrase':
3707
                //RFC 2047 section 5.3
3708
                $pattern = '^A-Za-z0-9!*+\/ -';
3709
                break;
3710
            /*
3711
             * RFC 2047 section 5.2.
3712
             * Build $pattern without including delimiters and []
3713
             */
3714
            /* @noinspection PhpMissingBreakStatementInspection */
3715
            case 'comment':
3716
                $pattern = '\(\)"';
3717
            /* Intentional fall through */
3718
            case 'text':
3719
            default:
3720
                //RFC 2047 section 5.1
3721
                //Replace every high ascii, control, =, ? and _ characters
3722
                $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
3723
                break;
3724
        }
3725
        $matches = [];
3726
        if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
3727
            //If the string contains an '=', make sure it's the first thing we replace
3728
            //so as to avoid double-encoding
3729
            $eqkey = array_search('=', $matches[0], true);
3730
            if (false !== $eqkey) {
3731
                unset($matches[0][$eqkey]);
3732
                array_unshift($matches[0], '=');
3733
            }
3734
            foreach (array_unique($matches[0]) as $char) {
3735
                $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
3736
            }
3737
        }
3738
        //Replace spaces with _ (more readable than =20)
3739
        //RFC 2047 section 4.2(2)
3740
        return str_replace(' ', '_', $encoded);
3741
    }
3742
 
3743
    /**
3744
     * Add a string or binary attachment (non-filesystem).
3745
     * This method can be used to attach ascii or binary data,
3746
     * such as a BLOB record from a database.
3747
     *
3748
     * @param string $string      String attachment data
3749
     * @param string $filename    Name of the attachment
3750
     * @param string $encoding    File encoding (see $Encoding)
3751
     * @param string $type        File extension (MIME) type
3752
     * @param string $disposition Disposition to use
3753
     *
3754
     * @throws Exception
3755
     *
3756
     * @return bool True on successfully adding an attachment
3757
     */
3758
    public function addStringAttachment(
3759
        $string,
3760
        $filename,
3761
        $encoding = self::ENCODING_BASE64,
3762
        $type = '',
3763
        $disposition = 'attachment'
3764
    ) {
3765
        try {
3766
            //If a MIME type is not specified, try to work it out from the file name
3767
            if ('' === $type) {
3768
                $type = static::filenameToType($filename);
3769
            }
3770
 
3771
            if (!$this->validateEncoding($encoding)) {
3772
                throw new Exception($this->lang('encoding') . $encoding);
3773
            }
3774
 
3775
            //Append to $attachment array
3776
            $this->attachment[] = [
3777
 
3778
                1 => $filename,
3779
                2 => static::mb_pathinfo($filename, PATHINFO_BASENAME),
3780
                3 => $encoding,
3781
                4 => $type,
3782
                5 => true, //isStringAttachment
3783
                6 => $disposition,
3784
                7 => 0,
3785
            ];
3786
        } catch (Exception $exc) {
3787
            $this->setError($exc->getMessage());
3788
            $this->edebug($exc->getMessage());
3789
            if ($this->exceptions) {
3790
                throw $exc;
3791
            }
3792
 
3793
            return false;
3794
        }
3795
 
3796
        return true;
3797
    }
3798
 
3799
    /**
3800
     * Add an embedded (inline) attachment from a file.
3801
     * This can include images, sounds, and just about any other document type.
3802
     * These differ from 'regular' attachments in that they are intended to be
3803
     * displayed inline with the message, not just attached for download.
3804
     * This is used in HTML messages that embed the images
3805
     * the HTML refers to using the `$cid` value in `img` tags, for example `<img src="cid:mylogo">`.
3806
     * Never use a user-supplied path to a file!
3807
     *
3808
     * @param string $path        Path to the attachment
3809
     * @param string $cid         Content ID of the attachment; Use this to reference
3810
     *                            the content when using an embedded image in HTML
3811
     * @param string $name        Overrides the attachment filename
3812
     * @param string $encoding    File encoding (see $Encoding) defaults to `base64`
3813
     * @param string $type        File MIME type (by default mapped from the `$path` filename's extension)
3814
     * @param string $disposition Disposition to use: `inline` (default) or `attachment`
3815
     *                            (unlikely you want this – {@see `addAttachment()`} instead)
3816
     *
3817
     * @return bool True on successfully adding an attachment
3818
     * @throws Exception
3819
     *
3820
     */
3821
    public function addEmbeddedImage(
3822
        $path,
3823
        $cid,
3824
        $name = '',
3825
        $encoding = self::ENCODING_BASE64,
3826
        $type = '',
3827
        $disposition = 'inline'
3828
    ) {
3829
        try {
3830
            if (!static::fileIsAccessible($path)) {
3831
                throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
3832
            }
3833
 
3834
            //If a MIME type is not specified, try to work it out from the file name
3835
            if ('' === $type) {
3836
                $type = static::filenameToType($path);
3837
            }
3838
 
3839
            if (!$this->validateEncoding($encoding)) {
3840
                throw new Exception($this->lang('encoding') . $encoding);
3841
            }
3842
 
3843
            $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME);
3844
            if ('' === $name) {
3845
                $name = $filename;
3846
            }
3847
 
3848
            //Append to $attachment array
3849
            $this->attachment[] = [
3850
 
3851
                1 => $filename,
3852
                2 => $name,
3853
                3 => $encoding,
3854
                4 => $type,
3855
                5 => false, //isStringAttachment
3856
                6 => $disposition,
3857
                7 => $cid,
3858
            ];
3859
        } catch (Exception $exc) {
3860
            $this->setError($exc->getMessage());
3861
            $this->edebug($exc->getMessage());
3862
            if ($this->exceptions) {
3863
                throw $exc;
3864
            }
3865
 
3866
            return false;
3867
        }
3868
 
3869
        return true;
3870
    }
3871
 
3872
    /**
3873
     * Add an embedded stringified attachment.
3874
     * This can include images, sounds, and just about any other document type.
3875
     * If your filename doesn't contain an extension, be sure to set the $type to an appropriate MIME type.
3876
     *
3877
     * @param string $string      The attachment binary data
3878
     * @param string $cid         Content ID of the attachment; Use this to reference
3879
     *                            the content when using an embedded image in HTML
3880
     * @param string $name        A filename for the attachment. If this contains an extension,
3881
     *                            PHPMailer will attempt to set a MIME type for the attachment.
3882
     *                            For example 'file.jpg' would get an 'image/jpeg' MIME type.
3883
     * @param string $encoding    File encoding (see $Encoding), defaults to 'base64'
3884
     * @param string $type        MIME type - will be used in preference to any automatically derived type
3885
     * @param string $disposition Disposition to use
3886
     *
3887
     * @throws Exception
3888
     *
3889
     * @return bool True on successfully adding an attachment
3890
     */
3891
    public function addStringEmbeddedImage(
3892
        $string,
3893
        $cid,
3894
        $name = '',
3895
        $encoding = self::ENCODING_BASE64,
3896
        $type = '',
3897
        $disposition = 'inline'
3898
    ) {
3899
        try {
3900
            //If a MIME type is not specified, try to work it out from the name
3901
            if ('' === $type && !empty($name)) {
3902
                $type = static::filenameToType($name);
3903
            }
3904
 
3905
            if (!$this->validateEncoding($encoding)) {
3906
                throw new Exception($this->lang('encoding') . $encoding);
3907
            }
3908
 
3909
            //Append to $attachment array
3910
            $this->attachment[] = [
3911
 
3912
                1 => $name,
3913
                2 => $name,
3914
                3 => $encoding,
3915
                4 => $type,
3916
                5 => true, //isStringAttachment
3917
                6 => $disposition,
3918
                7 => $cid,
3919
            ];
3920
        } catch (Exception $exc) {
3921
            $this->setError($exc->getMessage());
3922
            $this->edebug($exc->getMessage());
3923
            if ($this->exceptions) {
3924
                throw $exc;
3925
            }
3926
 
3927
            return false;
3928
        }
3929
 
3930
        return true;
3931
    }
3932
 
3933
    /**
3934
     * Validate encodings.
3935
     *
3936
     * @param string $encoding
3937
     *
3938
     * @return bool
3939
     */
3940
    protected function validateEncoding($encoding)
3941
    {
3942
        return in_array(
3943
            $encoding,
3944
            [
3945
                self::ENCODING_7BIT,
3946
                self::ENCODING_QUOTED_PRINTABLE,
3947
                self::ENCODING_BASE64,
3948
                self::ENCODING_8BIT,
3949
                self::ENCODING_BINARY,
3950
            ],
3951
            true
3952
        );
3953
    }
3954
 
3955
    /**
3956
     * Check if an embedded attachment is present with this cid.
3957
     *
3958
     * @param string $cid
3959
     *
3960
     * @return bool
3961
     */
3962
    protected function cidExists($cid)
3963
    {
3964
        foreach ($this->attachment as $attachment) {
3965
            if ('inline' === $attachment[6] && $cid === $attachment[7]) {
3966
                return true;
3967
            }
3968
        }
3969
 
3970
        return false;
3971
    }
3972
 
3973
    /**
3974
     * Check if an inline attachment is present.
3975
     *
3976
     * @return bool
3977
     */
3978
    public function inlineImageExists()
3979
    {
3980
        foreach ($this->attachment as $attachment) {
3981
            if ('inline' === $attachment[6]) {
3982
                return true;
3983
            }
3984
        }
3985
 
3986
        return false;
3987
    }
3988
 
3989
    /**
3990
     * Check if an attachment (non-inline) is present.
3991
     *
3992
     * @return bool
3993
     */
3994
    public function attachmentExists()
3995
    {
3996
        foreach ($this->attachment as $attachment) {
3997
            if ('attachment' === $attachment[6]) {
3998
                return true;
3999
            }
4000
        }
4001
 
4002
        return false;
4003
    }
4004
 
4005
    /**
4006
     * Check if this message has an alternative body set.
4007
     *
4008
     * @return bool
4009
     */
4010
    public function alternativeExists()
4011
    {
4012
        return !empty($this->AltBody);
4013
    }
4014
 
4015
    /**
4016
     * Clear queued addresses of given kind.
4017
     *
4018
     * @param string $kind 'to', 'cc', or 'bcc'
4019
     */
4020
    public function clearQueuedAddresses($kind)
4021
    {
4022
        $this->RecipientsQueue = array_filter(
4023
            $this->RecipientsQueue,
4024
            static function ($params) use ($kind) {
4025
                return $params[0] !== $kind;
4026
            }
4027
        );
4028
    }
4029
 
4030
    /**
4031
     * Clear all To recipients.
4032
     */
4033
    public function clearAddresses()
4034
    {
4035
        foreach ($this->to as $to) {
4036
            unset($this->all_recipients[strtolower($to[0])]);
4037
        }
4038
        $this->to = [];
4039
        $this->clearQueuedAddresses('to');
4040
    }
4041
 
4042
    /**
4043
     * Clear all CC recipients.
4044
     */
4045
    public function clearCCs()
4046
    {
4047
        foreach ($this->cc as $cc) {
4048
            unset($this->all_recipients[strtolower($cc[0])]);
4049
        }
4050
        $this->cc = [];
4051
        $this->clearQueuedAddresses('cc');
4052
    }
4053
 
4054
    /**
4055
     * Clear all BCC recipients.
4056
     */
4057
    public function clearBCCs()
4058
    {
4059
        foreach ($this->bcc as $bcc) {
4060
            unset($this->all_recipients[strtolower($bcc[0])]);
4061
        }
4062
        $this->bcc = [];
4063
        $this->clearQueuedAddresses('bcc');
4064
    }
4065
 
4066
    /**
4067
     * Clear all ReplyTo recipients.
4068
     */
4069
    public function clearReplyTos()
4070
    {
4071
        $this->ReplyTo = [];
4072
        $this->ReplyToQueue = [];
4073
    }
4074
 
4075
    /**
4076
     * Clear all recipient types.
4077
     */
4078
    public function clearAllRecipients()
4079
    {
4080
        $this->to = [];
4081
        $this->cc = [];
4082
        $this->bcc = [];
4083
        $this->all_recipients = [];
4084
        $this->RecipientsQueue = [];
4085
    }
4086
 
4087
    /**
4088
     * Clear all filesystem, string, and binary attachments.
4089
     */
4090
    public function clearAttachments()
4091
    {
4092
        $this->attachment = [];
4093
    }
4094
 
4095
    /**
4096
     * Clear all custom headers.
4097
     */
4098
    public function clearCustomHeaders()
4099
    {
4100
        $this->CustomHeader = [];
4101
    }
4102
 
4103
    /**
4104
     * Clear a specific custom header by name or name and value.
4105
     * $name value can be overloaded to contain
4106
     * both header name and value (name:value).
4107
     *
4108
     * @param string      $name  Custom header name
4109
     * @param string|null $value Header value
4110
     *
4111
     * @return bool True if a header was replaced successfully
4112
     */
4113
    public function clearCustomHeader($name, $value = null)
4114
    {
4115
        if (null === $value && strpos($name, ':') !== false) {
4116
            //Value passed in as name:value
4117
            list($name, $value) = explode(':', $name, 2);
4118
        }
4119
        $name = trim($name);
4120
        $value = (null === $value) ? null : trim($value);
4121
 
4122
        foreach ($this->CustomHeader as $k => $pair) {
4123
            if ($pair[0] == $name) {
4124
                // We remove the header if the value is not provided or it matches.
4125
                if (null === $value ||  $pair[1] == $value) {
4126
                    unset($this->CustomHeader[$k]);
4127
                }
4128
            }
4129
        }
4130
 
4131
        return true;
4132
    }
4133
 
4134
    /**
4135
     * Replace a custom header.
4136
     * $name value can be overloaded to contain
4137
     * both header name and value (name:value).
4138
     *
4139
     * @param string      $name  Custom header name
4140
     * @param string|null $value Header value
4141
     *
4142
     * @return bool True if a header was replaced successfully
4143
     * @throws Exception
4144
     */
4145
    public function replaceCustomHeader($name, $value = null)
4146
    {
4147
        if (null === $value && strpos($name, ':') !== false) {
4148
            //Value passed in as name:value
4149
            list($name, $value) = explode(':', $name, 2);
4150
        }
4151
        $name = trim($name);
4152
        $value = (null === $value) ? '' : trim($value);
4153
 
4154
        $replaced = false;
4155
        foreach ($this->CustomHeader as $k => $pair) {
4156
            if ($pair[0] == $name) {
4157
                if ($replaced) {
4158
                    unset($this->CustomHeader[$k]);
4159
                    continue;
4160
                }
4161
                if (strpbrk($name . $value, "\r\n") !== false) {
4162
                    if ($this->exceptions) {
4163
                        throw new Exception($this->lang('invalid_header'));
4164
                    }
4165
 
4166
                    return false;
4167
                }
4168
                $this->CustomHeader[$k] = [$name, $value];
4169
                $replaced = true;
4170
            }
4171
        }
4172
 
4173
        return true;
4174
    }
4175
 
4176
    /**
4177
     * Add an error message to the error container.
4178
     *
4179
     * @param string $msg
4180
     */
4181
    protected function setError($msg)
4182
    {
4183
        ++$this->error_count;
4184
        if ('smtp' === $this->Mailer && null !== $this->smtp) {
4185
            $lasterror = $this->smtp->getError();
4186
            if (!empty($lasterror['error'])) {
4187
                $msg .= $this->lang('smtp_error') . $lasterror['error'];
4188
                if (!empty($lasterror['detail'])) {
4189
                    $msg .= ' ' . $this->lang('smtp_detail') . $lasterror['detail'];
4190
                }
4191
                if (!empty($lasterror['smtp_code'])) {
4192
                    $msg .= ' ' . $this->lang('smtp_code') . $lasterror['smtp_code'];
4193
                }
4194
                if (!empty($lasterror['smtp_code_ex'])) {
4195
                    $msg .= ' ' . $this->lang('smtp_code_ex') . $lasterror['smtp_code_ex'];
4196
                }
4197
            }
4198
        }
4199
        $this->ErrorInfo = $msg;
4200
    }
4201
 
4202
    /**
4203
     * Return an RFC 822 formatted date.
4204
     *
4205
     * @return string
4206
     */
4207
    public static function rfcDate()
4208
    {
4209
        //Set the time zone to whatever the default is to avoid 500 errors
4210
        //Will default to UTC if it's not set properly in php.ini
4211
        date_default_timezone_set(@date_default_timezone_get());
4212
 
4213
        return date('D, j M Y H:i:s O');
4214
    }
4215
 
4216
    /**
4217
     * Get the server hostname.
4218
     * Returns 'localhost.localdomain' if unknown.
4219
     *
4220
     * @return string
4221
     */
4222
    protected function serverHostname()
4223
    {
4224
        $result = '';
4225
        if (!empty($this->Hostname)) {
4226
            $result = $this->Hostname;
4227
        } elseif (isset($_SERVER) && array_key_exists('SERVER_NAME', $_SERVER)) {
4228
            $result = $_SERVER['SERVER_NAME'];
4229
        } elseif (function_exists('gethostname') && gethostname() !== false) {
4230
            $result = gethostname();
4231
        } elseif (php_uname('n') !== false) {
4232
            $result = php_uname('n');
4233
        }
4234
        if (!static::isValidHost($result)) {
4235
            return 'localhost.localdomain';
4236
        }
4237
 
4238
        return $result;
4239
    }
4240
 
4241
    /**
4242
     * Validate whether a string contains a valid value to use as a hostname or IP address.
4243
     * IPv6 addresses must include [], e.g. `[::1]`, not just `::1`.
4244
     *
4245
     * @param string $host The host name or IP address to check
4246
     *
4247
     * @return bool
4248
     */
4249
    public static function isValidHost($host)
4250
    {
4251
        //Simple syntax limits
4252
        if (
4253
            empty($host)
4254
            || !is_string($host)
4255
            || strlen($host) > 256
4256
            || !preg_match('/^([a-zA-Z\d.-]*|\[[a-fA-F\d:]+\])$/', $host)
4257
        ) {
4258
            return false;
4259
        }
4260
        //Looks like a bracketed IPv6 address
4261
        if (strlen($host) > 2 && substr($host, 0, 1) === '[' && substr($host, -1, 1) === ']') {
4262
            return filter_var(substr($host, 1, -1), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
4263
        }
4264
        //If removing all the dots results in a numeric string, it must be an IPv4 address.
4265
        //Need to check this first because otherwise things like `999.0.0.0` are considered valid host names
4266
        if (is_numeric(str_replace('.', '', $host))) {
4267
            //Is it a valid IPv4 address?
4268
            return filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
4269
        }
4270
        //Is it a syntactically valid hostname (when embeded in a URL)?
4271
        return filter_var('http://' . $host, FILTER_VALIDATE_URL) !== false;
4272
    }
4273
 
4274
    /**
4275
     * Get an error message in the current language.
4276
     *
4277
     * @param string $key
4278
     *
4279
     * @return string
4280
     */
4281
    protected function lang($key)
4282
    {
4283
        if (count($this->language) < 1) {
4284
            $this->setLanguage(); //Set the default language
4285
        }
4286
 
4287
        if (array_key_exists($key, $this->language)) {
4288
            if ('smtp_connect_failed' === $key) {
4289
                //Include a link to troubleshooting docs on SMTP connection failure.
4290
                //This is by far the biggest cause of support questions
4291
                //but it's usually not PHPMailer's fault.
4292
                return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
4293
            }
4294
 
4295
            return $this->language[$key];
4296
        }
4297
 
4298
        //Return the key as a fallback
4299
        return $key;
4300
    }
4301
 
4302
    /**
4303
     * Build an error message starting with a generic one and adding details if possible.
4304
     *
4305
     * @param string $base_key
4306
     * @return string
4307
     */
4308
    private function getSmtpErrorMessage($base_key)
4309
    {
4310
        $message = $this->lang($base_key);
4311
        $error = $this->smtp->getError();
4312
        if (!empty($error['error'])) {
4313
            $message .= ' ' . $error['error'];
4314
            if (!empty($error['detail'])) {
4315
                $message .= ' ' . $error['detail'];
4316
            }
4317
        }
4318
 
4319
        return $message;
4320
    }
4321
 
4322
    /**
4323
     * Check if an error occurred.
4324
     *
4325
     * @return bool True if an error did occur
4326
     */
4327
    public function isError()
4328
    {
4329
        return $this->error_count > 0;
4330
    }
4331
 
4332
    /**
4333
     * Add a custom header.
4334
     * $name value can be overloaded to contain
4335
     * both header name and value (name:value).
4336
     *
4337
     * @param string      $name  Custom header name
4338
     * @param string|null $value Header value
4339
     *
4340
     * @return bool True if a header was set successfully
4341
     * @throws Exception
4342
     */
4343
    public function addCustomHeader($name, $value = null)
4344
    {
4345
        if (null === $value && strpos($name, ':') !== false) {
4346
            //Value passed in as name:value
4347
            list($name, $value) = explode(':', $name, 2);
4348
        }
4349
        $name = trim($name);
4350
        $value = (null === $value) ? '' : trim($value);
4351
        //Ensure name is not empty, and that neither name nor value contain line breaks
4352
        if (empty($name) || strpbrk($name . $value, "\r\n") !== false) {
4353
            if ($this->exceptions) {
4354
                throw new Exception($this->lang('invalid_header'));
4355
            }
4356
 
4357
            return false;
4358
        }
4359
        $this->CustomHeader[] = [$name, $value];
4360
 
4361
        return true;
4362
    }
4363
 
4364
    /**
4365
     * Returns all custom headers.
4366
     *
4367
     * @return array
4368
     */
4369
    public function getCustomHeaders()
4370
    {
4371
        return $this->CustomHeader;
4372
    }
4373
 
4374
    /**
4375
     * Create a message body from an HTML string.
4376
     * Automatically inlines images and creates a plain-text version by converting the HTML,
4377
     * overwriting any existing values in Body and AltBody.
4378
     * Do not source $message content from user input!
4379
     * $basedir is prepended when handling relative URLs, e.g. <img src="/images/a.png"> and must not be empty
4380
     * will look for an image file in $basedir/images/a.png and convert it to inline.
4381
     * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email)
4382
     * Converts data-uri images into embedded attachments.
4383
     * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly.
4384
     *
4385
     * @param string        $message  HTML message string
4386
     * @param string        $basedir  Absolute path to a base directory to prepend to relative paths to images
4387
     * @param bool|callable $advanced Whether to use the internal HTML to text converter
4388
     *                                or your own custom converter
4389
     * @return string The transformed message body
4390
     *
4391
     * @throws Exception
4392
     *
4393
     * @see PHPMailer::html2text()
4394
     */
4395
    public function msgHTML($message, $basedir = '', $advanced = false)
4396
    {
4397
        preg_match_all('/(?<!-)(src|background)=["\'](.*)["\']/Ui', $message, $images);
4398
        if (array_key_exists(2, $images)) {
4399
            if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {
4400
                //Ensure $basedir has a trailing /
4401
                $basedir .= '/';
4402
            }
4403
            foreach ($images[2] as $imgindex => $url) {
4404
                //Convert data URIs into embedded images
4405
                //e.g. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
4406
                $match = [];
4407
                if (preg_match('#^data:(image/(?:jpe?g|gif|png));?(base64)?,(.+)#', $url, $match)) {
4408
                    if (count($match) === 4 && static::ENCODING_BASE64 === $match[2]) {
4409
                        $data = base64_decode($match[3]);
4410
                    } elseif ('' === $match[2]) {
4411
                        $data = rawurldecode($match[3]);
4412
                    } else {
4413
                        //Not recognised so leave it alone
4414
                        continue;
4415
                    }
4416
                    //Hash the decoded data, not the URL, so that the same data-URI image used in multiple places
4417
                    //will only be embedded once, even if it used a different encoding
4418
                    $cid = substr(hash('sha256', $data), 0, 32) . '@phpmailer.0'; //RFC2392 S 2
4419
 
4420
                    if (!$this->cidExists($cid)) {
4421
                        $this->addStringEmbeddedImage(
4422
                            $data,
4423
                            $cid,
4424
                            'embed' . $imgindex,
4425
                            static::ENCODING_BASE64,
4426
                            $match[1]
4427
                        );
4428
                    }
4429
                    $message = str_replace(
4430
                        $images[0][$imgindex],
4431
                        $images[1][$imgindex] . '="cid:' . $cid . '"',
4432
                        $message
4433
                    );
4434
                    continue;
4435
                }
4436
                if (
4437
                    //Only process relative URLs if a basedir is provided (i.e. no absolute local paths)
4438
                    !empty($basedir)
4439
                    //Ignore URLs containing parent dir traversal (..)
4440
                    && (strpos($url, '..') === false)
4441
                    //Do not change urls that are already inline images
4442
                    && 0 !== strpos($url, 'cid:')
4443
                    //Do not change absolute URLs, including anonymous protocol
4444
                    && !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url)
4445
                ) {
4446
                    $filename = static::mb_pathinfo($url, PATHINFO_BASENAME);
4447
                    $directory = dirname($url);
4448
                    if ('.' === $directory) {
4449
                        $directory = '';
4450
                    }
4451
                    //RFC2392 S 2
4452
                    $cid = substr(hash('sha256', $url), 0, 32) . '@phpmailer.0';
4453
                    if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {
4454
                        $basedir .= '/';
4455
                    }
4456
                    if (strlen($directory) > 1 && '/' !== substr($directory, -1)) {
4457
                        $directory .= '/';
4458
                    }
4459
                    if (
4460
                        $this->addEmbeddedImage(
4461
                            $basedir . $directory . $filename,
4462
                            $cid,
4463
                            $filename,
4464
                            static::ENCODING_BASE64,
4465
                            static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION))
4466
                        )
4467
                    ) {
4468
                        $message = preg_replace(
4469
                            '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
4470
                            $images[1][$imgindex] . '="cid:' . $cid . '"',
4471
                            $message
4472
                        );
4473
                    }
4474
                }
4475
            }
4476
        }
4477
        $this->isHTML();
4478
        //Convert all message body line breaks to LE, makes quoted-printable encoding work much better
4479
        $this->Body = static::normalizeBreaks($message);
4480
        $this->AltBody = static::normalizeBreaks($this->html2text($message, $advanced));
4481
        if (!$this->alternativeExists()) {
4482
            $this->AltBody = 'This is an HTML-only message. To view it, activate HTML in your email application.'
4483
                . static::$LE;
4484
        }
4485
 
4486
        return $this->Body;
4487
    }
4488
 
4489
    /**
4490
     * Convert an HTML string into plain text.
4491
     * This is used by msgHTML().
4492
     * Note - older versions of this function used a bundled advanced converter
4493
     * which was removed for license reasons in #232.
4494
     * Example usage:
4495
     *
4496
     * ```php
4497
     * //Use default conversion
4498
     * $plain = $mail->html2text($html);
4499
     * //Use your own custom converter
4500
     * $plain = $mail->html2text($html, function($html) {
4501
     *     $converter = new MyHtml2text($html);
4502
     *     return $converter->get_text();
4503
     * });
4504
     * ```
4505
     *
4506
     * @param string        $html     The HTML text to convert
4507
     * @param bool|callable $advanced Any boolean value to use the internal converter,
4508
     *                                or provide your own callable for custom conversion.
4509
     *                                *Never* pass user-supplied data into this parameter
4510
     *
4511
     * @return string
4512
     */
4513
    public function html2text($html, $advanced = false)
4514
    {
4515
        if (is_callable($advanced)) {
4516
            return call_user_func($advanced, $html);
4517
        }
4518
 
4519
        return html_entity_decode(
4520
            trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
4521
            ENT_QUOTES,
4522
            $this->CharSet
4523
        );
4524
    }
4525
 
4526
    /**
4527
     * Get the MIME type for a file extension.
4528
     *
4529
     * @param string $ext File extension
4530
     *
4531
     * @return string MIME type of file
4532
     */
4533
    public static function _mime_types($ext = '')
4534
    {
4535
        $mimes = [
4536
            'xl' => 'application/excel',
4537
            'js' => 'application/javascript',
4538
            'hqx' => 'application/mac-binhex40',
4539
            'cpt' => 'application/mac-compactpro',
4540
            'bin' => 'application/macbinary',
4541
            'doc' => 'application/msword',
4542
            'word' => 'application/msword',
4543
            'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
4544
            'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
4545
            'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
4546
            'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
4547
            'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
4548
            'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
4549
            'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
4550
            'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
4551
            'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
4552
            'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
4553
            'class' => 'application/octet-stream',
4554
            'dll' => 'application/octet-stream',
4555
            'dms' => 'application/octet-stream',
4556
            'exe' => 'application/octet-stream',
4557
            'lha' => 'application/octet-stream',
4558
            'lzh' => 'application/octet-stream',
4559
            'psd' => 'application/octet-stream',
4560
            'sea' => 'application/octet-stream',
4561
            'so' => 'application/octet-stream',
4562
            'oda' => 'application/oda',
4563
            'pdf' => 'application/pdf',
4564
            'ai' => 'application/postscript',
4565
            'eps' => 'application/postscript',
4566
            'ps' => 'application/postscript',
4567
            'smi' => 'application/smil',
4568
            'smil' => 'application/smil',
4569
            'mif' => 'application/vnd.mif',
4570
            'xls' => 'application/vnd.ms-excel',
4571
            'ppt' => 'application/vnd.ms-powerpoint',
4572
            'wbxml' => 'application/vnd.wap.wbxml',
4573
            'wmlc' => 'application/vnd.wap.wmlc',
4574
            'dcr' => 'application/x-director',
4575
            'dir' => 'application/x-director',
4576
            'dxr' => 'application/x-director',
4577
            'dvi' => 'application/x-dvi',
4578
            'gtar' => 'application/x-gtar',
4579
            'php3' => 'application/x-httpd-php',
4580
            'php4' => 'application/x-httpd-php',
4581
            'php' => 'application/x-httpd-php',
4582
            'phtml' => 'application/x-httpd-php',
4583
            'phps' => 'application/x-httpd-php-source',
4584
            'swf' => 'application/x-shockwave-flash',
4585
            'sit' => 'application/x-stuffit',
4586
            'tar' => 'application/x-tar',
4587
            'tgz' => 'application/x-tar',
4588
            'xht' => 'application/xhtml+xml',
4589
            'xhtml' => 'application/xhtml+xml',
4590
            'zip' => 'application/zip',
4591
            'mid' => 'audio/midi',
4592
            'midi' => 'audio/midi',
4593
            'mp2' => 'audio/mpeg',
4594
            'mp3' => 'audio/mpeg',
4595
            'm4a' => 'audio/mp4',
4596
            'mpga' => 'audio/mpeg',
4597
            'aif' => 'audio/x-aiff',
4598
            'aifc' => 'audio/x-aiff',
4599
            'aiff' => 'audio/x-aiff',
4600
            'ram' => 'audio/x-pn-realaudio',
4601
            'rm' => 'audio/x-pn-realaudio',
4602
            'rpm' => 'audio/x-pn-realaudio-plugin',
4603
            'ra' => 'audio/x-realaudio',
4604
            'wav' => 'audio/x-wav',
4605
            'mka' => 'audio/x-matroska',
4606
            'bmp' => 'image/bmp',
4607
            'gif' => 'image/gif',
4608
            'jpeg' => 'image/jpeg',
4609
            'jpe' => 'image/jpeg',
4610
            'jpg' => 'image/jpeg',
4611
            'png' => 'image/png',
4612
            'tiff' => 'image/tiff',
4613
            'tif' => 'image/tiff',
4614
            'webp' => 'image/webp',
4615
            'avif' => 'image/avif',
4616
            'heif' => 'image/heif',
4617
            'heifs' => 'image/heif-sequence',
4618
            'heic' => 'image/heic',
4619
            'heics' => 'image/heic-sequence',
4620
            'eml' => 'message/rfc822',
4621
            'css' => 'text/css',
4622
            'html' => 'text/html',
4623
            'htm' => 'text/html',
4624
            'shtml' => 'text/html',
4625
            'log' => 'text/plain',
4626
            'text' => 'text/plain',
4627
            'txt' => 'text/plain',
4628
            'rtx' => 'text/richtext',
4629
            'rtf' => 'text/rtf',
4630
            'vcf' => 'text/vcard',
4631
            'vcard' => 'text/vcard',
4632
            'ics' => 'text/calendar',
4633
            'xml' => 'text/xml',
4634
            'xsl' => 'text/xml',
4635
            'csv' => 'text/csv',
4636
            'wmv' => 'video/x-ms-wmv',
4637
            'mpeg' => 'video/mpeg',
4638
            'mpe' => 'video/mpeg',
4639
            'mpg' => 'video/mpeg',
4640
            'mp4' => 'video/mp4',
4641
            'm4v' => 'video/mp4',
4642
            'mov' => 'video/quicktime',
4643
            'qt' => 'video/quicktime',
4644
            'rv' => 'video/vnd.rn-realvideo',
4645
            'avi' => 'video/x-msvideo',
4646
            'movie' => 'video/x-sgi-movie',
4647
            'webm' => 'video/webm',
4648
            'mkv' => 'video/x-matroska',
4649
        ];
4650
        $ext = strtolower($ext);
4651
        if (array_key_exists($ext, $mimes)) {
4652
            return $mimes[$ext];
4653
        }
4654
 
4655
        return 'application/octet-stream';
4656
    }
4657
 
4658
    /**
4659
     * Map a file name to a MIME type.
4660
     * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
4661
     *
4662
     * @param string $filename A file name or full path, does not need to exist as a file
4663
     *
4664
     * @return string
4665
     */
4666
    public static function filenameToType($filename)
4667
    {
4668
        //In case the path is a URL, strip any query string before getting extension
4669
        $qpos = strpos($filename, '?');
4670
        if (false !== $qpos) {
4671
            $filename = substr($filename, 0, $qpos);
4672
        }
4673
        $ext = static::mb_pathinfo($filename, PATHINFO_EXTENSION);
4674
 
4675
        return static::_mime_types($ext);
4676
    }
4677
 
4678
    /**
4679
     * Multi-byte-safe pathinfo replacement.
4680
     * Drop-in replacement for pathinfo(), but multibyte- and cross-platform-safe.
4681
     *
4682
     * @see http://www.php.net/manual/en/function.pathinfo.php#107461
4683
     *
4684
     * @param string     $path    A filename or path, does not need to exist as a file
4685
     * @param int|string $options Either a PATHINFO_* constant,
4686
     *                            or a string name to return only the specified piece
4687
     *
4688
     * @return string|array
4689
     */
4690
    public static function mb_pathinfo($path, $options = null)
4691
    {
4692
        $ret = ['dirname' => '', 'basename' => '', 'extension' => '', 'filename' => ''];
4693
        $pathinfo = [];
4694
        if (preg_match('#^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^.\\\\/]+?)|))[\\\\/.]*$#m', $path, $pathinfo)) {
4695
            if (array_key_exists(1, $pathinfo)) {
4696
                $ret['dirname'] = $pathinfo[1];
4697
            }
4698
            if (array_key_exists(2, $pathinfo)) {
4699
                $ret['basename'] = $pathinfo[2];
4700
            }
4701
            if (array_key_exists(5, $pathinfo)) {
4702
                $ret['extension'] = $pathinfo[5];
4703
            }
4704
            if (array_key_exists(3, $pathinfo)) {
4705
                $ret['filename'] = $pathinfo[3];
4706
            }
4707
        }
4708
        switch ($options) {
4709
            case PATHINFO_DIRNAME:
4710
            case 'dirname':
4711
                return $ret['dirname'];
4712
            case PATHINFO_BASENAME:
4713
            case 'basename':
4714
                return $ret['basename'];
4715
            case PATHINFO_EXTENSION:
4716
            case 'extension':
4717
                return $ret['extension'];
4718
            case PATHINFO_FILENAME:
4719
            case 'filename':
4720
                return $ret['filename'];
4721
            default:
4722
                return $ret;
4723
        }
4724
    }
4725
 
4726
    /**
4727
     * Set or reset instance properties.
4728
     * You should avoid this function - it's more verbose, less efficient, more error-prone and
4729
     * harder to debug than setting properties directly.
4730
     * Usage Example:
4731
     * `$mail->set('SMTPSecure', static::ENCRYPTION_STARTTLS);`
4732
     *   is the same as:
4733
     * `$mail->SMTPSecure = static::ENCRYPTION_STARTTLS;`.
4734
     *
4735
     * @param string $name  The property name to set
4736
     * @param mixed  $value The value to set the property to
4737
     *
4738
     * @return bool
4739
     */
4740
    public function set($name, $value = '')
4741
    {
4742
        if (property_exists($this, $name)) {
4743
            $this->{$name} = $value;
4744
 
4745
            return true;
4746
        }
4747
        $this->setError($this->lang('variable_set') . $name);
4748
 
4749
        return false;
4750
    }
4751
 
4752
    /**
4753
     * Strip newlines to prevent header injection.
4754
     *
4755
     * @param string $str
4756
     *
4757
     * @return string
4758
     */
4759
    public function secureHeader($str)
4760
    {
4761
        return trim(str_replace(["\r", "\n"], '', $str));
4762
    }
4763
 
4764
    /**
4765
     * Normalize line breaks in a string.
4766
     * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
4767
     * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
4768
     *
4769
     * @param string $text
4770
     * @param string $breaktype What kind of line break to use; defaults to static::$LE
4771
     *
4772
     * @return string
4773
     */
4774
    public static function normalizeBreaks($text, $breaktype = null)
4775
    {
4776
        if (null === $breaktype) {
4777
            $breaktype = static::$LE;
4778
        }
4779
        //Normalise to \n
4780
        $text = str_replace([self::CRLF, "\r"], "\n", $text);
4781
        //Now convert LE as needed
4782
        if ("\n" !== $breaktype) {
4783
            $text = str_replace("\n", $breaktype, $text);
4784
        }
4785
 
4786
        return $text;
4787
    }
4788
 
4789
    /**
4790
     * Remove trailing whitespace from a string.
4791
     *
4792
     * @param string $text
4793
     *
4794
     * @return string The text to remove whitespace from
4795
     */
4796
    public static function stripTrailingWSP($text)
4797
    {
4798
        return rtrim($text, " \r\n\t");
4799
    }
4800
 
4801
    /**
4802
     * Strip trailing line breaks from a string.
4803
     *
4804
     * @param string $text
4805
     *
4806
     * @return string The text to remove breaks from
4807
     */
4808
    public static function stripTrailingBreaks($text)
4809
    {
4810
        return rtrim($text, "\r\n");
4811
    }
4812
 
4813
    /**
4814
     * Return the current line break format string.
4815
     *
4816
     * @return string
4817
     */
4818
    public static function getLE()
4819
    {
4820
        return static::$LE;
4821
    }
4822
 
4823
    /**
4824
     * Set the line break format string, e.g. "\r\n".
4825
     *
4826
     * @param string $le
4827
     */
4828
    protected static function setLE($le)
4829
    {
4830
        static::$LE = $le;
4831
    }
4832
 
4833
    /**
4834
     * Set the public and private key files and password for S/MIME signing.
4835
     *
4836
     * @param string $cert_filename
4837
     * @param string $key_filename
4838
     * @param string $key_pass            Password for private key
4839
     * @param string $extracerts_filename Optional path to chain certificate
4840
     */
4841
    public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
4842
    {
4843
        $this->sign_cert_file = $cert_filename;
4844
        $this->sign_key_file = $key_filename;
4845
        $this->sign_key_pass = $key_pass;
4846
        $this->sign_extracerts_file = $extracerts_filename;
4847
    }
4848
 
4849
    /**
4850
     * Quoted-Printable-encode a DKIM header.
4851
     *
4852
     * @param string $txt
4853
     *
4854
     * @return string
4855
     */
4856
    public function DKIM_QP($txt)
4857
    {
4858
        $line = '';
4859
        $len = strlen($txt);
4860
        for ($i = 0; $i < $len; ++$i) {
4861
            $ord = ord($txt[$i]);
4862
            if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord === 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
4863
                $line .= $txt[$i];
4864
            } else {
4865
                $line .= '=' . sprintf('%02X', $ord);
4866
            }
4867
        }
4868
 
4869
        return $line;
4870
    }
4871
 
4872
    /**
4873
     * Generate a DKIM signature.
4874
     *
4875
     * @param string $signHeader
4876
     *
4877
     * @throws Exception
4878
     *
4879
     * @return string The DKIM signature value
4880
     */
4881
    public function DKIM_Sign($signHeader)
4882
    {
4883
        if (!defined('PKCS7_TEXT')) {
4884
            if ($this->exceptions) {
4885
                throw new Exception($this->lang('extension_missing') . 'openssl');
4886
            }
4887
 
4888
            return '';
4889
        }
4890
        $privKeyStr = !empty($this->DKIM_private_string) ?
4891
            $this->DKIM_private_string :
4892
            file_get_contents($this->DKIM_private);
4893
        if ('' !== $this->DKIM_passphrase) {
4894
            $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
4895
        } else {
4896
            $privKey = openssl_pkey_get_private($privKeyStr);
4897
        }
4898
        if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) {
4899
            if (\PHP_MAJOR_VERSION < 8) {
4900
                openssl_pkey_free($privKey);
4901
            }
4902
 
4903
            return base64_encode($signature);
4904
        }
4905
        if (\PHP_MAJOR_VERSION < 8) {
4906
            openssl_pkey_free($privKey);
4907
        }
4908
 
4909
        return '';
4910
    }
4911
 
4912
    /**
4913
     * Generate a DKIM canonicalization header.
4914
     * Uses the 'relaxed' algorithm from RFC6376 section 3.4.2.
4915
     * Canonicalized headers should *always* use CRLF, regardless of mailer setting.
4916
     *
4917
     * @see https://tools.ietf.org/html/rfc6376#section-3.4.2
4918
     *
4919
     * @param string $signHeader Header
4920
     *
4921
     * @return string
4922
     */
4923
    public function DKIM_HeaderC($signHeader)
4924
    {
4925
        //Normalize breaks to CRLF (regardless of the mailer)
4926
        $signHeader = static::normalizeBreaks($signHeader, self::CRLF);
4927
        //Unfold header lines
4928
        //Note PCRE \s is too broad a definition of whitespace; RFC5322 defines it as `[ \t]`
4929
        //@see https://tools.ietf.org/html/rfc5322#section-2.2
4930
        //That means this may break if you do something daft like put vertical tabs in your headers.
4931
        $signHeader = preg_replace('/\r\n[ \t]+/', ' ', $signHeader);
4932
        //Break headers out into an array
4933
        $lines = explode(self::CRLF, $signHeader);
4934
        foreach ($lines as $key => $line) {
4935
            //If the header is missing a :, skip it as it's invalid
4936
            //This is likely to happen because the explode() above will also split
4937
            //on the trailing LE, leaving an empty line
4938
            if (strpos($line, ':') === false) {
4939
                continue;
4940
            }
4941
            list($heading, $value) = explode(':', $line, 2);
4942
            //Lower-case header name
4943
            $heading = strtolower($heading);
4944
            //Collapse white space within the value, also convert WSP to space
4945
            $value = preg_replace('/[ \t]+/', ' ', $value);
4946
            //RFC6376 is slightly unclear here - it says to delete space at the *end* of each value
4947
            //But then says to delete space before and after the colon.
4948
            //Net result is the same as trimming both ends of the value.
4949
            //By elimination, the same applies to the field name
4950
            $lines[$key] = trim($heading, " \t") . ':' . trim($value, " \t");
4951
        }
4952
 
4953
        return implode(self::CRLF, $lines);
4954
    }
4955
 
4956
    /**
4957
     * Generate a DKIM canonicalization body.
4958
     * Uses the 'simple' algorithm from RFC6376 section 3.4.3.
4959
     * Canonicalized bodies should *always* use CRLF, regardless of mailer setting.
4960
     *
4961
     * @see https://tools.ietf.org/html/rfc6376#section-3.4.3
4962
     *
4963
     * @param string $body Message Body
4964
     *
4965
     * @return string
4966
     */
4967
    public function DKIM_BodyC($body)
4968
    {
4969
        if (empty($body)) {
4970
            return self::CRLF;
4971
        }
4972
        //Normalize line endings to CRLF
4973
        $body = static::normalizeBreaks($body, self::CRLF);
4974
 
4975
        //Reduce multiple trailing line breaks to a single one
4976
        return static::stripTrailingBreaks($body) . self::CRLF;
4977
    }
4978
 
4979
    /**
4980
     * Create the DKIM header and body in a new message header.
4981
     *
4982
     * @param string $headers_line Header lines
4983
     * @param string $subject      Subject
4984
     * @param string $body         Body
4985
     *
4986
     * @throws Exception
4987
     *
4988
     * @return string
4989
     */
4990
    public function DKIM_Add($headers_line, $subject, $body)
4991
    {
4992
        $DKIMsignatureType = 'rsa-sha256'; //Signature & hash algorithms
4993
        $DKIMcanonicalization = 'relaxed/simple'; //Canonicalization methods of header & body
4994
        $DKIMquery = 'dns/txt'; //Query method
4995
        $DKIMtime = time();
4996
        //Always sign these headers without being asked
4997
        //Recommended list from https://tools.ietf.org/html/rfc6376#section-5.4.1
4998
        $autoSignHeaders = [
4999
            'from',
5000
            'to',
5001
            'cc',
5002
            'date',
5003
            'subject',
5004
            'reply-to',
5005
            'message-id',
5006
            'content-type',
5007
            'mime-version',
5008
            'x-mailer',
5009
        ];
5010
        if (stripos($headers_line, 'Subject') === false) {
5011
            $headers_line .= 'Subject: ' . $subject . static::$LE;
5012
        }
5013
        $headerLines = explode(static::$LE, $headers_line);
5014
        $currentHeaderLabel = '';
5015
        $currentHeaderValue = '';
5016
        $parsedHeaders = [];
5017
        $headerLineIndex = 0;
5018
        $headerLineCount = count($headerLines);
5019
        foreach ($headerLines as $headerLine) {
5020
            $matches = [];
5021
            if (preg_match('/^([^ \t]*?)(?::[ \t]*)(.*)$/', $headerLine, $matches)) {
5022
                if ($currentHeaderLabel !== '') {
5023
                    //We were previously in another header; This is the start of a new header, so save the previous one
5024
                    $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue];
5025
                }
5026
                $currentHeaderLabel = $matches[1];
5027
                $currentHeaderValue = $matches[2];
5028
            } elseif (preg_match('/^[ \t]+(.*)$/', $headerLine, $matches)) {
5029
                //This is a folded continuation of the current header, so unfold it
5030
                $currentHeaderValue .= ' ' . $matches[1];
5031
            }
5032
            ++$headerLineIndex;
5033
            if ($headerLineIndex >= $headerLineCount) {
5034
                //This was the last line, so finish off this header
5035
                $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue];
5036
            }
5037
        }
5038
        $copiedHeaders = [];
5039
        $headersToSignKeys = [];
5040
        $headersToSign = [];
5041
        foreach ($parsedHeaders as $header) {
5042
            //Is this header one that must be included in the DKIM signature?
5043
            if (in_array(strtolower($header['label']), $autoSignHeaders, true)) {
5044
                $headersToSignKeys[] = $header['label'];
5045
                $headersToSign[] = $header['label'] . ': ' . $header['value'];
5046
                if ($this->DKIM_copyHeaderFields) {
5047
                    $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC
5048
                        str_replace('|', '=7C', $this->DKIM_QP($header['value']));
5049
                }
5050
                continue;
5051
            }
5052
            //Is this an extra custom header we've been asked to sign?
5053
            if (in_array($header['label'], $this->DKIM_extraHeaders, true)) {
5054
                //Find its value in custom headers
5055
                foreach ($this->CustomHeader as $customHeader) {
5056
                    if ($customHeader[0] === $header['label']) {
5057
                        $headersToSignKeys[] = $header['label'];
5058
                        $headersToSign[] = $header['label'] . ': ' . $header['value'];
5059
                        if ($this->DKIM_copyHeaderFields) {
5060
                            $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC
5061
                                str_replace('|', '=7C', $this->DKIM_QP($header['value']));
5062
                        }
5063
                        //Skip straight to the next header
5064
                        continue 2;
5065
                    }
5066
                }
5067
            }
5068
        }
5069
        $copiedHeaderFields = '';
5070
        if ($this->DKIM_copyHeaderFields && count($copiedHeaders) > 0) {
5071
            //Assemble a DKIM 'z' tag
5072
            $copiedHeaderFields = ' z=';
5073
            $first = true;
5074
            foreach ($copiedHeaders as $copiedHeader) {
5075
                if (!$first) {
5076
                    $copiedHeaderFields .= static::$LE . ' |';
5077
                }
5078
                //Fold long values
5079
                if (strlen($copiedHeader) > self::STD_LINE_LENGTH - 3) {
5080
                    $copiedHeaderFields .= substr(
5081
                        chunk_split($copiedHeader, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS),
5082
                        0,
5083
                        -strlen(static::$LE . self::FWS)
5084
                    );
5085
                } else {
5086
                    $copiedHeaderFields .= $copiedHeader;
5087
                }
5088
                $first = false;
5089
            }
5090
            $copiedHeaderFields .= ';' . static::$LE;
5091
        }
5092
        $headerKeys = ' h=' . implode(':', $headersToSignKeys) . ';' . static::$LE;
5093
        $headerValues = implode(static::$LE, $headersToSign);
5094
        $body = $this->DKIM_BodyC($body);
5095
        //Base64 of packed binary SHA-256 hash of body
5096
        $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body)));
5097
        $ident = '';
5098
        if ('' !== $this->DKIM_identity) {
5099
            $ident = ' i=' . $this->DKIM_identity . ';' . static::$LE;
5100
        }
5101
        //The DKIM-Signature header is included in the signature *except for* the value of the `b` tag
5102
        //which is appended after calculating the signature
5103
        //https://tools.ietf.org/html/rfc6376#section-3.5
5104
        $dkimSignatureHeader = 'DKIM-Signature: v=1;' .
5105
            ' d=' . $this->DKIM_domain . ';' .
5106
            ' s=' . $this->DKIM_selector . ';' . static::$LE .
5107
            ' a=' . $DKIMsignatureType . ';' .
5108
            ' q=' . $DKIMquery . ';' .
5109
            ' t=' . $DKIMtime . ';' .
5110
            ' c=' . $DKIMcanonicalization . ';' . static::$LE .
5111
            $headerKeys .
5112
            $ident .
5113
            $copiedHeaderFields .
5114
            ' bh=' . $DKIMb64 . ';' . static::$LE .
5115
            ' b=';
5116
        //Canonicalize the set of headers
5117
        $canonicalizedHeaders = $this->DKIM_HeaderC(
5118
            $headerValues . static::$LE . $dkimSignatureHeader
5119
        );
5120
        $signature = $this->DKIM_Sign($canonicalizedHeaders);
5121
        $signature = trim(chunk_split($signature, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS));
5122
 
5123
        return static::normalizeBreaks($dkimSignatureHeader . $signature);
5124
    }
5125
 
5126
    /**
5127
     * Detect if a string contains a line longer than the maximum line length
5128
     * allowed by RFC 2822 section 2.1.1.
5129
     *
5130
     * @param string $str
5131
     *
5132
     * @return bool
5133
     */
5134
    public static function hasLineLongerThanMax($str)
5135
    {
5136
        return (bool) preg_match('/^(.{' . (self::MAX_LINE_LENGTH + strlen(static::$LE)) . ',})/m', $str);
5137
    }
5138
 
5139
    /**
5140
     * If a string contains any "special" characters, double-quote the name,
5141
     * and escape any double quotes with a backslash.
5142
     *
5143
     * @param string $str
5144
     *
5145
     * @return string
5146
     *
5147
     * @see RFC822 3.4.1
5148
     */
5149
    public static function quotedString($str)
5150
    {
5151
        if (preg_match('/[ ()<>@,;:"\/\[\]?=]/', $str)) {
5152
            //If the string contains any of these chars, it must be double-quoted
5153
            //and any double quotes must be escaped with a backslash
5154
            return '"' . str_replace('"', '\\"', $str) . '"';
5155
        }
5156
 
5157
        //Return the string untouched, it doesn't need quoting
5158
        return $str;
5159
    }
5160
 
5161
    /**
5162
     * Allows for public read access to 'to' property.
5163
     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
5164
     *
5165
     * @return array
5166
     */
5167
    public function getToAddresses()
5168
    {
5169
        return $this->to;
5170
    }
5171
 
5172
    /**
5173
     * Allows for public read access to 'cc' property.
5174
     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
5175
     *
5176
     * @return array
5177
     */
5178
    public function getCcAddresses()
5179
    {
5180
        return $this->cc;
5181
    }
5182
 
5183
    /**
5184
     * Allows for public read access to 'bcc' property.
5185
     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
5186
     *
5187
     * @return array
5188
     */
5189
    public function getBccAddresses()
5190
    {
5191
        return $this->bcc;
5192
    }
5193
 
5194
    /**
5195
     * Allows for public read access to 'ReplyTo' property.
5196
     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
5197
     *
5198
     * @return array
5199
     */
5200
    public function getReplyToAddresses()
5201
    {
5202
        return $this->ReplyTo;
5203
    }
5204
 
5205
    /**
5206
     * Allows for public read access to 'all_recipients' property.
5207
     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
5208
     *
5209
     * @return array
5210
     */
5211
    public function getAllRecipientAddresses()
5212
    {
5213
        return $this->all_recipients;
5214
    }
5215
 
5216
    /**
5217
     * Perform a callback.
5218
     *
5219
     * @param bool   $isSent
5220
     * @param array  $to
5221
     * @param array  $cc
5222
     * @param array  $bcc
5223
     * @param string $subject
5224
     * @param string $body
5225
     * @param string $from
5226
     * @param array  $extra
5227
     */
5228
    protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from, $extra)
5229
    {
5230
        if (!empty($this->action_function) && is_callable($this->action_function)) {
5231
            call_user_func($this->action_function, $isSent, $to, $cc, $bcc, $subject, $body, $from, $extra);
5232
        }
5233
    }
5234
 
5235
    /**
5236
     * Get the OAuthTokenProvider instance.
5237
     *
5238
     * @return OAuthTokenProvider
5239
     */
5240
    public function getOAuth()
5241
    {
5242
        return $this->oauth;
5243
    }
5244
 
5245
    /**
5246
     * Set an OAuthTokenProvider instance.
5247
     */
5248
    public function setOAuth(OAuthTokenProvider $oauth)
5249
    {
5250
        $this->oauth = $oauth;
5251
    }
5252
}