Subversion Repositories cheapmusic

Rev

Rev 25 | Details | Compare with Previous | Last modification | View Log | RSS feed

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