Guest User

phpmailer.class.php

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