SHARE
TWEET

Untitled

a guest Jan 25th, 2016 177 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. /**
  3.  * PHPMailer - PHP email creation and transport class.
  4.  * PHP Version 5
  5.  * @package PHPMailer
  6.  * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
  7.  * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  8.  * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  9.  * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  10.  * @author Brent R. Matzelle (original founder)
  11.  * @copyright 2012 - 2014 Marcus Bointon
  12.  * @copyright 2010 - 2012 Jim Jagielski
  13.  * @copyright 2004 - 2009 Andy Prevost
  14.  * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  15.  * @note This program is distributed in the hope that it will be useful - WITHOUT
  16.  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  17.  * FITNESS FOR A PARTICULAR PURPOSE.
  18.  */
  19.  
  20. /**
  21.  * PHPMailer - PHP email creation and transport class.
  22.  * @package PHPMailer
  23.  * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  24.  * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  25.  * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  26.  * @author Brent R. Matzelle (original founder)
  27.  */
  28. class PHPMailer
  29. {
  30.     /**
  31.      * The PHPMailer Version number.
  32.      * @type string
  33.      */
  34.     public $Version = '5.2.9';
  35.  
  36.     /**
  37.      * Email priority.
  38.      * Options: 1 = High, 3 = Normal, 5 = low.
  39.      * @type integer
  40.      */
  41.     public $Priority = 3;
  42.  
  43.     /**
  44.      * The character set of the message.
  45.      * @type string
  46.      */
  47.     public $CharSet = 'iso-8859-1';
  48.  
  49.     /**
  50.      * The MIME Content-type of the message.
  51.      * @type string
  52.      */
  53.     public $ContentType = 'text/plain';
  54.  
  55.     /**
  56.      * The message encoding.
  57.      * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
  58.      * @type string
  59.      */
  60.     public $Encoding = '8bit';
  61.  
  62.     /**
  63.      * Holds the most recent mailer error message.
  64.      * @type string
  65.      */
  66.     public $ErrorInfo = '';
  67.  
  68.     /**
  69.      * The From email address for the message.
  70.      * @type string
  71.      */
  72.     public $From = 'root@localhost';
  73.  
  74.     /**
  75.      * The From name of the message.
  76.      * @type string
  77.      */
  78.     public $FromName = 'Root User';
  79.  
  80.     /**
  81.      * The Sender email (Return-Path) of the message.
  82.      * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  83.      * @type string
  84.      */
  85.     public $Sender = '';
  86.  
  87.     /**
  88.      * The Return-Path of the message.
  89.      * If empty, it will be set to either From or Sender.
  90.      * @type string
  91.      * @deprecated Email senders should never set a return-path header;
  92.      * it's the receiver's job (RFC5321 section 4.4), so this no longer does anything.
  93.      * @link https://tools.ietf.org/html/rfc5321#section-4.4 RFC5321 reference
  94.      */
  95.     public $ReturnPath = '';
  96.  
  97.     /**
  98.      * The Subject of the message.
  99.      * @type string
  100.      */
  101.     public $Subject = '';
  102.  
  103.     /**
  104.      * An HTML or plain text message body.
  105.      * If HTML then call isHTML(true).
  106.      * @type string
  107.      */
  108.     public $Body = '';
  109.  
  110.     /**
  111.      * The plain-text message body.
  112.      * This body can be read by mail clients that do not have HTML email
  113.      * capability such as mutt & Eudora.
  114.      * Clients that can read HTML will view the normal Body.
  115.      * @type string
  116.      */
  117.     public $AltBody = '';
  118.  
  119.     /**
  120.      * An iCal message part body.
  121.      * Only supported in simple alt or alt_inline message types
  122.      * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator
  123.      * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
  124.      * @link http://kigkonsult.se/iCalcreator/
  125.      * @type string
  126.      */
  127.     public $Ical = '';
  128.  
  129.     /**
  130.      * The complete compiled MIME message body.
  131.      * @access protected
  132.      * @type string
  133.      */
  134.     protected $MIMEBody = '';
  135.  
  136.     /**
  137.      * The complete compiled MIME message headers.
  138.      * @type string
  139.      * @access protected
  140.      */
  141.     protected $MIMEHeader = '';
  142.  
  143.     /**
  144.      * Extra headers that createHeader() doesn't fold in.
  145.      * @type string
  146.      * @access protected
  147.      */
  148.     protected $mailHeader = '';
  149.  
  150.     /**
  151.      * Word-wrap the message body to this number of chars.
  152.      * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
  153.      * @type integer
  154.      */
  155.     public $WordWrap = 0;
  156.  
  157.     /**
  158.      * Which method to use to send mail.
  159.      * Options: "mail", "sendmail", or "smtp".
  160.      * @type string
  161.      */
  162.     public $Mailer = 'mail';
  163.  
  164.     /**
  165.      * The path to the sendmail program.
  166.      * @type string
  167.      */
  168.     public $Sendmail = '/usr/sbin/sendmail';
  169.  
  170.     /**
  171.      * Whether mail() uses a fully sendmail-compatible MTA.
  172.      * One which supports sendmail's "-oi -f" options.
  173.      * @type boolean
  174.      */
  175.     public $UseSendmailOptions = true;
  176.  
  177.     /**
  178.      * Path to PHPMailer plugins.
  179.      * Useful if the SMTP class is not in the PHP include path.
  180.      * @type string
  181.      * @deprecated Should not be needed now there is an autoloader.
  182.      */
  183.     public $PluginDir = '';
  184.  
  185.     /**
  186.      * The email address that a reading confirmation should be sent to.
  187.      * @type string
  188.      */
  189.     public $ConfirmReadingTo = '';
  190.  
  191.     /**
  192.      * The hostname to use in Message-Id and Received headers
  193.      * and as default HELO string.
  194.      * If empty, the value returned
  195.      * by SERVER_NAME is used or 'localhost.localdomain'.
  196.      * @type string
  197.      */
  198.     public $Hostname = '';
  199.  
  200.     /**
  201.      * An ID to be used in the Message-Id header.
  202.      * If empty, a unique id will be generated.
  203.      * @type string
  204.      */
  205.     public $MessageID = '';
  206.  
  207.     /**
  208.      * The message Date to be used in the Date header.
  209.      * If empty, the current date will be added.
  210.      * @type string
  211.      */
  212.     public $MessageDate = '';
  213.  
  214.     /**
  215.      * SMTP hosts.
  216.      * Either a single hostname or multiple semicolon-delimited hostnames.
  217.      * You can also specify a different port
  218.      * for each host by using this format: [hostname:port]
  219.      * (e.g. "smtp1.example.com:25;smtp2.example.com").
  220.      * You can also specify encryption type, for example:
  221.      * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
  222.      * Hosts will be tried in order.
  223.      * @type string
  224.      */
  225.     public $Host = 'localhost';
  226.  
  227.     /**
  228.      * The default SMTP server port.
  229.      * @type integer
  230.      * @TODO Why is this needed when the SMTP class takes care of it?
  231.      */
  232.     public $Port = 25;
  233.  
  234.     /**
  235.      * The SMTP HELO of the message.
  236.      * Default is $Hostname.
  237.      * @type string
  238.      * @see PHPMailer::$Hostname
  239.      */
  240.     public $Helo = '';
  241.  
  242.     /**
  243.      * The secure connection prefix.
  244.      * Options: "", "ssl" or "tls"
  245.      * @type string
  246.      */
  247.     public $SMTPSecure = '';
  248.  
  249.     /**
  250.      * Whether to use SMTP authentication.
  251.      * Uses the Username and Password properties.
  252.      * @type boolean
  253.      * @see PHPMailer::$Username
  254.      * @see PHPMailer::$Password
  255.      */
  256.     public $SMTPAuth = false;
  257.  
  258.     /**
  259.      * SMTP username.
  260.      * @type string
  261.      */
  262.     public $Username = '';
  263.  
  264.     /**
  265.      * SMTP password.
  266.      * @type string
  267.      */
  268.     public $Password = '';
  269.  
  270.     /**
  271.      * SMTP auth type.
  272.      * Options are LOGIN (default), PLAIN, NTLM, CRAM-MD5
  273.      * @type string
  274.      */
  275.     public $AuthType = '';
  276.  
  277.     /**
  278.      * SMTP realm.
  279.      * Used for NTLM auth
  280.      * @type string
  281.      */
  282.     public $Realm = '';
  283.  
  284.     /**
  285.      * SMTP workstation.
  286.      * Used for NTLM auth
  287.      * @type string
  288.      */
  289.     public $Workstation = '';
  290.  
  291.     /**
  292.      * The SMTP server timeout in seconds.
  293.      * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
  294.      * @type integer
  295.      */
  296.     public $Timeout = 300;
  297.  
  298.     /**
  299.      * SMTP class debug output mode.
  300.      * Debug output level.
  301.      * Options:
  302.      * * `0` No output
  303.      * * `1` Commands
  304.      * * `2` Data and commands
  305.      * * `3` As 2 plus connection status
  306.      * * `4` Low-level data output
  307.      * @type integer
  308.      * @see SMTP::$do_debug
  309.      */
  310.     public $SMTPDebug = 0;
  311.  
  312.     /**
  313.      * How to handle debug output.
  314.      * Options:
  315.      * * `echo` Output plain-text as-is, appropriate for CLI
  316.      * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
  317.      * * `error_log` Output to error log as configured in php.ini
  318.      *
  319.      * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
  320.      * <code>
  321.      * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
  322.      * </code>
  323.      * @type string|callable
  324.      * @see SMTP::$Debugoutput
  325.      */
  326.     public $Debugoutput = 'echo';
  327.  
  328.     /**
  329.      * Whether to keep SMTP connection open after each message.
  330.      * If this is set to true then to close the connection
  331.      * requires an explicit call to smtpClose().
  332.      * @type boolean
  333.      */
  334.     public $SMTPKeepAlive = false;
  335.  
  336.     /**
  337.      * Whether to split multiple to addresses into multiple messages
  338.      * or send them all in one message.
  339.      * @type boolean
  340.      */
  341.     public $SingleTo = false;
  342.  
  343.     /**
  344.      * Storage for addresses when SingleTo is enabled.
  345.      * @type array
  346.      * @TODO This should really not be public
  347.      */
  348.     public $SingleToArray = array();
  349.  
  350.     /**
  351.      * Whether to generate VERP addresses on send.
  352.      * Only applicable when sending via SMTP.
  353.      * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
  354.      * @link http://www.postfix.org/VERP_README.html Postfix VERP info
  355.      * @type boolean
  356.      */
  357.     public $do_verp = false;
  358.  
  359.     /**
  360.      * Whether to allow sending messages with an empty body.
  361.      * @type boolean
  362.      */
  363.     public $AllowEmpty = false;
  364.  
  365.     /**
  366.      * The default line ending.
  367.      * @note The default remains "\n". We force CRLF where we know
  368.      *        it must be used via self::CRLF.
  369.      * @type string
  370.      */
  371.     public $LE = "\n";
  372.  
  373.     /**
  374.      * DKIM selector.
  375.      * @type string
  376.      */
  377.     public $DKIM_selector = '';
  378.  
  379.     /**
  380.      * DKIM Identity.
  381.      * Usually the email address used as the source of the email
  382.      * @type string
  383.      */
  384.     public $DKIM_identity = '';
  385.  
  386.     /**
  387.      * DKIM passphrase.
  388.      * Used if your key is encrypted.
  389.      * @type string
  390.      */
  391.     public $DKIM_passphrase = '';
  392.  
  393.     /**
  394.      * DKIM signing domain name.
  395.      * @example 'example.com'
  396.      * @type string
  397.      */
  398.     public $DKIM_domain = '';
  399.  
  400.     /**
  401.      * DKIM private key file path.
  402.      * @type string
  403.      */
  404.     public $DKIM_private = '';
  405.  
  406.     /**
  407.      * Callback Action function name.
  408.      *
  409.      * The function that handles the result of the send email action.
  410.      * It is called out by send() for each email sent.
  411.      *
  412.      * Value can be any php callable: http://www.php.net/is_callable
  413.      *
  414.      * Parameters:
  415.      *   boolean $result        result of the send action
  416.      *   string  $to            email address of the recipient
  417.      *   string  $cc            cc email addresses
  418.      *   string  $bcc           bcc email addresses
  419.      *   string  $subject       the subject
  420.      *   string  $body          the email body
  421.      *   string  $from          email address of sender
  422.      * @type string
  423.      */
  424.     public $action_function = '';
  425.  
  426.     /**
  427.      * What to put in the X-Mailer header.
  428.      * Options: An empty string for PHPMailer default, whitespace for none, or a string to use
  429.      * @type string
  430.      */
  431.     public $XMailer = '';
  432.  
  433.     /**
  434.      * An instance of the SMTP sender class.
  435.      * @type SMTP
  436.      * @access protected
  437.      */
  438.     protected $smtp = null;
  439.  
  440.     /**
  441.      * The array of 'to' addresses.
  442.      * @type array
  443.      * @access protected
  444.      */
  445.     protected $to = array();
  446.  
  447.     /**
  448.      * The array of 'cc' addresses.
  449.      * @type array
  450.      * @access protected
  451.      */
  452.     protected $cc = array();
  453.  
  454.     /**
  455.      * The array of 'bcc' addresses.
  456.      * @type array
  457.      * @access protected
  458.      */
  459.     protected $bcc = array();
  460.  
  461.     /**
  462.      * The array of reply-to names and addresses.
  463.      * @type array
  464.      * @access protected
  465.      */
  466.     protected $ReplyTo = array();
  467.  
  468.     /**
  469.      * An array of all kinds of addresses.
  470.      * Includes all of $to, $cc, $bcc, $replyto
  471.      * @type array
  472.      * @access protected
  473.      */
  474.     protected $all_recipients = array();
  475.  
  476.     /**
  477.      * The array of attachments.
  478.      * @type array
  479.      * @access protected
  480.      */
  481.     protected $attachment = array();
  482.  
  483.     /**
  484.      * The array of custom headers.
  485.      * @type array
  486.      * @access protected
  487.      */
  488.     protected $CustomHeader = array();
  489.  
  490.     /**
  491.      * The most recent Message-ID (including angular brackets).
  492.      * @type string
  493.      * @access protected
  494.      */
  495.     protected $lastMessageID = '';
  496.  
  497.     /**
  498.      * The message's MIME type.
  499.      * @type string
  500.      * @access protected
  501.      */
  502.     protected $message_type = '';
  503.  
  504.     /**
  505.      * The array of MIME boundary strings.
  506.      * @type array
  507.      * @access protected
  508.      */
  509.     protected $boundary = array();
  510.  
  511.     /**
  512.      * The array of available languages.
  513.      * @type array
  514.      * @access protected
  515.      */
  516.     protected $language = array();
  517.  
  518.     /**
  519.      * The number of errors encountered.
  520.      * @type integer
  521.      * @access protected
  522.      */
  523.     protected $error_count = 0;
  524.  
  525.     /**
  526.      * The S/MIME certificate file path.
  527.      * @type string
  528.      * @access protected
  529.      */
  530.     protected $sign_cert_file = '';
  531.  
  532.     /**
  533.      * The S/MIME key file path.
  534.      * @type string
  535.      * @access protected
  536.      */
  537.     protected $sign_key_file = '';
  538.  
  539.     /**
  540.      * The optional S/MIME extra certificates ("CA Chain") file path.
  541.      * @type string
  542.      * @access protected
  543.      */
  544.     protected $sign_extracerts_file = '';
  545.  
  546.     /**
  547.      * The S/MIME password for the key.
  548.      * Used only if the key is encrypted.
  549.      * @type string
  550.      * @access protected
  551.      */
  552.     protected $sign_key_pass = '';
  553.  
  554.     /**
  555.      * Whether to throw exceptions for errors.
  556.      * @type boolean
  557.      * @access protected
  558.      */
  559.     protected $exceptions = false;
  560.  
  561.     /**
  562.      * Error severity: message only, continue processing.
  563.      */
  564.     const STOP_MESSAGE = 0;
  565.  
  566.     /**
  567.      * Error severity: message, likely ok to continue processing.
  568.      */
  569.     const STOP_CONTINUE = 1;
  570.  
  571.     /**
  572.      * Error severity: message, plus full stop, critical error reached.
  573.      */
  574.     const STOP_CRITICAL = 2;
  575.  
  576.     /**
  577.      * SMTP RFC standard line ending.
  578.      */
  579.     const CRLF = "\r\n";
  580.  
  581.     /**
  582.      * Constructor.
  583.      * @param boolean $exceptions Should we throw external exceptions?
  584.      */
  585.     public function __construct($exceptions = false)
  586.     {
  587.         $this->exceptions = (boolean)$exceptions;
  588.     }
  589.  
  590.     /**
  591.      * Destructor.
  592.      */
  593.     public function __destruct()
  594.     {
  595.         //Close any open SMTP connection nicely
  596.         if ($this->Mailer == 'smtp') {
  597.             $this->smtpClose();
  598.         }
  599.     }
  600.  
  601.     /**
  602.      * Call mail() in a safe_mode-aware fashion.
  603.      * Also, unless sendmail_path points to sendmail (or something that
  604.      * claims to be sendmail), don't pass params (not a perfect fix,
  605.      * but it will do)
  606.      * @param string $to To
  607.      * @param string $subject Subject
  608.      * @param string $body Message Body
  609.      * @param string $header Additional Header(s)
  610.      * @param string $params Params
  611.      * @access private
  612.      * @return boolean
  613.      */
  614.     private function mailPassthru($to, $subject, $body, $header, $params)
  615.     {
  616.         //Check overloading of mail function to avoid double-encoding
  617.         if (ini_get('mbstring.func_overload') & 1) {
  618.             $subject = $this->secureHeader($subject);
  619.         } else {
  620.             $subject = $this->encodeHeader($this->secureHeader($subject));
  621.         }
  622.         if (ini_get('safe_mode') || !($this->UseSendmailOptions)) {
  623.             $result = @mail($to, $subject, $body, $header);
  624.         } else {
  625.             $result = @mail($to, $subject, $body, $header, $params);
  626.         }
  627.         return $result;
  628.     }
  629.  
  630.     /**
  631.      * Output debugging info via user-defined method.
  632.      * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
  633.      * @see PHPMailer::$Debugoutput
  634.      * @see PHPMailer::$SMTPDebug
  635.      * @param string $str
  636.      */
  637.     protected function edebug($str)
  638.     {
  639.         if ($this->SMTPDebug <= 0) {
  640.             return;
  641.         }
  642.         //Avoid clash with built-in function names
  643.         if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
  644.             call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
  645.             return;
  646.         }
  647.         switch ($this->Debugoutput) {
  648.             case 'error_log':
  649.                 //Don't output, just log
  650.                 error_log($str);
  651.                 break;
  652.             case 'html':
  653.                 //Cleans up output a bit for a better looking, HTML-safe output
  654.                 echo htmlentities(
  655.                     preg_replace('/[\r\n]+/', '', $str),
  656.                     ENT_QUOTES,
  657.                     'UTF-8'
  658.                 )
  659.                 . "<br>\n";
  660.                 break;
  661.             case 'echo':
  662.             default:
  663.                 //Normalize line breaks
  664.                 $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
  665.                 echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
  666.                     "\n",
  667.                     "\n                   \t                  ",
  668.                     trim($str)
  669.                 ) . "\n";
  670.         }
  671.     }
  672.  
  673.     /**
  674.      * Sets message type to HTML or plain.
  675.      * @param boolean $isHtml True for HTML mode.
  676.      * @return void
  677.      */
  678.     public function isHTML($isHtml = true)
  679.     {
  680.         if ($isHtml) {
  681.             $this->ContentType = 'text/html';
  682.         } else {
  683.             $this->ContentType = 'text/plain';
  684.         }
  685.     }
  686.  
  687.     /**
  688.      * Send messages using SMTP.
  689.      * @return void
  690.      */
  691.     public function isSMTP()
  692.     {
  693.         $this->Mailer = 'smtp';
  694.     }
  695.  
  696.     /**
  697.      * Send messages using PHP's mail() function.
  698.      * @return void
  699.      */
  700.     public function isMail()
  701.     {
  702.         $this->Mailer = 'mail';
  703.     }
  704.  
  705.     /**
  706.      * Send messages using $Sendmail.
  707.      * @return void
  708.      */
  709.     public function isSendmail()
  710.     {
  711.         $ini_sendmail_path = ini_get('sendmail_path');
  712.  
  713.         if (!stristr($ini_sendmail_path, 'sendmail')) {
  714.             $this->Sendmail = '/usr/sbin/sendmail';
  715.         } else {
  716.             $this->Sendmail = $ini_sendmail_path;
  717.         }
  718.         $this->Mailer = 'sendmail';
  719.     }
  720.  
  721.     /**
  722.      * Send messages using qmail.
  723.      * @return void
  724.      */
  725.     public function isQmail()
  726.     {
  727.         $ini_sendmail_path = ini_get('sendmail_path');
  728.  
  729.         if (!stristr($ini_sendmail_path, 'qmail')) {
  730.             $this->Sendmail = '/var/qmail/bin/qmail-inject';
  731.         } else {
  732.             $this->Sendmail = $ini_sendmail_path;
  733.         }
  734.         $this->Mailer = 'qmail';
  735.     }
  736.  
  737.     /**
  738.      * Add a "To" address.
  739.      * @param string $address
  740.      * @param string $name
  741.      * @return boolean true on success, false if address already used
  742.      */
  743.     public function addAddress($address, $name = '')
  744.     {
  745.         return $this->addAnAddress('to', $address, $name);
  746.     }
  747.  
  748.     /**
  749.      * Add a "CC" address.
  750.      * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
  751.      * @param string $address
  752.      * @param string $name
  753.      * @return boolean true on success, false if address already used
  754.      */
  755.     public function addCC($address, $name = '')
  756.     {
  757.         return $this->addAnAddress('cc', $address, $name);
  758.     }
  759.  
  760.     /**
  761.      * Add a "BCC" address.
  762.      * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
  763.      * @param string $address
  764.      * @param string $name
  765.      * @return boolean true on success, false if address already used
  766.      */
  767.     public function addBCC($address, $name = '')
  768.     {
  769.         return $this->addAnAddress('bcc', $address, $name);
  770.     }
  771.  
  772.     /**
  773.      * Add a "Reply-to" address.
  774.      * @param string $address
  775.      * @param string $name
  776.      * @return boolean
  777.      */
  778.     public function addReplyTo($address, $name = '')
  779.     {
  780.         return $this->addAnAddress('Reply-To', $address, $name);
  781.     }
  782.  
  783.     /**
  784.      * Add an address to one of the recipient arrays.
  785.      * Addresses that have been added already return false, but do not throw exceptions
  786.      * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
  787.      * @param string $address The email address to send to
  788.      * @param string $name
  789.      * @throws phpmailerException
  790.      * @return boolean true on success, false if address already used or invalid in some way
  791.      * @access protected
  792.      */
  793.     protected function addAnAddress($kind, $address, $name = '')
  794.     {
  795.         if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
  796.             $this->setError($this->lang('Invalid recipient array') . ': ' . $kind);
  797.             $this->edebug($this->lang('Invalid recipient array') . ': ' . $kind);
  798.             if ($this->exceptions) {
  799.                 throw new phpmailerException('Invalid recipient array: ' . $kind);
  800.             }
  801.             return false;
  802.         }
  803.         $address = trim($address);
  804.         $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  805.         if (!$this->validateAddress($address)) {
  806.             $this->setError($this->lang('invalid_address') . ': ' . $address);
  807.             $this->edebug($this->lang('invalid_address') . ': ' . $address);
  808.             if ($this->exceptions) {
  809.                 throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
  810.             }
  811.             return false;
  812.         }
  813.         if ($kind != 'Reply-To') {
  814.             if (!isset($this->all_recipients[strtolower($address)])) {
  815.                 array_push($this->$kind, array($address, $name));
  816.                 $this->all_recipients[strtolower($address)] = true;
  817.                 return true;
  818.             }
  819.         } else {
  820.             if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  821.                 $this->ReplyTo[strtolower($address)] = array($address, $name);
  822.                 return true;
  823.             }
  824.         }
  825.         return false;
  826.     }
  827.  
  828.     /**
  829.      * Set the From and FromName properties.
  830.      * @param string $address
  831.      * @param string $name
  832.      * @param boolean $auto Whether to also set the Sender address, defaults to true
  833.      * @throws phpmailerException
  834.      * @return boolean
  835.      */
  836.     public function setFrom($address, $name = '', $auto = true)
  837.     {
  838.         $address = trim($address);
  839.         $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  840.         if (!$this->validateAddress($address)) {
  841.             $this->setError($this->lang('invalid_address') . ': ' . $address);
  842.             $this->edebug($this->lang('invalid_address') . ': ' . $address);
  843.             if ($this->exceptions) {
  844.                 throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
  845.             }
  846.             return false;
  847.         }
  848.         $this->From = $address;
  849.         $this->FromName = $name;
  850.         if ($auto) {
  851.             if (empty($this->Sender)) {
  852.                 $this->Sender = $address;
  853.             }
  854.         }
  855.         return true;
  856.     }
  857.  
  858.     /**
  859.      * Return the Message-ID header of the last email.
  860.      * Technically this is the value from the last time the headers were created,
  861.      * but it's also the message ID of the last sent message except in
  862.      * pathological cases.
  863.      * @return string
  864.      */
  865.     public function getLastMessageID()
  866.     {
  867.         return $this->lastMessageID;
  868.     }
  869.  
  870.     /**
  871.      * Check that a string looks like an email address.
  872.      * @param string $address The email address to check
  873.      * @param string $patternselect A selector for the validation pattern to use :
  874.      * * `auto` Pick strictest one automatically;
  875.      * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
  876.      * * `pcre` Use old PCRE implementation;
  877.      * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; same as pcre8 but does not allow 'dotless' domains;
  878.      * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
  879.      * * `noregex` Don't use a regex: super fast, really dumb.
  880.      * @return boolean
  881.      * @static
  882.      * @access public
  883.      */
  884.     public static function validateAddress($address, $patternselect = 'auto')
  885.     {
  886.         if (!$patternselect or $patternselect == 'auto') {
  887.             //Check this constant first so it works when extension_loaded() is disabled by safe mode
  888.             //Constant was added in PHP 5.2.4
  889.             if (defined('PCRE_VERSION')) {
  890.                 //This pattern can get stuck in a recursive loop in PCRE <= 8.0.2
  891.                 if (version_compare(PCRE_VERSION, '8.0.3') >= 0) {
  892.                     $patternselect = 'pcre8';
  893.                 } else {
  894.                     $patternselect = 'pcre';
  895.                 }
  896.             } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) {
  897.                 //Fall back to older PCRE
  898.                 $patternselect = 'pcre';
  899.             } else {
  900.                 //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension
  901.                 if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
  902.                     $patternselect = 'php';
  903.                 } else {
  904.                     $patternselect = 'noregex';
  905.                 }
  906.             }
  907.         }
  908.         switch ($patternselect) {
  909.             case 'pcre8':
  910.                 /**
  911.                  * Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains.
  912.                  * @link http://squiloople.com/2009/12/20/email-address-validation/
  913.                  * @copyright 2009-2010 Michael Rushton
  914.                  * Feel free to use and redistribute this code. But please keep this copyright notice.
  915.                  */
  916.                 return (boolean)preg_match(
  917.                     '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
  918.                     '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
  919.                     '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
  920.                     '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
  921.                     '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
  922.                     '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
  923.                     '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
  924.                     '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  925.                     '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
  926.                     $address
  927.                 );
  928.             case 'pcre':
  929.                 //An older regex that doesn't need a recent PCRE
  930.                 return (boolean)preg_match(
  931.                     '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' .
  932.                     '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' .
  933.                     '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' .
  934.                     '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' .
  935.                     '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' .
  936.                     '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' .
  937.                     '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' .
  938.                     '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' .
  939.                     '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  940.                     '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD',
  941.                     $address
  942.                 );
  943.             case 'html5':
  944.                 /**
  945.                  * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
  946.                  * @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
  947.                  */
  948.                 return (boolean)preg_match(
  949.                     '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
  950.                     '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
  951.                     $address
  952.                 );
  953.             case 'noregex':
  954.                 //No PCRE! Do something _very_ approximate!
  955.                 //Check the address is 3 chars or longer and contains an @ that's not the first or last char
  956.                 return (strlen($address) >= 3
  957.                     and strpos($address, '@') >= 1
  958.                     and strpos($address, '@') != strlen($address) - 1);
  959.             case 'php':
  960.             default:
  961.                 return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL);
  962.         }
  963.     }
  964.  
  965.     /**
  966.      * Create a message and send it.
  967.      * Uses the sending method specified by $Mailer.
  968.      * @throws phpmailerException
  969.      * @return boolean false on error - See the ErrorInfo property for details of the error.
  970.      */
  971.     public function send()
  972.     {
  973.         try {
  974.             if (!$this->preSend()) {
  975.                 return false;
  976.             }
  977.             return $this->postSend();
  978.         } catch (phpmailerException $exc) {
  979.             $this->mailHeader = '';
  980.             $this->setError($exc->getMessage());
  981.             if ($this->exceptions) {
  982.                 throw $exc;
  983.             }
  984.             return false;
  985.         }
  986.     }
  987.  
  988.     /**
  989.      * Prepare a message for sending.
  990.      * @throws phpmailerException
  991.      * @return boolean
  992.      */
  993.     public function preSend()
  994.     {
  995.         try {
  996.             $this->mailHeader = '';
  997.             if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  998.                 throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
  999.             }
  1000.  
  1001.             // Set whether the message is multipart/alternative
  1002.             if (!empty($this->AltBody)) {
  1003.                 $this->ContentType = 'multipart/alternative';
  1004.             }
  1005.  
  1006.             $this->error_count = 0; // reset errors
  1007.             $this->setMessageType();
  1008.             // Refuse to send an empty message unless we are specifically allowing it
  1009.             if (!$this->AllowEmpty and empty($this->Body)) {
  1010.                 throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
  1011.             }
  1012.  
  1013.             $this->MIMEHeader = $this->createHeader();
  1014.             $this->MIMEBody = $this->createBody();
  1015.  
  1016.             // To capture the complete message when using mail(), create
  1017.             // an extra header list which createHeader() doesn't fold in
  1018.             if ($this->Mailer == 'mail') {
  1019.                 if (count($this->to) > 0) {
  1020.                     $this->mailHeader .= $this->addrAppend('To', $this->to);
  1021.                 } else {
  1022.                     $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
  1023.                 }
  1024.                 $this->mailHeader .= $this->headerLine(
  1025.                     'Subject',
  1026.                     $this->encodeHeader($this->secureHeader(trim($this->Subject)))
  1027.                 );
  1028.             }
  1029.  
  1030.             // Sign with DKIM if enabled
  1031.             if (!empty($this->DKIM_domain)
  1032.                 && !empty($this->DKIM_private)
  1033.                 && !empty($this->DKIM_selector)
  1034.                 && file_exists($this->DKIM_private)) {
  1035.                 $header_dkim = $this->DKIM_Add(
  1036.                     $this->MIMEHeader . $this->mailHeader,
  1037.                     $this->encodeHeader($this->secureHeader($this->Subject)),
  1038.                     $this->MIMEBody
  1039.                 );
  1040.                 $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF .
  1041.                     str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
  1042.             }
  1043.             return true;
  1044.  
  1045.         } catch (phpmailerException $exc) {
  1046.             $this->setError($exc->getMessage());
  1047.             if ($this->exceptions) {
  1048.                 throw $exc;
  1049.             }
  1050.             return false;
  1051.         }
  1052.     }
  1053.  
  1054.     /**
  1055.      * Actually send a message.
  1056.      * Send the email via the selected mechanism
  1057.      * @throws phpmailerException
  1058.      * @return boolean
  1059.      */
  1060.     public function postSend()
  1061.     {
  1062.         try {
  1063.             // Choose the mailer and send through it
  1064.             switch ($this->Mailer) {
  1065.                 case 'sendmail':
  1066.                 case 'qmail':
  1067.                     return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
  1068.                 case 'smtp':
  1069.                     return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
  1070.                 case 'mail':
  1071.                     return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  1072.                 default:
  1073.                     $sendMethod = $this->Mailer.'Send';
  1074.                     if (method_exists($this, $sendMethod)) {
  1075.                         return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
  1076.                     }
  1077.  
  1078.                     return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  1079.             }
  1080.         } catch (phpmailerException $exc) {
  1081.             $this->setError($exc->getMessage());
  1082.             $this->edebug($exc->getMessage());
  1083.             if ($this->exceptions) {
  1084.                 throw $exc;
  1085.             }
  1086.         }
  1087.         return false;
  1088.     }
  1089.  
  1090.     /**
  1091.      * Send mail using the $Sendmail program.
  1092.      * @param string $header The message headers
  1093.      * @param string $body The message body
  1094.      * @see PHPMailer::$Sendmail
  1095.      * @throws phpmailerException
  1096.      * @access protected
  1097.      * @return boolean
  1098.      */
  1099.     protected function sendmailSend($header, $body)
  1100.     {
  1101.         if ($this->Sender != '') {
  1102.             if ($this->Mailer == 'qmail') {
  1103.                 $sendmail = sprintf('%s -f%s', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  1104.             } else {
  1105.                 $sendmail = sprintf('%s -oi -f%s -t', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  1106.             }
  1107.         } else {
  1108.             if ($this->Mailer == 'qmail') {
  1109.                 $sendmail = sprintf('%s', escapeshellcmd($this->Sendmail));
  1110.             } else {
  1111.                 $sendmail = sprintf('%s -oi -t', escapeshellcmd($this->Sendmail));
  1112.             }
  1113.         }
  1114.         if ($this->SingleTo) {
  1115.             foreach ($this->SingleToArray as $toAddr) {
  1116.                 if (!@$mail = popen($sendmail, 'w')) {
  1117.                     throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1118.                 }
  1119.                 fputs($mail, 'To: ' . $toAddr . "\n");
  1120.                 fputs($mail, $header);
  1121.                 fputs($mail, $body);
  1122.                 $result = pclose($mail);
  1123.                 $this->doCallback(
  1124.                     ($result == 0),
  1125.                     array($toAddr),
  1126.                     $this->cc,
  1127.                     $this->bcc,
  1128.                     $this->Subject,
  1129.                     $body,
  1130.                     $this->From
  1131.                 );
  1132.                 if ($result != 0) {
  1133.                     throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1134.                 }
  1135.             }
  1136.         } else {
  1137.             if (!@$mail = popen($sendmail, 'w')) {
  1138.                 throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1139.             }
  1140.             fputs($mail, $header);
  1141.             fputs($mail, $body);
  1142.             $result = pclose($mail);
  1143.             $this->doCallback(($result == 0), $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  1144.             if ($result != 0) {
  1145.                 throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1146.             }
  1147.         }
  1148.         return true;
  1149.     }
  1150.  
  1151.     /**
  1152.      * Send mail using the PHP mail() function.
  1153.      * @param string $header The message headers
  1154.      * @param string $body The message body
  1155.      * @link http://www.php.net/manual/en/book.mail.php
  1156.      * @throws phpmailerException
  1157.      * @access protected
  1158.      * @return boolean
  1159.      */
  1160.     protected function mailSend($header, $body)
  1161.     {
  1162.         $toArr = array();
  1163.         foreach ($this->to as $toaddr) {
  1164.             $toArr[] = $this->addrFormat($toaddr);
  1165.         }
  1166.         $to = implode(', ', $toArr);
  1167.  
  1168.         if (empty($this->Sender)) {
  1169.             $params = ' ';
  1170.         } else {
  1171.             $params = sprintf('-f%s', $this->Sender);
  1172.         }
  1173.         if ($this->Sender != '' and !ini_get('safe_mode')) {
  1174.             $old_from = ini_get('sendmail_from');
  1175.             ini_set('sendmail_from', $this->Sender);
  1176.         }
  1177.         $result = false;
  1178.         if ($this->SingleTo && count($toArr) > 1) {
  1179.             foreach ($toArr as $toAddr) {
  1180.                 $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
  1181.                 $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  1182.             }
  1183.         } else {
  1184.             $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
  1185.             $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  1186.         }
  1187.         if (isset($old_from)) {
  1188.             ini_set('sendmail_from', $old_from);
  1189.         }
  1190.         if (!$result) {
  1191.             throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL);
  1192.         }
  1193.         return true;
  1194.     }
  1195.  
  1196.     /**
  1197.      * Get an instance to use for SMTP operations.
  1198.      * Override this function to load your own SMTP implementation
  1199.      * @return SMTP
  1200.      */
  1201.     public function getSMTPInstance()
  1202.     {
  1203.         if (!is_object($this->smtp)) {
  1204.             $this->smtp = new SMTP;
  1205.         }
  1206.         return $this->smtp;
  1207.     }
  1208.  
  1209.     /**
  1210.      * Send mail via SMTP.
  1211.      * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
  1212.      * Uses the PHPMailerSMTP class by default.
  1213.      * @see PHPMailer::getSMTPInstance() to use a different class.
  1214.      * @param string $header The message headers
  1215.      * @param string $body The message body
  1216.      * @throws phpmailerException
  1217.      * @uses SMTP
  1218.      * @access protected
  1219.      * @return boolean
  1220.      */
  1221.     protected function smtpSend($header, $body)
  1222.     {
  1223.         $bad_rcpt = array();
  1224.  
  1225.         if (!$this->smtpConnect()) {
  1226.             throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
  1227.         }
  1228.         if ('' == $this->Sender) {
  1229.             $smtp_from = $this->From;
  1230.         } else {
  1231.             $smtp_from = $this->Sender;
  1232.         }
  1233.         if (!$this->smtp->mail($smtp_from)) {
  1234.             $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
  1235.             throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
  1236.         }
  1237.  
  1238.         // Attempt to send to all recipients
  1239.         foreach ($this->to as $to) {
  1240.             if (!$this->smtp->recipient($to[0])) {
  1241.                 $bad_rcpt[] = $to[0];
  1242.                 $isSent = false;
  1243.             } else {
  1244.                 $isSent = true;
  1245.             }
  1246.             $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From);
  1247.         }
  1248.         foreach ($this->cc as $cc) {
  1249.             if (!$this->smtp->recipient($cc[0])) {
  1250.                 $bad_rcpt[] = $cc[0];
  1251.                 $isSent = false;
  1252.             } else {
  1253.                 $isSent = true;
  1254.             }
  1255.             $this->doCallback($isSent, array(), array($cc[0]), array(), $this->Subject, $body, $this->From);
  1256.         }
  1257.         foreach ($this->bcc as $bcc) {
  1258.             if (!$this->smtp->recipient($bcc[0])) {
  1259.                 $bad_rcpt[] = $bcc[0];
  1260.                 $isSent = false;
  1261.             } else {
  1262.                 $isSent = true;
  1263.             }
  1264.             $this->doCallback($isSent, array(), array(), array($bcc[0]), $this->Subject, $body, $this->From);
  1265.         }
  1266.  
  1267.         // Only send the DATA command if we have viable recipients
  1268.         if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
  1269.             throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
  1270.         }
  1271.         if ($this->SMTPKeepAlive) {
  1272.             $this->smtp->reset();
  1273.         } else {
  1274.             $this->smtp->quit();
  1275.             $this->smtp->close();
  1276.         }
  1277.         //Create error message for any bad addresses
  1278.         if (count($bad_rcpt) > 0) {
  1279.             throw new phpmailerException(
  1280.                 $this->lang('recipients_failed') . implode(', ', $bad_rcpt),
  1281.                 self::STOP_CONTINUE
  1282.             );
  1283.         }
  1284.         return true;
  1285.     }
  1286.  
  1287.     /**
  1288.      * Initiate a connection to an SMTP server.
  1289.      * Returns false if the operation failed.
  1290.      * @param array $options An array of options compatible with stream_context_create()
  1291.      * @uses SMTP
  1292.      * @access public
  1293.      * @throws phpmailerException
  1294.      * @return boolean
  1295.      */
  1296.     public function smtpConnect($options = array())
  1297.     {
  1298.         if (is_null($this->smtp)) {
  1299.             $this->smtp = $this->getSMTPInstance();
  1300.         }
  1301.  
  1302.         // Already connected?
  1303.         if ($this->smtp->connected()) {
  1304.             return true;
  1305.         }
  1306.  
  1307.         $this->smtp->setTimeout($this->Timeout);
  1308.         $this->smtp->setDebugLevel($this->SMTPDebug);
  1309.         $this->smtp->setDebugOutput($this->Debugoutput);
  1310.         $this->smtp->setVerp($this->do_verp);
  1311.         $hosts = explode(';', $this->Host);
  1312.         $lastexception = null;
  1313.  
  1314.         foreach ($hosts as $hostentry) {
  1315.             $hostinfo = array();
  1316.             if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) {
  1317.                 // Not a valid host entry
  1318.                 continue;
  1319.             }
  1320.             // $hostinfo[2]: optional ssl or tls prefix
  1321.             // $hostinfo[3]: the hostname
  1322.             // $hostinfo[4]: optional port number
  1323.             // The host string prefix can temporarily override the current setting for SMTPSecure
  1324.             // If it's not specified, the default value is used
  1325.             $prefix = '';
  1326.             $tls = ($this->SMTPSecure == 'tls');
  1327.             if ($hostinfo[2] == 'ssl' or ($hostinfo[2] == '' and $this->SMTPSecure == 'ssl')) {
  1328.                 $prefix = 'ssl://';
  1329.                 $tls = false; // Can't have SSL and TLS at once
  1330.             } elseif ($hostinfo[2] == 'tls') {
  1331.                 $tls = true;
  1332.                 // tls doesn't use a prefix
  1333.             }
  1334.             $host = $hostinfo[3];
  1335.             $port = $this->Port;
  1336.             $tport = (integer)$hostinfo[4];
  1337.             if ($tport > 0 and $tport < 65536) {
  1338.                 $port = $tport;
  1339.             }
  1340.             if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
  1341.                 try {
  1342.                     if ($this->Helo) {
  1343.                         $hello = $this->Helo;
  1344.                     } else {
  1345.                         $hello = $this->serverHostname();
  1346.                     }
  1347.                     $this->smtp->hello($hello);
  1348.  
  1349.                     if ($tls) {
  1350.                         if (!$this->smtp->startTLS()) {
  1351.                             throw new phpmailerException($this->lang('connect_host'));
  1352.                         }
  1353.                         // We must resend HELO after tls negotiation
  1354.                         $this->smtp->hello($hello);
  1355.                     }
  1356.                     if ($this->SMTPAuth) {
  1357.                         if (!$this->smtp->authenticate(
  1358.                             $this->Username,
  1359.                             $this->Password,
  1360.                             $this->AuthType,
  1361.                             $this->Realm,
  1362.                             $this->Workstation
  1363.                         )
  1364.                         ) {
  1365.                             throw new phpmailerException($this->lang('authenticate'));
  1366.                         }
  1367.                     }
  1368.                     return true;
  1369.                 } catch (phpmailerException $exc) {
  1370.                     $lastexception = $exc;
  1371.                     // We must have connected, but then failed TLS or Auth, so close connection nicely
  1372.                     $this->smtp->quit();
  1373.                 }
  1374.             }
  1375.         }
  1376.         // If we get here, all connection attempts have failed, so close connection hard
  1377.         $this->smtp->close();
  1378.         // As we've caught all exceptions, just report whatever the last one was
  1379.         if ($this->exceptions and !is_null($lastexception)) {
  1380.             throw $lastexception;
  1381.         }
  1382.         return false;
  1383.     }
  1384.  
  1385.     /**
  1386.      * Close the active SMTP session if one exists.
  1387.      * @return void
  1388.      */
  1389.     public function smtpClose()
  1390.     {
  1391.         if ($this->smtp !== null) {
  1392.             if ($this->smtp->connected()) {
  1393.                 $this->smtp->quit();
  1394.                 $this->smtp->close();
  1395.             }
  1396.         }
  1397.     }
  1398.  
  1399.     /**
  1400.      * Set the language for error messages.
  1401.      * Returns false if it cannot load the language file.
  1402.      * The default language is English.
  1403.      * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
  1404.      * @param string $lang_path Path to the language file directory, with trailing separator (slash)
  1405.      * @return boolean
  1406.      * @access public
  1407.      */
  1408.     public function setLanguage($langcode = 'en', $lang_path = '')
  1409.     {
  1410.         // Define full set of translatable strings in English
  1411.         $PHPMAILER_LANG = array(
  1412.             'authenticate' => 'SMTP Error: Could not authenticate.',
  1413.             'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  1414.             'data_not_accepted' => 'SMTP Error: data not accepted.',
  1415.             'empty_message' => 'Message body empty',
  1416.             'encoding' => 'Unknown encoding: ',
  1417.             'execute' => 'Could not execute: ',
  1418.             'file_access' => 'Could not access file: ',
  1419.             'file_open' => 'File Error: Could not open file: ',
  1420.             'from_failed' => 'The following From address failed: ',
  1421.             'instantiate' => 'Could not instantiate mail function.',
  1422.             'invalid_address' => 'Invalid address',
  1423.             'mailer_not_supported' => ' mailer is not supported.',
  1424.             'provide_address' => 'You must provide at least one recipient email address.',
  1425.             'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  1426.             'signing' => 'Signing Error: ',
  1427.             'smtp_connect_failed' => 'SMTP connect() failed.',
  1428.             'smtp_error' => 'SMTP server error: ',
  1429.             'variable_set' => 'Cannot set or reset variable: '
  1430.         );
  1431.         if (empty($lang_path)) {
  1432.             // Calculate an absolute path so it can work if CWD is not here
  1433.             $lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR;
  1434.         }
  1435.         $foundlang = true;
  1436.         $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
  1437.         if ($langcode != 'en') { // There is no English translation file
  1438.             // Make sure language file path is readable
  1439.             if (!is_readable($lang_file)) {
  1440.                 $foundlang = false;
  1441.             } else {
  1442.                 // Overwrite language-specific strings.
  1443.                 // This way we'll never have missing translations.
  1444.                 $foundlang = include $lang_file;
  1445.             }
  1446.         }
  1447.         $this->language = $PHPMAILER_LANG;
  1448.         return (boolean)$foundlang; // Returns false if language not found
  1449.     }
  1450.  
  1451.     /**
  1452.      * Get the array of strings for the current language.
  1453.      * @return array
  1454.      */
  1455.     public function getTranslations()
  1456.     {
  1457.         return $this->language;
  1458.     }
  1459.  
  1460.     /**
  1461.      * Create recipient headers.
  1462.      * @access public
  1463.      * @param string $type
  1464.      * @param array $addr An array of recipient,
  1465.      * where each recipient is a 2-element indexed array with element 0 containing an address
  1466.      * and element 1 containing a name, like:
  1467.      * array(array('joe@example.com', 'Joe User'), array('zoe@example.com', 'Zoe User'))
  1468.      * @return string
  1469.      */
  1470.     public function addrAppend($type, $addr)
  1471.     {
  1472.         $addresses = array();
  1473.         foreach ($addr as $address) {
  1474.             $addresses[] = $this->addrFormat($address);
  1475.         }
  1476.         return $type . ': ' . implode(', ', $addresses) . $this->LE;
  1477.     }
  1478.  
  1479.     /**
  1480.      * Format an address for use in a message header.
  1481.      * @access public
  1482.      * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name
  1483.      *      like array('joe@example.com', 'Joe User')
  1484.      * @return string
  1485.      */
  1486.     public function addrFormat($addr)
  1487.     {
  1488.         if (empty($addr[1])) { // No name provided
  1489.             return $this->secureHeader($addr[0]);
  1490.         } else {
  1491.             return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
  1492.                 $addr[0]
  1493.             ) . '>';
  1494.         }
  1495.     }
  1496.  
  1497.     /**
  1498.      * Word-wrap message.
  1499.      * For use with mailers that do not automatically perform wrapping
  1500.      * and for quoted-printable encoded messages.
  1501.      * Original written by philippe.
  1502.      * @param string $message The message to wrap
  1503.      * @param integer $length The line length to wrap to
  1504.      * @param boolean $qp_mode Whether to run in Quoted-Printable mode
  1505.      * @access public
  1506.      * @return string
  1507.      */
  1508.     public function wrapText($message, $length, $qp_mode = false)
  1509.     {
  1510.         if ($qp_mode) {
  1511.             $soft_break = sprintf(' =%s', $this->LE);
  1512.         } else {
  1513.             $soft_break = $this->LE;
  1514.         }
  1515.         // If utf-8 encoding is used, we will need to make sure we don't
  1516.         // split multibyte characters when we wrap
  1517.         $is_utf8 = (strtolower($this->CharSet) == 'utf-8');
  1518.         $lelen = strlen($this->LE);
  1519.         $crlflen = strlen(self::CRLF);
  1520.  
  1521.         $message = $this->fixEOL($message);
  1522.         //Remove a trailing line break
  1523.         if (substr($message, -$lelen) == $this->LE) {
  1524.             $message = substr($message, 0, -$lelen);
  1525.         }
  1526.  
  1527.         //Split message into lines
  1528.         $lines = explode($this->LE, $message);
  1529.         //Message will be rebuilt in here
  1530.         $message = '';
  1531.         foreach ($lines as $line) {
  1532.             $words = explode(' ', $line);
  1533.             $buf = '';
  1534.             $firstword = true;
  1535.             foreach ($words as $word) {
  1536.                 if ($qp_mode and (strlen($word) > $length)) {
  1537.                     $space_left = $length - strlen($buf) - $crlflen;
  1538.                     if (!$firstword) {
  1539.                         if ($space_left > 20) {
  1540.                             $len = $space_left;
  1541.                             if ($is_utf8) {
  1542.                                 $len = $this->utf8CharBoundary($word, $len);
  1543.                             } elseif (substr($word, $len - 1, 1) == '=') {
  1544.                                 $len--;
  1545.                             } elseif (substr($word, $len - 2, 1) == '=') {
  1546.                                 $len -= 2;
  1547.                             }
  1548.                             $part = substr($word, 0, $len);
  1549.                             $word = substr($word, $len);
  1550.                             $buf .= ' ' . $part;
  1551.                             $message .= $buf . sprintf('=%s', self::CRLF);
  1552.                         } else {
  1553.                             $message .= $buf . $soft_break;
  1554.                         }
  1555.                         $buf = '';
  1556.                     }
  1557.                     while (strlen($word) > 0) {
  1558.                         if ($length <= 0) {
  1559.                             break;
  1560.                         }
  1561.                         $len = $length;
  1562.                         if ($is_utf8) {
  1563.                             $len = $this->utf8CharBoundary($word, $len);
  1564.                         } elseif (substr($word, $len - 1, 1) == '=') {
  1565.                             $len--;
  1566.                         } elseif (substr($word, $len - 2, 1) == '=') {
  1567.                             $len -= 2;
  1568.                         }
  1569.                         $part = substr($word, 0, $len);
  1570.                         $word = substr($word, $len);
  1571.  
  1572.                         if (strlen($word) > 0) {
  1573.                             $message .= $part . sprintf('=%s', self::CRLF);
  1574.                         } else {
  1575.                             $buf = $part;
  1576.                         }
  1577.                     }
  1578.                 } else {
  1579.                     $buf_o = $buf;
  1580.                     if (!$firstword) {
  1581.                         $buf .= ' ';
  1582.                     }
  1583.                     $buf .= $word;
  1584.  
  1585.                     if (strlen($buf) > $length and $buf_o != '') {
  1586.                         $message .= $buf_o . $soft_break;
  1587.                         $buf = $word;
  1588.                     }
  1589.                 }
  1590.                 $firstword = false;
  1591.             }
  1592.             $message .= $buf . self::CRLF;
  1593.         }
  1594.  
  1595.         return $message;
  1596.     }
  1597.  
  1598.     /**
  1599.      * Find the last character boundary prior to $maxLength in a utf-8
  1600.      * quoted-printable encoded string.
  1601.      * Original written by Colin Brown.
  1602.      * @access public
  1603.      * @param string $encodedText utf-8 QP text
  1604.      * @param integer $maxLength Find the last character boundary prior to this length
  1605.      * @return integer
  1606.      */
  1607.     public function utf8CharBoundary($encodedText, $maxLength)
  1608.     {
  1609.         $foundSplitPos = false;
  1610.         $lookBack = 3;
  1611.         while (!$foundSplitPos) {
  1612.             $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  1613.             $encodedCharPos = strpos($lastChunk, '=');
  1614.             if (false !== $encodedCharPos) {
  1615.                 // Found start of encoded character byte within $lookBack block.
  1616.                 // Check the encoded byte value (the 2 chars after the '=')
  1617.                 $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  1618.                 $dec = hexdec($hex);
  1619.                 if ($dec < 128) {
  1620.                     // Single byte character.
  1621.                     // If the encoded char was found at pos 0, it will fit
  1622.                     // otherwise reduce maxLength to start of the encoded char
  1623.                     if ($encodedCharPos > 0) {
  1624.                         $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  1625.                     }
  1626.                     $foundSplitPos = true;
  1627.                 } elseif ($dec >= 192) {
  1628.                     // First byte of a multi byte character
  1629.                     // Reduce maxLength to split at start of character
  1630.                     $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  1631.                     $foundSplitPos = true;
  1632.                 } elseif ($dec < 192) {
  1633.                     // Middle byte of a multi byte character, look further back
  1634.                     $lookBack += 3;
  1635.                 }
  1636.             } else {
  1637.                 // No encoded character found
  1638.                 $foundSplitPos = true;
  1639.             }
  1640.         }
  1641.         return $maxLength;
  1642.     }
  1643.  
  1644.     /**
  1645.      * Apply word wrapping to the message body.
  1646.      * Wraps the message body to the number of chars set in the WordWrap property.
  1647.      * You should only do this to plain-text bodies as wrapping HTML tags may break them.
  1648.      * This is called automatically by createBody(), so you don't need to call it yourself.
  1649.      * @access public
  1650.      * @return void
  1651.      */
  1652.     public function setWordWrap()
  1653.     {
  1654.         if ($this->WordWrap < 1) {
  1655.             return;
  1656.         }
  1657.  
  1658.         switch ($this->message_type) {
  1659.             case 'alt':
  1660.             case 'alt_inline':
  1661.             case 'alt_attach':
  1662.             case 'alt_inline_attach':
  1663.                 $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
  1664.                 break;
  1665.             default:
  1666.                 $this->Body = $this->wrapText($this->Body, $this->WordWrap);
  1667.                 break;
  1668.         }
  1669.     }
  1670.  
  1671.     /**
  1672.      * Assemble message headers.
  1673.      * @access public
  1674.      * @return string The assembled headers
  1675.      */
  1676.     public function createHeader()
  1677.     {
  1678.         $result = '';
  1679.  
  1680.         // Set the boundaries
  1681.         $uniq_id = md5(uniqid(time()));
  1682.         $this->boundary[1] = 'b1_' . $uniq_id;
  1683.         $this->boundary[2] = 'b2_' . $uniq_id;
  1684.         $this->boundary[3] = 'b3_' . $uniq_id;
  1685.  
  1686.         if ($this->MessageDate == '') {
  1687.             $this->MessageDate = self::rfcDate();
  1688.         }
  1689.         $result .= $this->headerLine('Date', $this->MessageDate);
  1690.  
  1691.  
  1692.         // To be created automatically by mail()
  1693.         if ($this->SingleTo) {
  1694.             if ($this->Mailer != 'mail') {
  1695.                 foreach ($this->to as $toaddr) {
  1696.                     $this->SingleToArray[] = $this->addrFormat($toaddr);
  1697.                 }
  1698.             }
  1699.         } else {
  1700.             if (count($this->to) > 0) {
  1701.                 if ($this->Mailer != 'mail') {
  1702.                     $result .= $this->addrAppend('To', $this->to);
  1703.                 }
  1704.             } elseif (count($this->cc) == 0) {
  1705.                 $result .= $this->headerLine('To', 'undisclosed-recipients:;');
  1706.             }
  1707.         }
  1708.  
  1709.         $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName)));
  1710.  
  1711.         // sendmail and mail() extract Cc from the header before sending
  1712.         if (count($this->cc) > 0) {
  1713.             $result .= $this->addrAppend('Cc', $this->cc);
  1714.         }
  1715.  
  1716.         // sendmail and mail() extract Bcc from the header before sending
  1717.         if ((
  1718.                 $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail'
  1719.             )
  1720.             and count($this->bcc) > 0
  1721.         ) {
  1722.             $result .= $this->addrAppend('Bcc', $this->bcc);
  1723.         }
  1724.  
  1725.         if (count($this->ReplyTo) > 0) {
  1726.             $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
  1727.         }
  1728.  
  1729.         // mail() sets the subject itself
  1730.         if ($this->Mailer != 'mail') {
  1731.             $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
  1732.         }
  1733.  
  1734.         if ($this->MessageID != '') {
  1735.             $this->lastMessageID = $this->MessageID;
  1736.         } else {
  1737.             $this->lastMessageID = sprintf('<%s@%s>', $uniq_id, $this->ServerHostname());
  1738.         }
  1739.         $result .= $this->HeaderLine('Message-ID', $this->lastMessageID);
  1740.         $result .= $this->headerLine('X-Priority', $this->Priority);
  1741.         if ($this->XMailer == '') {
  1742.             $result .= $this->headerLine(
  1743.                 'X-Mailer',
  1744.                 'PHPMailer ' . $this->Version . ' (https://github.com/PHPMailer/PHPMailer/)'
  1745.             );
  1746.         } else {
  1747.             $myXmailer = trim($this->XMailer);
  1748.             if ($myXmailer) {
  1749.                 $result .= $this->headerLine('X-Mailer', $myXmailer);
  1750.             }
  1751.         }
  1752.  
  1753.         if ($this->ConfirmReadingTo != '') {
  1754.             $result .= $this->headerLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
  1755.         }
  1756.  
  1757.         // Add custom headers
  1758.         foreach ($this->CustomHeader as $header) {
  1759.             $result .= $this->headerLine(
  1760.                 trim($header[0]),
  1761.                 $this->encodeHeader(trim($header[1]))
  1762.             );
  1763.         }
  1764.         if (!$this->sign_key_file) {
  1765.             $result .= $this->headerLine('MIME-Version', '1.0');
  1766.             $result .= $this->getMailMIME();
  1767.         }
  1768.  
  1769.         return $result;
  1770.     }
  1771.  
  1772.     /**
  1773.      * Get the message MIME type headers.
  1774.      * @access public
  1775.      * @return string
  1776.      */
  1777.     public function getMailMIME()
  1778.     {
  1779.         $result = '';
  1780.         $ismultipart = true;
  1781.         switch ($this->message_type) {
  1782.             case 'inline':
  1783.                 $result .= $this->headerLine('Content-Type', 'multipart/related;');
  1784.                 $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  1785.                 break;
  1786.             case 'attach':
  1787.             case 'inline_attach':
  1788.             case 'alt_attach':
  1789.             case 'alt_inline_attach':
  1790.                 $result .= $this->headerLine('Content-Type', 'multipart/mixed;');
  1791.                 $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  1792.                 break;
  1793.             case 'alt':
  1794.             case 'alt_inline':
  1795.                 $result .= $this->headerLine('Content-Type', 'multipart/alternative;');
  1796.                 $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  1797.                 break;
  1798.             default:
  1799.                 // Catches case 'plain': and case '':
  1800.                 $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
  1801.                 $ismultipart = false;
  1802.                 break;
  1803.         }
  1804.         // RFC1341 part 5 says 7bit is assumed if not specified
  1805.         if ($this->Encoding != '7bit') {
  1806.             // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
  1807.             if ($ismultipart) {
  1808.                 if ($this->Encoding == '8bit') {
  1809.                     $result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
  1810.                 }
  1811.                 // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
  1812.             } else {
  1813.                 $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
  1814.             }
  1815.         }
  1816.  
  1817.         if ($this->Mailer != 'mail') {
  1818.             $result .= $this->LE;
  1819.         }
  1820.  
  1821.         return $result;
  1822.     }
  1823.  
  1824.     /**
  1825.      * Returns the whole MIME message.
  1826.      * Includes complete headers and body.
  1827.      * Only valid post preSend().
  1828.      * @see PHPMailer::preSend()
  1829.      * @access public
  1830.      * @return string
  1831.      */
  1832.     public function getSentMIMEMessage()
  1833.     {
  1834.         return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
  1835.     }
  1836.  
  1837.     /**
  1838.      * Assemble the message body.
  1839.      * Returns an empty string on failure.
  1840.      * @access public
  1841.      * @throws phpmailerException
  1842.      * @return string The assembled message body
  1843.      */
  1844.     public function createBody()
  1845.     {
  1846.         $body = '';
  1847.  
  1848.         if ($this->sign_key_file) {
  1849.             $body .= $this->getMailMIME() . $this->LE;
  1850.         }
  1851.  
  1852.         $this->setWordWrap();
  1853.  
  1854.         $bodyEncoding = $this->Encoding;
  1855.         $bodyCharSet = $this->CharSet;
  1856.         if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) {
  1857.             $bodyEncoding = '7bit';
  1858.             $bodyCharSet = 'us-ascii';
  1859.         }
  1860.         $altBodyEncoding = $this->Encoding;
  1861.         $altBodyCharSet = $this->CharSet;
  1862.         if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) {
  1863.             $altBodyEncoding = '7bit';
  1864.             $altBodyCharSet = 'us-ascii';
  1865.         }
  1866.         switch ($this->message_type) {
  1867.             case 'inline':
  1868.                 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  1869.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1870.                 $body .= $this->LE . $this->LE;
  1871.                 $body .= $this->attachAll('inline', $this->boundary[1]);
  1872.                 break;
  1873.             case 'attach':
  1874.                 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  1875.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1876.                 $body .= $this->LE . $this->LE;
  1877.                 $body .= $this->attachAll('attachment', $this->boundary[1]);
  1878.                 break;
  1879.             case 'inline_attach':
  1880.                 $body .= $this->textLine('--' . $this->boundary[1]);
  1881.                 $body .= $this->headerLine('Content-Type', 'multipart/related;');
  1882.                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1883.                 $body .= $this->LE;
  1884.                 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
  1885.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1886.                 $body .= $this->LE . $this->LE;
  1887.                 $body .= $this->attachAll('inline', $this->boundary[2]);
  1888.                 $body .= $this->LE;
  1889.                 $body .= $this->attachAll('attachment', $this->boundary[1]);
  1890.                 break;
  1891.             case 'alt':
  1892.                 $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1893.                 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1894.                 $body .= $this->LE . $this->LE;
  1895.                 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
  1896.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1897.                 $body .= $this->LE . $this->LE;
  1898.                 if (!empty($this->Ical)) {
  1899.                     $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
  1900.                     $body .= $this->encodeString($this->Ical, $this->Encoding);
  1901.                     $body .= $this->LE . $this->LE;
  1902.                 }
  1903.                 $body .= $this->endBoundary($this->boundary[1]);
  1904.                 break;
  1905.             case 'alt_inline':
  1906.                 $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1907.                 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1908.                 $body .= $this->LE . $this->LE;
  1909.                 $body .= $this->textLine('--' . $this->boundary[1]);
  1910.                 $body .= $this->headerLine('Content-Type', 'multipart/related;');
  1911.                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1912.                 $body .= $this->LE;
  1913.                 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  1914.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1915.                 $body .= $this->LE . $this->LE;
  1916.                 $body .= $this->attachAll('inline', $this->boundary[2]);
  1917.                 $body .= $this->LE;
  1918.                 $body .= $this->endBoundary($this->boundary[1]);
  1919.                 break;
  1920.             case 'alt_attach':
  1921.                 $body .= $this->textLine('--' . $this->boundary[1]);
  1922.                 $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  1923.                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1924.                 $body .= $this->LE;
  1925.                 $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1926.                 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1927.                 $body .= $this->LE . $this->LE;
  1928.                 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  1929.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1930.                 $body .= $this->LE . $this->LE;
  1931.                 $body .= $this->endBoundary($this->boundary[2]);
  1932.                 $body .= $this->LE;
  1933.                 $body .= $this->attachAll('attachment', $this->boundary[1]);
  1934.                 break;
  1935.             case 'alt_inline_attach':
  1936.                 $body .= $this->textLine('--' . $this->boundary[1]);
  1937.                 $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  1938.                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1939.                 $body .= $this->LE;
  1940.                 $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1941.                 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1942.                 $body .= $this->LE . $this->LE;
  1943.                 $body .= $this->textLine('--' . $this->boundary[2]);
  1944.                 $body .= $this->headerLine('Content-Type', 'multipart/related;');
  1945.                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
  1946.                 $body .= $this->LE;
  1947.                 $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
  1948.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1949.                 $body .= $this->LE . $this->LE;
  1950.                 $body .= $this->attachAll('inline', $this->boundary[3]);
  1951.                 $body .= $this->LE;
  1952.                 $body .= $this->endBoundary($this->boundary[2]);
  1953.                 $body .= $this->LE;
  1954.                 $body .= $this->attachAll('attachment', $this->boundary[1]);
  1955.                 break;
  1956.             default:
  1957.                 // catch case 'plain' and case ''
  1958.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1959.                 break;
  1960.         }
  1961.  
  1962.         if ($this->isError()) {
  1963.             $body = '';
  1964.         } elseif ($this->sign_key_file) {
  1965.             try {
  1966.                 if (!defined('PKCS7_TEXT')) {
  1967.                     throw new phpmailerException($this->lang('signing') . ' OpenSSL extension missing.');
  1968.                 }
  1969.                 // @TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1
  1970.                 $file = tempnam(sys_get_temp_dir(), 'mail');
  1971.                 if (false === file_put_contents($file, $body)) {
  1972.                     throw new phpmailerException($this->lang('signing') . ' Could not write temp file');
  1973.                 }
  1974.                 $signed = tempnam(sys_get_temp_dir(), 'signed');
  1975.                 //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
  1976.                 if (empty($this->sign_extracerts_file)) {
  1977.                     $sign = @openssl_pkcs7_sign(
  1978.                         $file,
  1979.                         $signed,
  1980.                         'file://' . realpath($this->sign_cert_file),
  1981.                         array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
  1982.                         null
  1983.                     );
  1984.                 } else {
  1985.                     $sign = @openssl_pkcs7_sign(
  1986.                         $file,
  1987.                         $signed,
  1988.                         'file://' . realpath($this->sign_cert_file),
  1989.                         array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
  1990.                         null,
  1991.                         PKCS7_DETACHED,
  1992.                         $this->sign_extracerts_file
  1993.                     );
  1994.                 }
  1995.                 if ($sign) {
  1996.                     @unlink($file);
  1997.                     $body = file_get_contents($signed);
  1998.                     @unlink($signed);
  1999.                 } else {
  2000.                     @unlink($file);
  2001.                     @unlink($signed);
  2002.                     throw new phpmailerException($this->lang('signing') . openssl_error_string());
  2003.                 }
  2004.             } catch (phpmailerException $exc) {
  2005.                 $body = '';
  2006.                 if ($this->exceptions) {
  2007.                     throw $exc;
  2008.                 }
  2009.             }
  2010.         }
  2011.         return $body;
  2012.     }
  2013.  
  2014.     /**
  2015.      * Return the start of a message boundary.
  2016.      * @access protected
  2017.      * @param string $boundary
  2018.      * @param string $charSet
  2019.      * @param string $contentType
  2020.      * @param string $encoding
  2021.      * @return string
  2022.      */
  2023.     protected function getBoundary($boundary, $charSet, $contentType, $encoding)
  2024.     {
  2025.         $result = '';
  2026.         if ($charSet == '') {
  2027.             $charSet = $this->CharSet;
  2028.         }
  2029.         if ($contentType == '') {
  2030.             $contentType = $this->ContentType;
  2031.         }
  2032.         if ($encoding == '') {
  2033.             $encoding = $this->Encoding;
  2034.         }
  2035.         $result .= $this->textLine('--' . $boundary);
  2036.         $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
  2037.         $result .= $this->LE;
  2038.         // RFC1341 part 5 says 7bit is assumed if not specified
  2039.         if ($encoding != '7bit') {
  2040.             $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
  2041.         }
  2042.         $result .= $this->LE;
  2043.  
  2044.         return $result;
  2045.     }
  2046.  
  2047.     /**
  2048.      * Return the end of a message boundary.
  2049.      * @access protected
  2050.      * @param string $boundary
  2051.      * @return string
  2052.      */
  2053.     protected function endBoundary($boundary)
  2054.     {
  2055.         return $this->LE . '--' . $boundary . '--' . $this->LE;
  2056.     }
  2057.  
  2058.     /**
  2059.      * Set the message type.
  2060.      * PHPMailer only supports some preset message types,
  2061.      * not arbitrary MIME structures.
  2062.      * @access protected
  2063.      * @return void
  2064.      */
  2065.     protected function setMessageType()
  2066.     {
  2067.         $type = array();
  2068.         if ($this->alternativeExists()) {
  2069.             $type[] = 'alt';
  2070.         }
  2071.         if ($this->inlineImageExists()) {
  2072.             $type[] = 'inline';
  2073.         }
  2074.         if ($this->attachmentExists()) {
  2075.             $type[] = 'attach';
  2076.         }
  2077.         $this->message_type = implode('_', $type);
  2078.         if ($this->message_type == '') {
  2079.             $this->message_type = 'plain';
  2080.         }
  2081.     }
  2082.  
  2083.     /**
  2084.      * Format a header line.
  2085.      * @access public
  2086.      * @param string $name
  2087.      * @param string $value
  2088.      * @return string
  2089.      */
  2090.     public function headerLine($name, $value)
  2091.     {
  2092.         return $name . ': ' . $value . $this->LE;
  2093.     }
  2094.  
  2095.     /**
  2096.      * Return a formatted mail line.
  2097.      * @access public
  2098.      * @param string $value
  2099.      * @return string
  2100.      */
  2101.     public function textLine($value)
  2102.     {
  2103.         return $value . $this->LE;
  2104.     }
  2105.  
  2106.     /**
  2107.      * Add an attachment from a path on the filesystem.
  2108.      * Returns false if the file could not be found or read.
  2109.      * @param string $path Path to the attachment.
  2110.      * @param string $name Overrides the attachment name.
  2111.      * @param string $encoding File encoding (see $Encoding).
  2112.      * @param string $type File extension (MIME) type.
  2113.      * @param string $disposition Disposition to use
  2114.      * @throws phpmailerException
  2115.      * @return boolean
  2116.      */
  2117.     public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment')
  2118.     {
  2119.         try {
  2120.             if (!@is_file($path)) {
  2121.                 throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE);
  2122.             }
  2123.  
  2124.             // If a MIME type is not specified, try to work it out from the file name
  2125.             if ($type == '') {
  2126.                 $type = self::filenameToType($path);
  2127.             }
  2128.  
  2129.             $filename = basename($path);
  2130.             if ($name == '') {
  2131.                 $name = $filename;
  2132.             }
  2133.  
  2134.             $this->attachment[] = array(
  2135.                 0 => $path,
  2136.                 1 => $filename,
  2137.                 2 => $name,
  2138.                 3 => $encoding,
  2139.                 4 => $type,
  2140.                 5 => false, // isStringAttachment
  2141.                 6 => $disposition,
  2142.                 7 => 0
  2143.             );
  2144.  
  2145.         } catch (phpmailerException $exc) {
  2146.             $this->setError($exc->getMessage());
  2147.             $this->edebug($exc->getMessage());
  2148.             if ($this->exceptions) {
  2149.                 throw $exc;
  2150.             }
  2151.             return false;
  2152.         }
  2153.         return true;
  2154.     }
  2155.  
  2156.     /**
  2157.      * Return the array of attachments.
  2158.      * @return array
  2159.      */
  2160.     public function getAttachments()
  2161.     {
  2162.         return $this->attachment;
  2163.     }
  2164.  
  2165.     /**
  2166.      * Attach all file, string, and binary attachments to the message.
  2167.      * Returns an empty string on failure.
  2168.      * @access protected
  2169.      * @param string $disposition_type
  2170.      * @param string $boundary
  2171.      * @return string
  2172.      */
  2173.     protected function attachAll($disposition_type, $boundary)
  2174.     {
  2175.         // Return text of body
  2176.         $mime = array();
  2177.         $cidUniq = array();
  2178.         $incl = array();
  2179.  
  2180.         // Add all attachments
  2181.         foreach ($this->attachment as $attachment) {
  2182.             // Check if it is a valid disposition_filter
  2183.             if ($attachment[6] == $disposition_type) {
  2184.                 // Check for string attachment
  2185.                 $string = '';
  2186.                 $path = '';
  2187.                 $bString = $attachment[5];
  2188.                 if ($bString) {
  2189.                     $string = $attachment[0];
  2190.                 } else {
  2191.                     $path = $attachment[0];
  2192.                 }
  2193.  
  2194.                 $inclhash = md5(serialize($attachment));
  2195.                 if (in_array($inclhash, $incl)) {
  2196.                     continue;
  2197.                 }
  2198.                 $incl[] = $inclhash;
  2199.                 $name = $attachment[2];
  2200.                 $encoding = $attachment[3];
  2201.                 $type = $attachment[4];
  2202.                 $disposition = $attachment[6];
  2203.                 $cid = $attachment[7];
  2204.                 if ($disposition == 'inline' && isset($cidUniq[$cid])) {
  2205.                     continue;
  2206.                 }
  2207.                 $cidUniq[$cid] = true;
  2208.  
  2209.                 $mime[] = sprintf('--%s%s', $boundary, $this->LE);
  2210.                 $mime[] = sprintf(
  2211.                     'Content-Type: %s; name="%s"%s',
  2212.                     $type,
  2213.                     $this->encodeHeader($this->secureHeader($name)),
  2214.                     $this->LE
  2215.                 );
  2216.                 // RFC1341 part 5 says 7bit is assumed if not specified
  2217.                 if ($encoding != '7bit') {
  2218.                     $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE);
  2219.                 }
  2220.  
  2221.                 if ($disposition == 'inline') {
  2222.                     $mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE);
  2223.                 }
  2224.  
  2225.                 // If a filename contains any of these chars, it should be quoted,
  2226.                 // but not otherwise: RFC2183 & RFC2045 5.1
  2227.                 // Fixes a warning in IETF's msglint MIME checker
  2228.                 // Allow for bypassing the Content-Disposition header totally
  2229.                 if (!(empty($disposition))) {
  2230.                     $encoded_name = $this->encodeHeader($this->secureHeader($name));
  2231.                     if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
  2232.                         $mime[] = sprintf(
  2233.                             'Content-Disposition: %s; filename="%s"%s',
  2234.                             $disposition,
  2235.                             $encoded_name,
  2236.                             $this->LE . $this->LE
  2237.                         );
  2238.                     } else {
  2239.                         $mime[] = sprintf(
  2240.                             'Content-Disposition: %s; filename=%s%s',
  2241.                             $disposition,
  2242.                             $encoded_name,
  2243.                             $this->LE . $this->LE
  2244.                         );
  2245.                     }
  2246.                 } else {
  2247.                     $mime[] = $this->LE;
  2248.                 }
  2249.  
  2250.                 // Encode as string attachment
  2251.                 if ($bString) {
  2252.                     $mime[] = $this->encodeString($string, $encoding);
  2253.                     if ($this->isError()) {
  2254.                         return '';
  2255.                     }
  2256.                     $mime[] = $this->LE . $this->LE;
  2257.                 } else {
  2258.                     $mime[] = $this->encodeFile($path, $encoding);
  2259.                     if ($this->isError()) {
  2260.                         return '';
  2261.                     }
  2262.                     $mime[] = $this->LE . $this->LE;
  2263.                 }
  2264.             }
  2265.         }
  2266.  
  2267.         $mime[] = sprintf('--%s--%s', $boundary, $this->LE);
  2268.  
  2269.         return implode('', $mime);
  2270.     }
  2271.  
  2272.     /**
  2273.      * Encode a file attachment in requested format.
  2274.      * Returns an empty string on failure.
  2275.      * @param string $path The full path to the file
  2276.      * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  2277.      * @throws phpmailerException
  2278.      * @see EncodeFile(encodeFile
  2279.      * @access protected
  2280.      * @return string
  2281.      */
  2282.     protected function encodeFile($path, $encoding = 'base64')
  2283.     {
  2284.         try {
  2285.             if (!is_readable($path)) {
  2286.                 throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE);
  2287.             }
  2288.             $magic_quotes = get_magic_quotes_runtime();
  2289.             if ($magic_quotes) {
  2290.                 if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  2291.                     set_magic_quotes_runtime(false);
  2292.                 } else {
  2293.                     //Doesn't exist in PHP 5.4, but we don't need to check because
  2294.                     //get_magic_quotes_runtime always returns false in 5.4+
  2295.                     //so it will never get here
  2296.                     ini_set('magic_quotes_runtime', false);
  2297.                 }
  2298.             }
  2299.             $file_buffer = file_get_contents($path);
  2300.             $file_buffer = $this->encodeString($file_buffer, $encoding);
  2301.             if ($magic_quotes) {
  2302.                 if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  2303.                     set_magic_quotes_runtime($magic_quotes);
  2304.                 } else {
  2305.                     ini_set('magic_quotes_runtime', $magic_quotes);
  2306.                 }
  2307.             }
  2308.             return $file_buffer;
  2309.         } catch (Exception $exc) {
  2310.             $this->setError($exc->getMessage());
  2311.             return '';
  2312.         }
  2313.     }
  2314.  
  2315.     /**
  2316.      * Encode a string in requested format.
  2317.      * Returns an empty string on failure.
  2318.      * @param string $str The text to encode
  2319.      * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  2320.      * @access public
  2321.      * @return string
  2322.      */
  2323.     public function encodeString($str, $encoding = 'base64')
  2324.     {
  2325.         $encoded = '';
  2326.         switch (strtolower($encoding)) {
  2327.             case 'base64':
  2328.                 $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  2329.                 break;
  2330.             case '7bit':
  2331.             case '8bit':
  2332.                 $encoded = $this->fixEOL($str);
  2333.                 // Make sure it ends with a line break
  2334.                 if (substr($encoded, -(strlen($this->LE))) != $this->LE) {
  2335.                     $encoded .= $this->LE;
  2336.                 }
  2337.                 break;
  2338.             case 'binary':
  2339.                 $encoded = $str;
  2340.                 break;
  2341.             case 'quoted-printable':
  2342.                 $encoded = $this->encodeQP($str);
  2343.                 break;
  2344.             default:
  2345.                 $this->setError($this->lang('encoding') . $encoding);
  2346.                 break;
  2347.         }
  2348.         return $encoded;
  2349.     }
  2350.  
  2351.     /**
  2352.      * Encode a header string optimally.
  2353.      * Picks shortest of Q, B, quoted-printable or none.
  2354.      * @access public
  2355.      * @param string $str
  2356.      * @param string $position
  2357.      * @return string
  2358.      */
  2359.     public function encodeHeader($str, $position = 'text')
  2360.     {
  2361.         $matchcount = 0;
  2362.         switch (strtolower($position)) {
  2363.             case 'phrase':
  2364.                 if (!preg_match('/[\200-\377]/', $str)) {
  2365.                     // Can't use addslashes as we don't know the value of magic_quotes_sybase
  2366.                     $encoded = addcslashes($str, "\0..\37\177\\\"");
  2367.                     if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  2368.                         return ($encoded);
  2369.                     } else {
  2370.                         return ("\"$encoded\"");
  2371.                     }
  2372.                 }
  2373.                 $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  2374.                 break;
  2375.             /** @noinspection PhpMissingBreakStatementInspection */
  2376.             case 'comment':
  2377.                 $matchcount = preg_match_all('/[()"]/', $str, $matches);
  2378.                 // Intentional fall-through
  2379.             case 'text':
  2380.             default:
  2381.                 $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  2382.                 break;
  2383.         }
  2384.  
  2385.         //There are no chars that need encoding
  2386.         if ($matchcount == 0) {
  2387.             return ($str);
  2388.         }
  2389.  
  2390.         $maxlen = 75 - 7 - strlen($this->CharSet);
  2391.         // Try to select the encoding which should produce the shortest output
  2392.         if ($matchcount > strlen($str) / 3) {
  2393.             // More than a third of the content will need encoding, so B encoding will be most efficient
  2394.             $encoding = 'B';
  2395.             if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) {
  2396.                 // Use a custom function which correctly encodes and wraps long
  2397.                 // multibyte strings without breaking lines within a character
  2398.                 $encoded = $this->base64EncodeWrapMB($str, "\n");
  2399.             } else {
  2400.                 $encoded = base64_encode($str);
  2401.                 $maxlen -= $maxlen % 4;
  2402.                 $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  2403.             }
  2404.         } else {
  2405.             $encoding = 'Q';
  2406.             $encoded = $this->encodeQ($str, $position);
  2407.             $encoded = $this->wrapText($encoded, $maxlen, true);
  2408.             $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded));
  2409.         }
  2410.  
  2411.         $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
  2412.         $encoded = trim(str_replace("\n", $this->LE, $encoded));
  2413.  
  2414.         return $encoded;
  2415.     }
  2416.  
  2417.     /**
  2418.      * Check if a string contains multi-byte characters.
  2419.      * @access public
  2420.      * @param string $str multi-byte text to wrap encode
  2421.      * @return boolean
  2422.      */
  2423.     public function hasMultiBytes($str)
  2424.     {
  2425.         if (function_exists('mb_strlen')) {
  2426.             return (strlen($str) > mb_strlen($str, $this->CharSet));
  2427.         } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  2428.             return false;
  2429.         }
  2430.     }
  2431.  
  2432.     /**
  2433.      * Does a string contain any 8-bit chars (in any charset)?
  2434.      * @param string $text
  2435.      * @return boolean
  2436.      */
  2437.     public function has8bitChars($text)
  2438.     {
  2439.         return (boolean)preg_match('/[\x80-\xFF]/', $text);
  2440.     }
  2441.  
  2442.     /**
  2443.      * Encode and wrap long multibyte strings for mail headers
  2444.      * without breaking lines within a character.
  2445.      * Adapted from a function by paravoid
  2446.      * @link http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
  2447.      * @access public
  2448.      * @param string $str multi-byte text to wrap encode
  2449.      * @param string $linebreak string to use as linefeed/end-of-line
  2450.      * @return string
  2451.      */
  2452.     public function base64EncodeWrapMB($str, $linebreak = null)
  2453.     {
  2454.         $start = '=?' . $this->CharSet . '?B?';
  2455.         $end = '?=';
  2456.         $encoded = '';
  2457.         if ($linebreak === null) {
  2458.             $linebreak = $this->LE;
  2459.         }
  2460.  
  2461.         $mb_length = mb_strlen($str, $this->CharSet);
  2462.         // Each line must have length <= 75, including $start and $end
  2463.         $length = 75 - strlen($start) - strlen($end);
  2464.         // Average multi-byte ratio
  2465.         $ratio = $mb_length / strlen($str);
  2466.         // Base64 has a 4:3 ratio
  2467.         $avgLength = floor($length * $ratio * .75);
  2468.  
  2469.         for ($i = 0; $i < $mb_length; $i += $offset) {
  2470.             $lookBack = 0;
  2471.             do {
  2472.                 $offset = $avgLength - $lookBack;
  2473.                 $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  2474.                 $chunk = base64_encode($chunk);
  2475.                 $lookBack++;
  2476.             } while (strlen($chunk) > $length);
  2477.             $encoded .= $chunk . $linebreak;
  2478.         }
  2479.  
  2480.         // Chomp the last linefeed
  2481.         $encoded = substr($encoded, 0, -strlen($linebreak));
  2482.         return $encoded;
  2483.     }
  2484.  
  2485.     /**
  2486.      * Encode a string in quoted-printable format.
  2487.      * According to RFC2045 section 6.7.
  2488.      * @access public
  2489.      * @param string $string The text to encode
  2490.      * @param integer $line_max Number of chars allowed on a line before wrapping
  2491.      * @return string
  2492.      * @link http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 Adapted from this comment
  2493.      */
  2494.     public function encodeQP($string, $line_max = 76)
  2495.     {
  2496.         if (function_exists('quoted_printable_encode')) { // Use native function if it's available (>= PHP5.3)
  2497.             return $this->fixEOL(quoted_printable_encode($string));
  2498.         }
  2499.         // Fall back to a pure PHP implementation
  2500.         $string = str_replace(
  2501.             array('%20', '%0D%0A.', '%0D%0A', '%'),
  2502.             array(' ', "\r\n=2E", "\r\n", '='),
  2503.             rawurlencode($string)
  2504.         );
  2505.         $string = preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string);
  2506.         return $this->fixEOL($string);
  2507.     }
  2508.  
  2509.     /**
  2510.      * Backward compatibility wrapper for an old QP encoding function that was removed.
  2511.      * @see PHPMailer::encodeQP()
  2512.      * @access public
  2513.      * @param string $string
  2514.      * @param integer $line_max
  2515.      * @param boolean $space_conv
  2516.      * @return string
  2517.      * @deprecated Use encodeQP instead.
  2518.      */
  2519.     public function encodeQPphp(
  2520.         $string,
  2521.         $line_max = 76,
  2522.         /** @noinspection PhpUnusedParameterInspection */ $space_conv = false
  2523.     ) {
  2524.         return $this->encodeQP($string, $line_max);
  2525.     }
  2526.  
  2527.     /**
  2528.      * Encode a string using Q encoding.
  2529.      * @link http://tools.ietf.org/html/rfc2047
  2530.      * @param string $str the text to encode
  2531.      * @param string $position Where the text is going to be used, see the RFC for what that means
  2532.      * @access public
  2533.      * @return string
  2534.      */
  2535.     public function encodeQ($str, $position = 'text')
  2536.     {
  2537.         // There should not be any EOL in the string
  2538.         $pattern = '';
  2539.         $encoded = str_replace(array("\r", "\n"), '', $str);
  2540.         switch (strtolower($position)) {
  2541.             case 'phrase':
  2542.                 // RFC 2047 section 5.3
  2543.                 $pattern = '^A-Za-z0-9!*+\/ -';
  2544.                 break;
  2545.             /** @noinspection PhpMissingBreakStatementInspection */
  2546.             case 'comment':
  2547.                 // RFC 2047 section 5.2
  2548.                 $pattern = '\(\)"';
  2549.                 // intentional fall-through
  2550.                 // for this reason we build the $pattern without including delimiters and []
  2551.             case 'text':
  2552.             default:
  2553.                 // RFC 2047 section 5.1
  2554.                 // Replace every high ascii, control, =, ? and _ characters
  2555.                 $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
  2556.                 break;
  2557.         }
  2558.         $matches = array();
  2559.         if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
  2560.             // If the string contains an '=', make sure it's the first thing we replace
  2561.             // so as to avoid double-encoding
  2562.             $eqkey = array_search('=', $matches[0]);
  2563.             if (false !== $eqkey) {
  2564.                 unset($matches[0][$eqkey]);
  2565.                 array_unshift($matches[0], '=');
  2566.             }
  2567.             foreach (array_unique($matches[0]) as $char) {
  2568.                 $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
  2569.             }
  2570.         }
  2571.         // Replace every spaces to _ (more readable than =20)
  2572.         return str_replace(' ', '_', $encoded);
  2573.     }
  2574.  
  2575.  
  2576.     /**
  2577.      * Add a string or binary attachment (non-filesystem).
  2578.      * This method can be used to attach ascii or binary data,
  2579.      * such as a BLOB record from a database.
  2580.      * @param string $string String attachment data.
  2581.      * @param string $filename Name of the attachment.
  2582.      * @param string $encoding File encoding (see $Encoding).
  2583.      * @param string $type File extension (MIME) type.
  2584.      * @param string $disposition Disposition to use
  2585.      * @return void
  2586.      */
  2587.     public function addStringAttachment(
  2588.         $string,
  2589.         $filename,
  2590.         $encoding = 'base64',
  2591.         $type = '',
  2592.         $disposition = 'attachment'
  2593.     ) {
  2594.         // If a MIME type is not specified, try to work it out from the file name
  2595.         if ($type == '') {
  2596.             $type = self::filenameToType($filename);
  2597.         }
  2598.         // Append to $attachment array
  2599.         $this->attachment[] = array(
  2600.             0 => $string,
  2601.             1 => $filename,
  2602.             2 => basename($filename),
  2603.             3 => $encoding,
  2604.             4 => $type,
  2605.             5 => true, // isStringAttachment
  2606.             6 => $disposition,
  2607.             7 => 0
  2608.         );
  2609.     }
  2610.  
  2611.     /**
  2612.      * Add an embedded (inline) attachment from a file.
  2613.      * This can include images, sounds, and just about any other document type.
  2614.      * These differ from 'regular' attachments in that they are intended to be
  2615.      * displayed inline with the message, not just attached for download.
  2616.      * This is used in HTML messages that embed the images
  2617.      * the HTML refers to using the $cid value.
  2618.      * @param string $path Path to the attachment.
  2619.      * @param string $cid Content ID of the attachment; Use this to reference
  2620.      *        the content when using an embedded image in HTML.
  2621.      * @param string $name Overrides the attachment name.
  2622.      * @param string $encoding File encoding (see $Encoding).
  2623.      * @param string $type File MIME type.
  2624.      * @param string $disposition Disposition to use
  2625.      * @return boolean True on successfully adding an attachment
  2626.      */
  2627.     public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline')
  2628.     {
  2629.         if (!@is_file($path)) {
  2630.             $this->setError($this->lang('file_access') . $path);
  2631.             return false;
  2632.         }
  2633.  
  2634.         // If a MIME type is not specified, try to work it out from the file name
  2635.         if ($type == '') {
  2636.             $type = self::filenameToType($path);
  2637.         }
  2638.  
  2639.         $filename = basename($path);
  2640.         if ($name == '') {
  2641.             $name = $filename;
  2642.         }
  2643.  
  2644.         // Append to $attachment array
  2645.         $this->attachment[] = array(
  2646.             0 => $path,
  2647.             1 => $filename,
  2648.             2 => $name,
  2649.             3 => $encoding,
  2650.             4 => $type,
  2651.             5 => false, // isStringAttachment
  2652.             6 => $disposition,
  2653.             7 => $cid
  2654.         );
  2655.         return true;
  2656.     }
  2657.  
  2658.     /**
  2659.      * Add an embedded stringified attachment.
  2660.      * This can include images, sounds, and just about any other document type.
  2661.      * Be sure to set the $type to an image type for images:
  2662.      * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
  2663.      * @param string $string The attachment binary data.
  2664.      * @param string $cid Content ID of the attachment; Use this to reference
  2665.      *        the content when using an embedded image in HTML.
  2666.      * @param string $name
  2667.      * @param string $encoding File encoding (see $Encoding).
  2668.      * @param string $type MIME type.
  2669.      * @param string $disposition Disposition to use
  2670.      * @return boolean True on successfully adding an attachment
  2671.      */
  2672.     public function addStringEmbeddedImage(
  2673.         $string,
  2674.         $cid,
  2675.         $name = '',
  2676.         $encoding = 'base64',
  2677.         $type = '',
  2678.         $disposition = 'inline'
  2679.     ) {
  2680.         // If a MIME type is not specified, try to work it out from the name
  2681.         if ($type == '') {
  2682.             $type = self::filenameToType($name);
  2683.         }
  2684.  
  2685.         // Append to $attachment array
  2686.         $this->attachment[] = array(
  2687.             0 => $string,
  2688.             1 => $name,
  2689.             2 => $name,
  2690.             3 => $encoding,
  2691.             4 => $type,
  2692.             5 => true, // isStringAttachment
  2693.             6 => $disposition,
  2694.             7 => $cid
  2695.         );
  2696.         return true;
  2697.     }
  2698.  
  2699.     /**
  2700.      * Check if an inline attachment is present.
  2701.      * @access public
  2702.      * @return boolean
  2703.      */
  2704.     public function inlineImageExists()
  2705.     {
  2706.         foreach ($this->attachment as $attachment) {
  2707.             if ($attachment[6] == 'inline') {
  2708.                 return true;
  2709.             }
  2710.         }
  2711.         return false;
  2712.     }
  2713.  
  2714.     /**
  2715.      * Check if an attachment (non-inline) is present.
  2716.      * @return boolean
  2717.      */
  2718.     public function attachmentExists()
  2719.     {
  2720.         foreach ($this->attachment as $attachment) {
  2721.             if ($attachment[6] == 'attachment') {
  2722.                 return true;
  2723.             }
  2724.         }
  2725.         return false;
  2726.     }
  2727.  
  2728.     /**
  2729.      * Check if this message has an alternative body set.
  2730.      * @return boolean
  2731.      */
  2732.     public function alternativeExists()
  2733.     {
  2734.         return !empty($this->AltBody);
  2735.     }
  2736.  
  2737.     /**
  2738.      * Clear all To recipients.
  2739.      * @return void
  2740.      */
  2741.     public function clearAddresses()
  2742.     {
  2743.         foreach ($this->to as $to) {
  2744.             unset($this->all_recipients[strtolower($to[0])]);
  2745.         }
  2746.         $this->to = array();
  2747.     }
  2748.  
  2749.     /**
  2750.      * Clear all CC recipients.
  2751.      * @return void
  2752.      */
  2753.     public function clearCCs()
  2754.     {
  2755.         foreach ($this->cc as $cc) {
  2756.             unset($this->all_recipients[strtolower($cc[0])]);
  2757.         }
  2758.         $this->cc = array();
  2759.     }
  2760.  
  2761.     /**
  2762.      * Clear all BCC recipients.
  2763.      * @return void
  2764.      */
  2765.     public function clearBCCs()
  2766.     {
  2767.         foreach ($this->bcc as $bcc) {
  2768.             unset($this->all_recipients[strtolower($bcc[0])]);
  2769.         }
  2770.         $this->bcc = array();
  2771.     }
  2772.  
  2773.     /**
  2774.      * Clear all ReplyTo recipients.
  2775.      * @return void
  2776.      */
  2777.     public function clearReplyTos()
  2778.     {
  2779.         $this->ReplyTo = array();
  2780.     }
  2781.  
  2782.     /**
  2783.      * Clear all recipient types.
  2784.      * @return void
  2785.      */
  2786.     public function clearAllRecipients()
  2787.     {
  2788.         $this->to = array();
  2789.         $this->cc = array();
  2790.         $this->bcc = array();
  2791.         $this->all_recipients = array();
  2792.     }
  2793.  
  2794.     /**
  2795.      * Clear all filesystem, string, and binary attachments.
  2796.      * @return void
  2797.      */
  2798.     public function clearAttachments()
  2799.     {
  2800.         $this->attachment = array();
  2801.     }
  2802.  
  2803.     /**
  2804.      * Clear all custom headers.
  2805.      * @return void
  2806.      */
  2807.     public function clearCustomHeaders()
  2808.     {
  2809.         $this->CustomHeader = array();
  2810.     }
  2811.  
  2812.     /**
  2813.      * Add an error message to the error container.
  2814.      * @access protected
  2815.      * @param string $msg
  2816.      * @return void
  2817.      */
  2818.     protected function setError($msg)
  2819.     {
  2820.         $this->error_count++;
  2821.         if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
  2822.             $lasterror = $this->smtp->getError();
  2823.             if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
  2824.                 $msg .= '<p>' . $this->lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
  2825.             }
  2826.         }
  2827.         $this->ErrorInfo = $msg;
  2828.     }
  2829.  
  2830.     /**
  2831.      * Return an RFC 822 formatted date.
  2832.      * @access public
  2833.      * @return string
  2834.      * @static
  2835.      */
  2836.     public static function rfcDate()
  2837.     {
  2838.         // Set the time zone to whatever the default is to avoid 500 errors
  2839.         // Will default to UTC if it's not set properly in php.ini
  2840.         date_default_timezone_set(@date_default_timezone_get());
  2841.         return date('D, j M Y H:i:s O');
  2842.     }
  2843.  
  2844.     /**
  2845.      * Get the server hostname.
  2846.      * Returns 'localhost.localdomain' if unknown.
  2847.      * @access protected
  2848.      * @return string
  2849.      */
  2850.     protected function serverHostname()
  2851.     {
  2852.         $result = 'localhost.localdomain';
  2853.         if (!empty($this->Hostname)) {
  2854.             $result = $this->Hostname;
  2855.         } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) {
  2856.             $result = $_SERVER['SERVER_NAME'];
  2857.         } elseif (function_exists('gethostname') && gethostname() !== false) {
  2858.             $result = gethostname();
  2859.         } elseif (php_uname('n') !== false) {
  2860.             $result = php_uname('n');
  2861.         }
  2862.         return $result;
  2863.     }
  2864.  
  2865.     /**
  2866.      * Get an error message in the current language.
  2867.      * @access protected
  2868.      * @param string $key
  2869.      * @return string
  2870.      */
  2871.     protected function lang($key)
  2872.     {
  2873.         if (count($this->language) < 1) {
  2874.             $this->setLanguage('en'); // set the default language
  2875.         }
  2876.  
  2877.         if (isset($this->language[$key])) {
  2878.             return $this->language[$key];
  2879.         } else {
  2880.             return 'Language string failed to load: ' . $key;
  2881.         }
  2882.     }
  2883.  
  2884.     /**
  2885.      * Check if an error occurred.
  2886.      * @access public
  2887.      * @return boolean True if an error did occur.
  2888.      */
  2889.     public function isError()
  2890.     {
  2891.         return ($this->error_count > 0);
  2892.     }
  2893.  
  2894.     /**
  2895.      * Ensure consistent line endings in a string.
  2896.      * Changes every end of line from CRLF, CR or LF to $this->LE.
  2897.      * @access public
  2898.      * @param string $str String to fixEOL
  2899.      * @return string
  2900.      */
  2901.     public function fixEOL($str)
  2902.     {
  2903.         // Normalise to \n
  2904.         $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
  2905.         // Now convert LE as needed
  2906.         if ($this->LE !== "\n") {
  2907.             $nstr = str_replace("\n", $this->LE, $nstr);
  2908.         }
  2909.         return $nstr;
  2910.     }
  2911.  
  2912.     /**
  2913.      * Add a custom header.
  2914.      * $name value can be overloaded to contain
  2915.      * both header name and value (name:value)
  2916.      * @access public
  2917.      * @param string $name Custom header name
  2918.      * @param string $value Header value
  2919.      * @return void
  2920.      */
  2921.     public function addCustomHeader($name, $value = null)
  2922.     {
  2923.         if ($value === null) {
  2924.             // Value passed in as name:value
  2925.             $this->CustomHeader[] = explode(':', $name, 2);
  2926.         } else {
  2927.             $this->CustomHeader[] = array($name, $value);
  2928.         }
  2929.     }
  2930.  
  2931.     /**
  2932.      * Create a message from an HTML string.
  2933.      * Automatically makes modifications for inline images and backgrounds
  2934.      * and creates a plain-text version by converting the HTML.
  2935.      * Overwrites any existing values in $this->Body and $this->AltBody
  2936.      * @access public
  2937.      * @param string $message HTML message string
  2938.      * @param string $basedir baseline directory for path
  2939.      * @param boolean|callable $advanced Whether to use the internal HTML to text converter
  2940.      *    or your own custom converter @see html2text()
  2941.      * @return string $message
  2942.      */
  2943.     public function msgHTML($message, $basedir = '', $advanced = false)
  2944.     {
  2945.         preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
  2946.         if (isset($images[2])) {
  2947.             foreach ($images[2] as $imgindex => $url) {
  2948.                 // Convert data URIs into embedded images
  2949.                 if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) {
  2950.                     $data = substr($url, strpos($url, ','));
  2951.                     if ($match[2]) {
  2952.                         $data = base64_decode($data);
  2953.                     } else {
  2954.                         $data = rawurldecode($data);
  2955.                     }
  2956.                     $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
  2957.                     if ($this->addStringEmbeddedImage($data, $cid, '', 'base64', $match[1])) {
  2958.                         $message = str_replace(
  2959.                             $images[0][$imgindex],
  2960.                             $images[1][$imgindex] . '="cid:' . $cid . '"',
  2961.                             $message
  2962.                         );
  2963.                     }
  2964.                 } elseif (!preg_match('#^[A-z]+://#', $url)) {
  2965.                     // Do not change urls for absolute images (thanks to corvuscorax)
  2966.                     $filename = basename($url);
  2967.                     $directory = dirname($url);
  2968.                     if ($directory == '.') {
  2969.                         $directory = '';
  2970.                     }
  2971.                     $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
  2972.                     if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
  2973.                         $basedir .= '/';
  2974.                     }
  2975.                     if (strlen($directory) > 1 && substr($directory, -1) != '/') {
  2976.                         $directory .= '/';
  2977.                     }
  2978.                     if ($this->addEmbeddedImage(
  2979.                         $basedir . $directory . $filename,
  2980.                         $cid,
  2981.                         $filename,
  2982.                         'base64',
  2983.                         self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION))
  2984.                     )
  2985.                     ) {
  2986.                         $message = preg_replace(
  2987.                             '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
  2988.                             $images[1][$imgindex] . '="cid:' . $cid . '"',
  2989.                             $message
  2990.                         );
  2991.                     }
  2992.                 }
  2993.             }
  2994.         }
  2995.         $this->isHTML(true);
  2996.         // Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
  2997.         $this->Body = $this->normalizeBreaks($message);
  2998.         $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced));
  2999.         if (empty($this->AltBody)) {
  3000.             $this->AltBody = 'To view this email message, open it in a program that understands HTML!' .
  3001.                 self::CRLF . self::CRLF;
  3002.         }
  3003.         return $this->Body;
  3004.     }
  3005.  
  3006.     /**
  3007.      * Convert an HTML string into plain text.
  3008.      * This is used by msgHTML().
  3009.      * Note - older versions of this function used a bundled advanced converter
  3010.      * which was been removed for license reasons in #232
  3011.      * Example usage:
  3012.      * <code>
  3013.      * // Use default conversion
  3014.      * $plain = $mail->html2text($html);
  3015.      * // Use your own custom converter
  3016.      * $plain = $mail->html2text($html, function($html) {
  3017.      *     $converter = new MyHtml2text($html);
  3018.      *     return $converter->get_text();
  3019.      * });
  3020.      * </code>
  3021.      * @param string $html The HTML text to convert
  3022.      * @param boolean|callable $advanced Any boolean value to use the internal converter,
  3023.      *   or provide your own callable for custom conversion.
  3024.      * @return string
  3025.      */
  3026.     public function html2text($html, $advanced = false)
  3027.     {
  3028.         if (is_callable($advanced)) {
  3029.             return call_user_func($advanced, $html);
  3030.         }
  3031.         return html_entity_decode(
  3032.             trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
  3033.             ENT_QUOTES,
  3034.             $this->CharSet
  3035.         );
  3036.     }
  3037.  
  3038.     /**
  3039.      * Get the MIME type for a file extension.
  3040.      * @param string $ext File extension
  3041.      * @access public
  3042.      * @return string MIME type of file.
  3043.      * @static
  3044.      */
  3045.     public static function _mime_types($ext = '')
  3046.     {
  3047.         $mimes = array(
  3048.             'xl'    => 'application/excel',
  3049.             'js'    => 'application/javascript',
  3050.             'hqx'   => 'application/mac-binhex40',
  3051.             'cpt'   => 'application/mac-compactpro',
  3052.             'bin'   => 'application/macbinary',
  3053.             'doc'   => 'application/msword',
  3054.             'word'  => 'application/msword',
  3055.             'class' => 'application/octet-stream',
  3056.             'dll'   => 'application/octet-stream',
  3057.             'dms'   => 'application/octet-stream',
  3058.             'exe'   => 'application/octet-stream',
  3059.             'lha'   => 'application/octet-stream',
  3060.             'lzh'   => 'application/octet-stream',
  3061.             'psd'   => 'application/octet-stream',
  3062.             'sea'   => 'application/octet-stream',
  3063.             'so'    => 'application/octet-stream',
  3064.             'oda'   => 'application/oda',
  3065.             'pdf'   => 'application/pdf',
  3066.             'ai'    => 'application/postscript',
  3067.             'eps'   => 'application/postscript',
  3068.             'ps'    => 'application/postscript',
  3069.             'smi'   => 'application/smil',
  3070.             'smil'  => 'application/smil',
  3071.             'mif'   => 'application/vnd.mif',
  3072.             'xls'   => 'application/vnd.ms-excel',
  3073.             'ppt'   => 'application/vnd.ms-powerpoint',
  3074.             'wbxml' => 'application/vnd.wap.wbxml',
  3075.             'wmlc'  => 'application/vnd.wap.wmlc',
  3076.             'dcr'   => 'application/x-director',
  3077.             'dir'   => 'application/x-director',
  3078.             'dxr'   => 'application/x-director',
  3079.             'dvi'   => 'application/x-dvi',
  3080.             'gtar'  => 'application/x-gtar',
  3081.             'php3'  => 'application/x-httpd-php',
  3082.             'php4'  => 'application/x-httpd-php',
  3083.             'php'   => 'application/x-httpd-php',
  3084.             'phtml' => 'application/x-httpd-php',
  3085.             'phps'  => 'application/x-httpd-php-source',
  3086.             'swf'   => 'application/x-shockwave-flash',
  3087.             'sit'   => 'application/x-stuffit',
  3088.             'tar'   => 'application/x-tar',
  3089.             'tgz'   => 'application/x-tar',
  3090.             'xht'   => 'application/xhtml+xml',
  3091.             'xhtml' => 'application/xhtml+xml',
  3092.             'zip'   => 'application/zip',
  3093.             'mid'   => 'audio/midi',
  3094.             'midi'  => 'audio/midi',
  3095.             'mp2'   => 'audio/mpeg',
  3096.             'mp3'   => 'audio/mpeg',
  3097.             'mpga'  => 'audio/mpeg',
  3098.             'aif'   => 'audio/x-aiff',
  3099.             'aifc'  => 'audio/x-aiff',
  3100.             'aiff'  => 'audio/x-aiff',
  3101.             'ram'   => 'audio/x-pn-realaudio',
  3102.             'rm'    => 'audio/x-pn-realaudio',
  3103.             'rpm'   => 'audio/x-pn-realaudio-plugin',
  3104.             'ra'    => 'audio/x-realaudio',
  3105.             'wav'   => 'audio/x-wav',
  3106.             'bmp'   => 'image/bmp',
  3107.             'gif'   => 'image/gif',
  3108.             'jpeg'  => 'image/jpeg',
  3109.             'jpe'   => 'image/jpeg',
  3110.             'jpg'   => 'image/jpeg',
  3111.             'png'   => 'image/png',
  3112.             'tiff'  => 'image/tiff',
  3113.             'tif'   => 'image/tiff',
  3114.             'eml'   => 'message/rfc822',
  3115.             'css'   => 'text/css',
  3116.             'html'  => 'text/html',
  3117.             'htm'   => 'text/html',
  3118.             'shtml' => 'text/html',
  3119.             'log'   => 'text/plain',
  3120.             'text'  => 'text/plain',
  3121.             'txt'   => 'text/plain',
  3122.             'rtx'   => 'text/richtext',
  3123.             'rtf'   => 'text/rtf',
  3124.             'vcf'   => 'text/vcard',
  3125.             'vcard' => 'text/vcard',
  3126.             'xml'   => 'text/xml',
  3127.             'xsl'   => 'text/xml',
  3128.             'mpeg'  => 'video/mpeg',
  3129.             'mpe'   => 'video/mpeg',
  3130.             'mpg'   => 'video/mpeg',
  3131.             'mov'   => 'video/quicktime',
  3132.             'qt'    => 'video/quicktime',
  3133.             'rv'    => 'video/vnd.rn-realvideo',
  3134.             'avi'   => 'video/x-msvideo',
  3135.             'movie' => 'video/x-sgi-movie'
  3136.         );
  3137.         if (array_key_exists(strtolower($ext), $mimes)) {
  3138.             return $mimes[strtolower($ext)];
  3139.         }
  3140.         return 'application/octet-stream';
  3141.     }
  3142.  
  3143.     /**
  3144.      * Map a file name to a MIME type.
  3145.      * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
  3146.      * @param string $filename A file name or full path, does not need to exist as a file
  3147.      * @return string
  3148.      * @static
  3149.      */
  3150.     public static function filenameToType($filename)
  3151.     {
  3152.         // In case the path is a URL, strip any query string before getting extension
  3153.         $qpos = strpos($filename, '?');
  3154.         if (false !== $qpos) {
  3155.             $filename = substr($filename, 0, $qpos);
  3156.         }
  3157.         $pathinfo = self::mb_pathinfo($filename);
  3158.         return self::_mime_types($pathinfo['extension']);
  3159.     }
  3160.  
  3161.     /**
  3162.      * Multi-byte-safe pathinfo replacement.
  3163.      * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe.
  3164.      * Works similarly to the one in PHP >= 5.2.0
  3165.      * @link http://www.php.net/manual/en/function.pathinfo.php#107461
  3166.      * @param string $path A filename or path, does not need to exist as a file
  3167.      * @param integer|string $options Either a PATHINFO_* constant,
  3168.      *      or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2
  3169.      * @return string|array
  3170.      * @static
  3171.      */
  3172.     public static function mb_pathinfo($path, $options = null)
  3173.     {
  3174.         $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
  3175.         $pathinfo = array();
  3176.         if (preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo)) {
  3177.             if (array_key_exists(1, $pathinfo)) {
  3178.                 $ret['dirname'] = $pathinfo[1];
  3179.             }
  3180.             if (array_key_exists(2, $pathinfo)) {
  3181.                 $ret['basename'] = $pathinfo[2];
  3182.             }
  3183.             if (array_key_exists(5, $pathinfo)) {
  3184.                 $ret['extension'] = $pathinfo[5];
  3185.             }
  3186.             if (array_key_exists(3, $pathinfo)) {
  3187.                 $ret['filename'] = $pathinfo[3];
  3188.             }
  3189.         }
  3190.         switch ($options) {
  3191.             case PATHINFO_DIRNAME:
  3192.             case 'dirname':
  3193.                 return $ret['dirname'];
  3194.             case PATHINFO_BASENAME:
  3195.             case 'basename':
  3196.                 return $ret['basename'];
  3197.             case PATHINFO_EXTENSION:
  3198.             case 'extension':
  3199.                 return $ret['extension'];
  3200.             case PATHINFO_FILENAME:
  3201.             case 'filename':
  3202.                 return $ret['filename'];
  3203.             default:
  3204.                 return $ret;
  3205.         }
  3206.     }
  3207.  
  3208.     /**
  3209.      * Set or reset instance properties.
  3210.      * You should avoid this function - it's more verbose, less efficient, more error-prone and
  3211.      * harder to debug than setting properties directly.
  3212.      * Usage Example:
  3213.      * `$mail->set('SMTPSecure', 'tls');`
  3214.      *   is the same as:
  3215.      * `$mail->SMTPSecure = 'tls';`
  3216.      * @access public
  3217.      * @param string $name The property name to set
  3218.      * @param mixed $value The value to set the property to
  3219.      * @return boolean
  3220.      * @TODO Should this not be using the __set() magic function?
  3221.      */
  3222.     public function set($name, $value = '')
  3223.     {
  3224.         if (property_exists($this, $name)) {
  3225.             $this->$name = $value;
  3226.             return true;
  3227.         } else {
  3228.             $this->setError($this->lang('variable_set') . $name);
  3229.             return false;
  3230.         }
  3231.     }
  3232.  
  3233.     /**
  3234.      * Strip newlines to prevent header injection.
  3235.      * @access public
  3236.      * @param string $str
  3237.      * @return string
  3238.      */
  3239.     public function secureHeader($str)
  3240.     {
  3241.         return trim(str_replace(array("\r", "\n"), '', $str));
  3242.     }
  3243.  
  3244.     /**
  3245.      * Normalize line breaks in a string.
  3246.      * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
  3247.      * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
  3248.      * @param string $text
  3249.      * @param string $breaktype What kind of line break to use, defaults to CRLF
  3250.      * @return string
  3251.      * @access public
  3252.      * @static
  3253.      */
  3254.     public static function normalizeBreaks($text, $breaktype = "\r\n")
  3255.     {
  3256.         return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text);
  3257.     }
  3258.  
  3259.  
  3260.     /**
  3261.      * Set the public and private key files and password for S/MIME signing.
  3262.      * @access public
  3263.      * @param string $cert_filename
  3264.      * @param string $key_filename
  3265.      * @param string $key_pass Password for private key
  3266.      * @param string $extracerts_filename Optional path to chain certificate
  3267.      */
  3268.     public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
  3269.     {
  3270.         $this->sign_cert_file = $cert_filename;
  3271.         $this->sign_key_file = $key_filename;
  3272.         $this->sign_key_pass = $key_pass;
  3273.         $this->sign_extracerts_file = $extracerts_filename;
  3274.     }
  3275.  
  3276.     /**
  3277.      * Quoted-Printable-encode a DKIM header.
  3278.      * @access public
  3279.      * @param string $txt
  3280.      * @return string
  3281.      */
  3282.     public function DKIM_QP($txt)
  3283.     {
  3284.         $line = '';
  3285.         for ($i = 0; $i < strlen($txt); $i++) {
  3286.             $ord = ord($txt[$i]);
  3287.             if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
  3288.                 $line .= $txt[$i];
  3289.             } else {
  3290.                 $line .= '=' . sprintf('%02X', $ord);
  3291.             }
  3292.         }
  3293.         return $line;
  3294.     }
  3295.  
  3296.     /**
  3297.      * Generate a DKIM signature.
  3298.      * @access public
  3299.      * @param string $signHeader
  3300.      * @throws phpmailerException
  3301.      * @return string
  3302.      */
  3303.     public function DKIM_Sign($signHeader)
  3304.     {
  3305.         if (!defined('PKCS7_TEXT')) {
  3306.             if ($this->exceptions) {
  3307.                 throw new phpmailerException($this->lang('signing') . ' OpenSSL extension missing.');
  3308.             }
  3309.             return '';
  3310.         }
  3311.         $privKeyStr = file_get_contents($this->DKIM_private);
  3312.         if ($this->DKIM_passphrase != '') {
  3313.             $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  3314.         } else {
  3315.             $privKey = $privKeyStr;
  3316.         }
  3317.         if (openssl_sign($signHeader, $signature, $privKey)) {
  3318.             return base64_encode($signature);
  3319.         }
  3320.         return '';
  3321.     }
  3322.  
  3323.     /**
  3324.      * Generate a DKIM canonicalization header.
  3325.      * @access public
  3326.      * @param string $signHeader Header
  3327.      * @return string
  3328.      */
  3329.     public function DKIM_HeaderC($signHeader)
  3330.     {
  3331.         $signHeader = preg_replace('/\r\n\s+/', ' ', $signHeader);
  3332.         $lines = explode("\r\n", $signHeader);
  3333.         foreach ($lines as $key => $line) {
  3334.             list($heading, $value) = explode(':', $line, 2);
  3335.             $heading = strtolower($heading);
  3336.             $value = preg_replace('/\s+/', ' ', $value); // Compress useless spaces
  3337.             $lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value
  3338.         }
  3339.         $signHeader = implode("\r\n", $lines);
  3340.         return $signHeader;
  3341.     }
  3342.  
  3343.     /**
  3344.      * Generate a DKIM canonicalization body.
  3345.      * @access public
  3346.      * @param string $body Message Body
  3347.      * @return string
  3348.      */
  3349.     public function DKIM_BodyC($body)
  3350.     {
  3351.         if ($body == '') {
  3352.             return "\r\n";
  3353.         }
  3354.         // stabilize line endings
  3355.         $body = str_replace("\r\n", "\n", $body);
  3356.         $body = str_replace("\n", "\r\n", $body);
  3357.         // END stabilize line endings
  3358.         while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
  3359.             $body = substr($body, 0, strlen($body) - 2);
  3360.         }
  3361.         return $body;
  3362.     }
  3363.  
  3364.     /**
  3365.      * Create the DKIM header and body in a new message header.
  3366.      * @access public
  3367.      * @param string $headers_line Header lines
  3368.      * @param string $subject Subject
  3369.      * @param string $body Body
  3370.      * @return string
  3371.      */
  3372.     public function DKIM_Add($headers_line, $subject, $body)
  3373.     {
  3374.         $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
  3375.         $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  3376.         $DKIMquery = 'dns/txt'; // Query method
  3377.         $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  3378.         $subject_header = "Subject: $subject";
  3379.         $headers = explode($this->LE, $headers_line);
  3380.         $from_header = '';
  3381.         $to_header = '';
  3382.         $current = '';
  3383.         foreach ($headers as $header) {
  3384.             if (strpos($header, 'From:') === 0) {
  3385.                 $from_header = $header;
  3386.                 $current = 'from_header';
  3387.             } elseif (strpos($header, 'To:') === 0) {
  3388.                 $to_header = $header;
  3389.                 $current = 'to_header';
  3390.             } else {
  3391.                 if ($current && strpos($header, ' =?') === 0) {
  3392.                     $current .= $header;
  3393.                 } else {
  3394.                     $current = '';
  3395.                 }
  3396.             }
  3397.         }
  3398.         $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
  3399.         $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
  3400.         $subject = str_replace(
  3401.             '|',
  3402.             '=7C',
  3403.             $this->DKIM_QP($subject_header)
  3404.         ); // Copied header fields (dkim-quoted-printable)
  3405.         $body = $this->DKIM_BodyC($body);
  3406.         $DKIMlen = strlen($body); // Length of body
  3407.         $DKIMb64 = base64_encode(pack('H*', sha1($body))); // Base64 of packed binary SHA-1 hash of body
  3408.         if ('' == $this->DKIM_identity) {
  3409.             $ident = '';
  3410.         } else {
  3411.             $ident = ' i=' . $this->DKIM_identity . ';';
  3412.         }
  3413.         $dkimhdrs = 'DKIM-Signature: v=1; a=' .
  3414.             $DKIMsignatureType . '; q=' .
  3415.             $DKIMquery . '; l=' .
  3416.             $DKIMlen . '; s=' .
  3417.             $this->DKIM_selector .
  3418.             ";\r\n" .
  3419.             "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
  3420.             "\th=From:To:Subject;\r\n" .
  3421.             "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" .
  3422.             "\tz=$from\r\n" .
  3423.             "\t|$to\r\n" .
  3424.             "\t|$subject;\r\n" .
  3425.             "\tbh=" . $DKIMb64 . ";\r\n" .
  3426.             "\tb=";
  3427.         $toSign = $this->DKIM_HeaderC(
  3428.             $from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs
  3429.         );
  3430.         $signed = $this->DKIM_Sign($toSign);
  3431.         return $dkimhdrs . $signed . "\r\n";
  3432.     }
  3433.  
  3434.     /**
  3435.      * Allows for public read access to 'to' property.
  3436.      * @access public
  3437.      * @return array
  3438.      */
  3439.     public function getToAddresses()
  3440.     {
  3441.         return $this->to;
  3442.     }
  3443.  
  3444.     /**
  3445.      * Allows for public read access to 'cc' property.
  3446.      * @access public
  3447.      * @return array
  3448.      */
  3449.     public function getCcAddresses()
  3450.     {
  3451.         return $this->cc;
  3452.     }
  3453.  
  3454.     /**
  3455.      * Allows for public read access to 'bcc' property.
  3456.      * @access public
  3457.      * @return array
  3458.      */
  3459.     public function getBccAddresses()
  3460.     {
  3461.         return $this->bcc;
  3462.     }
  3463.  
  3464.     /**
  3465.      * Allows for public read access to 'ReplyTo' property.
  3466.      * @access public
  3467.      * @return array
  3468.      */
  3469.     public function getReplyToAddresses()
  3470.     {
  3471.         return $this->ReplyTo;
  3472.     }
  3473.  
  3474.     /**
  3475.      * Allows for public read access to 'all_recipients' property.
  3476.      * @access public
  3477.      * @return array
  3478.      */
  3479.     public function getAllRecipientAddresses()
  3480.     {
  3481.         return $this->all_recipients;
  3482.     }
  3483.  
  3484.     /**
  3485.      * Perform a callback.
  3486.      * @param boolean $isSent
  3487.      * @param array $to
  3488.      * @param array $cc
  3489.      * @param array $bcc
  3490.      * @param string $subject
  3491.      * @param string $body
  3492.      * @param string $from
  3493.      */
  3494.     protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from)
  3495.     {
  3496.         if (!empty($this->action_function) && is_callable($this->action_function)) {
  3497.             $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
  3498.             call_user_func_array($this->action_function, $params);
  3499.         }
  3500.     }
  3501. }
  3502.  
  3503. /**
  3504.  * PHPMailer exception handler
  3505.  * @package PHPMailer
  3506.  */
  3507. class phpmailerException extends Exception
  3508. {
  3509.     /**
  3510.      * Prettify error message output
  3511.      * @return string
  3512.      */
  3513.     public function errorMessage()
  3514.     {
  3515.         $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
  3516.         return $errorMsg;
  3517.     }
  3518. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top