Guest User

Untitled

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